From 343cb4c2dd168642d97fa54572065c7d925f0152 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Tue, 17 Nov 2026 18:50:38 -0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(build-providers):=20buildProviders=201?= =?UTF-8?q?=20=E6=8C=89=E6=BA=90=E6=96=87=E4=BB=B6=E6=89=BE=E8=BF=90?= =?UTF-8?q?=E8=A1=8C=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs 1lck/Lithe-IDEA#2104 Co-Authored-By: Claude Opus 5.5 --- rust/contracts/rust-core-api.md | 12 +- rust/crates/build/src/commands.rs | 28 +++ rust/crates/build/src/lib.rs | 1 + rust/crates/build/src/manifest.rs | 6 + rust/crates/build/src/manifest/run.rs | 25 ++ rust/crates/build/src/run_entrypoints.rs | 153 +++++++++++++ rust/crates/build/src/run_preparation.rs | 53 +++-- rust/crates/core/src/protocol/command.rs | 6 + .../core/src/runtime/dispatcher/build.rs | 10 + rust/crates/core/src/tests/build_systems.rs | 125 +++++++++- .../core/src/tests/run_configuration.rs | 61 +++++ .../execution/src/configuration/document.rs | 8 +- .../execution/src/configuration/editing.rs | 26 ++- .../execution/src/configuration/requests.rs | 4 + rust/crates/lsp-client/src/build_provider.rs | 10 +- rust/crates/plugin-manifest/src/validation.rs | 14 ++ rust/crates/plugin-model/src/capabilities.rs | 4 +- shared/plugins/contract/v1/README.md | 67 +++++- ...build-provider-run-entrypoints.plugin.json | 216 ++++++++++++++++++ .../build-run-entrypoints.json | 68 ++++++ .../contract/v1/plugin-manifest.schema.json | 21 ++ .../reference/capabilities-and-versions.md | 4 + .../github/litheidea/plugin/sdk/Backend.java | 21 +- .../litheidea/plugin/sdk/Diagnostics.java | 1 + .../github/litheidea/plugin/sdk/Protocol.java | 8 +- .../litheidea/plugin/sdk/BuildTest.java | 20 +- shared/plugins/sdk/node/src/backend.mjs | 9 +- shared/plugins/sdk/node/src/diagnostics.mjs | 2 +- shared/plugins/sdk/node/src/index.d.ts | 9 + shared/plugins/sdk/node/src/protocol.mjs | 4 +- shared/plugins/sdk/node/test/build.test.mjs | 14 +- .../sdk/rust/plugin-sdk/src/diagnostics.rs | 1 + 32 files changed, 949 insertions(+), 62 deletions(-) create mode 100644 rust/crates/build/src/run_entrypoints.rs create mode 100644 shared/plugins/contract/v1/fixtures/build-providers/build-provider-run-entrypoints.plugin.json create mode 100644 shared/plugins/contract/v1/fixtures/build-providers/build-run-entrypoints.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 0609c797..a3889728 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -535,6 +535,8 @@ or removing a command fails until the table changes in the same commit. | `build.decodeRunPreparation` | Validate portable launch data before the native Run host starts a process | | `build.testDiscoveryPlan` | Plan opt-in Provider test discovery for an instance | | `build.decodeTestDiscovery` | Validate, deduplicate and order Provider test selectors | +| `build.runEntrypointsPlan` | Plan a Provider request for the run entrypoints of one source file (`buildProviders` 1) | +| `build.decodeRunEntrypoints` | Validate and deduplicate the run entrypoints a Provider named | | `build.dependencyPlan` | Expand the command that prints a project's dependency tree, or the request a build provider answers | | `build.decodeModel` | Decode model output or a provider result into projects, targets, tasks, content roots, option values, and run entries | | `build.decodeTestResults` | Decode a test run's reports and output into per-case results and a summary | @@ -3671,7 +3673,11 @@ and Core preserves them unchanged. Provider applications can be explicitly saved with `runConfig.createUserConfiguration` using `{root,scope:"local",name,type:"buildProvider",build:{pluginID,buildSystemID, -root,run,projectID,targetID,userArguments?,execution?}}`. Core upserts the existing local +root,run,projectID,targetID,userArguments?,execution?},entrypoint?}`. An entrypoint run +(`buildProviders` 1) has an empty `targetID` and names `entrypoint`, the opaque +`launchOptions.entrypoint` a provider found with `build.decodeRunEntrypoints`; Core saves it as +`extensions.build-run.entrypoint`, and the entrypoint is part of the selector identity, so each +entrypoint is its own configuration. Core upserts the existing local reference by selector identity and retains its existing ID (new references use `user:` IDs), unrelated configurations and project toolchain defaults. `extensions.build` in Run v2 holds the typed reference; optional execution is application/service/task and must match the current @@ -4937,7 +4943,9 @@ and the directories are absolute host paths used only as substitution text. | `build.testPlan` | plan fields plus `project?`, `target?`, `suite?`, `case?`, `userArguments?`, `projects?` (the model's project directories) | command plan or `provider: {method: "lithe/build/test", params}`, plus `results`: `null`, `{ decoder, reports }` with workspace-relative globs (for the selected project, or for the root and every listed project when none is selected), or command-only `{ decoder: "hostIntegration" }`. Command filters that templates cannot place, such as a case without its suite when the tool only addresses `Suite#case`, are `plugin.build.invalidSelection`; Provider filters remain separate typed values and must be declared supported | | `build.testDiscoveryPlan` | common plan fields plus `refresh?`, `tool?`; no project/output file | `plan.provider` for `lithe/build/discoverTests`, only with `test.discovery: true`, using the same effective options and effect metadata | | `build.decodeTestDiscovery` | common plan fields plus canonical `result` | `discovery.tests` with validated `{id, suite, case, project?, target?}` selectors; bounded at 10,000 items/32 MiB, deterministic and exactly runnable; malformed replies reject in full | -| `build.prepareRunPlan` | common plan fields, `run`, required `project`/`target`, `userArguments?`, `launchOptions?`, `workspaceRoot?` (required for an explicit launch cwd); no output file | `plan.provider` for `lithe/build/prepareRun`, selected declaration/tags/paths/options validated; typed launch options must match the run's declared execution kind, and a service or task run requires them | +| `build.runEntrypointsPlan` | common plan fields plus `file` (workspace-relative, inside the instance), `refresh?`, `tool?`; no project/output file | `plan.provider` for `lithe/build/runEntrypoints` with `file`, only when a run declares `entrypoints: true`; decoder `litheRunEntrypoints` | +| `build.decodeRunEntrypoints` | common plan fields plus canonical `result` | `entrypoints.entrypoints`: `[{run, name, entrypoint, project:{name, path}}]` in the provider's order without exact duplicates; at most 64; each names an entrypoint run, a 1–256 byte name, a 1–4,096 byte entrypoint and a project inside the instance; malformed replies reject in full with `plugin.build.invalidOutput` | +| `build.prepareRunPlan` | common plan fields, `run`, required `project`, `target` (required for a target run, refused for an entrypoint run), `userArguments?`, `launchOptions?`, `workspaceRoot?` (required for an explicit launch cwd); no output file | `plan.provider` for `lithe/build/prepareRun`, selected declaration/tags/paths/options validated; typed launch options must match the run's declared execution kind, a service or task run requires them, and an entrypoint run requires `launchOptions.entrypoint` and sends no `target` | | `build.decodeRunPreparation` | `workspaceRoot`, instance `root`, raw `result`, same optional `launchOptions` | `launch` with portable `{executable:{kind,value},arguments,workingDirectory,environment}`; bounded strings and workspace directory containment, `plugin.build.invalidOutput` on invalid result | | `build.prepareDebugPlan` | same selected fields as `build.prepareRunPlan`; run declares same-plugin `debug.adapter` | `plan.provider` for `lithe/build/prepareDebug`; no cross-package reference, and launch options are refused: they apply only to running a target | | `build.decodeDebugPreparation` | `workspaceRoot`, instance `root`, selected `run`, raw `result` | `preparation` with declaration-owned `adapter`, normalized `root`, `program`, `arguments`, `workingDirectory`, `environment`; program is an existing regular file contained in the instance after canonicalization | diff --git a/rust/crates/build/src/commands.rs b/rust/crates/build/src/commands.rs index a145f46f..ccdc80d0 100644 --- a/rust/crates/build/src/commands.rs +++ b/rust/crates/build/src/commands.rs @@ -214,6 +214,34 @@ pub fn build_decode_test_discovery_command( ) } +/// `build.runEntrypointsPlan`: asks the provider which entrypoints a file holds. +pub fn build_run_entrypoints_plan_command( + payload: Value, +) -> Result { + with_build_system::( + payload, + "build.runEntrypointsPlan", + "plan", + |build_system, request: &super::run_entrypoints::RunEntrypointsPlanRequest| { + super::run_entrypoints::plan(build_system, request) + }, + ) +} + +/// `build.decodeRunEntrypoints`: the entrypoints the host may save and start. +pub fn build_decode_run_entrypoints_command( + payload: Value, +) -> Result { + with_build_system::( + payload, + "build.decodeRunEntrypoints", + "entrypoints", + |build_system, request: &super::run_entrypoints::DecodeRunEntrypointsRequest| { + super::run_entrypoints::decode(build_system, request) + }, + ) +} + /// `build.prepareRunPlan`: validates a provider-owned target launch request. pub fn build_prepare_run_plan_command( payload: Value, diff --git a/rust/crates/build/src/lib.rs b/rust/crates/build/src/lib.rs index 66eea3a2..f571e923 100644 --- a/rust/crates/build/src/lib.rs +++ b/rust/crates/build/src/lib.rs @@ -29,6 +29,7 @@ mod options; mod outputs; mod plans; mod project_options; +mod run_entrypoints; mod run_preparation; mod run_start; mod select; diff --git a/rust/crates/build/src/manifest.rs b/rust/crates/build/src/manifest.rs index f41c1aab..7b089098 100644 --- a/rust/crates/build/src/manifest.rs +++ b/rust/crates/build/src/manifest.rs @@ -177,6 +177,12 @@ pub fn validate_declarations( } impl BuildSystemDeclaration { + /// Whether a run starts entrypoints the provider finds in files, which + /// `buildProviders` 1 introduced. + pub fn has_run_entrypoints(&self) -> bool { + self.run.iter().any(|run| run.entrypoints) + } + /// Folder names every workspace hides at any depth while the plugin is /// enabled (`layout.hiddenDirectoryNames`), sorted and unique once validated. pub fn hidden_directory_names(&self) -> &[String] { diff --git a/rust/crates/build/src/manifest/run.rs b/rust/crates/build/src/manifest/run.rs index 2cb9495d..d1963499 100644 --- a/rust/crates/build/src/manifest/run.rs +++ b/rust/crates/build/src/manifest/run.rs @@ -30,6 +30,11 @@ pub(crate) struct RunDeclaration { /// Metadata stored under `extensions.` of the entry. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(crate) extension: BTreeMap, + /// `buildProviders` 1: the provider names entrypoints in source files + /// (`lithe/build/runEntrypoints`), and the run starts one of them in a + /// project. It applies to no target and is never listed per target. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub(crate) entrypoints: bool, } /// Native launch binds a local adapter; connection attach names a public registry type. @@ -108,6 +113,26 @@ impl BuildSystemDeclaration { "Debug preparation requires a provider run.", )); } + if run.entrypoints { + if run.source != TaskSource::Provider + || run.from_targets.is_some() + || run.from_tasks.is_some() + || !run.arguments.is_empty() + || !run.extension.is_empty() + || run.execution.unwrap_or(BuildExecution::Application) + != BuildExecution::Application + || run.debug.is_some() + || run.name.as_ref().is_some_and(|name| { + name.trim().is_empty() || name.len() > MAX_TEXT || name.contains("${") + }) + { + return Err(invalid( + &field, + "Entrypoint runs are provider applications without targets, templates or debug.", + )); + } + continue; + } if run.source == TaskSource::Provider { let valid_targets = run.from_targets.as_ref().is_some_and(|from| { !from.tags.is_empty() diff --git a/rust/crates/build/src/run_entrypoints.rs b/rust/crates/build/src/run_entrypoints.rs new file mode 100644 index 00000000..0c982dda --- /dev/null +++ b/rust/crates/build/src/run_entrypoints.rs @@ -0,0 +1,153 @@ +//! Entrypoints a provider finds in one source file (`buildProviders` 1). +//! +//! A run declared with `entrypoints: true` starts an entrypoint the provider +//! names, such as a class with a `main` method, in one of its projects. Core +//! never reads the source: the provider answers `lithe/build/runEntrypoints` +//! for a file and Core checks that every answer is something the run can +//! start, so the host can save and start it as an ordinary provider run. + +use super::decode::{invalid_output, MAX_OUTPUT_BYTES}; +use super::manifest::{BuildSystemDeclaration, TaskSource}; +use super::plans::{self, OutputPlanRequest, PlanBase, SelectedEntity}; +use lithe_plugin_model::Validation; +use serde::Deserialize; +use serde_json::{json, Value}; + +/// Version of the `litheRunEntrypoints` document a provider returns. +const ENTRYPOINTS_VERSION: u64 = 0; + +/// Most entrypoints one file may name. +const MAX_ENTRYPOINTS: usize = 64; + +/// Longest entrypoint name, in bytes. +const MAX_NAME: usize = 256; + +/// Longest opaque entrypoint, in bytes, as `launchOptions.entrypoint` allows. +const MAX_ENTRYPOINT: usize = 4096; + +/// The source file whose entrypoints the host asks for. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct RunEntrypointsPlanRequest { + #[serde(flatten)] + pub(crate) base: OutputPlanRequest, + /// Workspace-relative file inside the instance root. + pub(crate) file: String, +} + +/// The plan's configuration and the provider's answer. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct DecodeRunEntrypointsRequest { + #[serde(flatten)] + pub(crate) base: PlanBase, + pub(crate) result: Value, +} + +/// One entrypoint as the provider names it. +#[derive(Deserialize)] +struct Entrypoint { + run: String, + name: String, + entrypoint: String, + project: SelectedEntity, +} + +fn has_entrypoint_run(build_system: &BuildSystemDeclaration) -> bool { + build_system + .run + .iter() + .any(|run| run.entrypoints && run.source == TaskSource::Provider) +} + +/// `build.runEntrypointsPlan`: asks the provider which entrypoints `file` holds. +pub(crate) fn plan( + build_system: &BuildSystemDeclaration, + request: &RunEntrypointsPlanRequest, +) -> Validation { + if !has_entrypoint_run(build_system) { + return Err(plans::unavailable(build_system, "run entrypoints")); + } + if request.base.project.is_some() || request.base.output_file.is_some() { + return Err(plans::invalid_selection( + "Run entrypoints are found by file, not by project.", + )); + } + let context = plans::PlanContext::new(build_system, &request.base.base)?; + let file = super::decode::request_path(&request.file, "file")?; + if super::decode::relative_to(&context.root, &file).is_none_or(|relative| relative == ".") { + return Err(plans::invalid_selection( + "The file is outside the build-system root.", + )); + } + let mut params = plans::provider_hints(&request.base)?; + params.insert("file".to_string(), json!(file)); + let provider = build_system + .provider + .as_ref() + .ok_or_else(|| plans::unavailable(build_system, "a provider"))?; + Ok(context.provider_plan( + provider, + "lithe/build/runEntrypoints", + "litheRunEntrypoints", + params, + )) +} + +/// `build.decodeRunEntrypoints`: the entrypoints the host may save and start, in +/// the provider's order without duplicates. A malformed answer is refused whole. +pub(crate) fn decode( + build_system: &BuildSystemDeclaration, + request: &DecodeRunEntrypointsRequest, +) -> Validation { + if !has_entrypoint_run(build_system) { + return Err(plans::unavailable(build_system, "run entrypoints")); + } + let context = plans::PlanContext::new(build_system, &request.base)?; + let result = &request.result; + if serde_json::to_vec(result).map_or(usize::MAX, |bytes| bytes.len()) > MAX_OUTPUT_BYTES + || result["format"] != "litheRunEntrypoints" + || result["version"] != ENTRYPOINTS_VERSION + { + return Err(invalid_output("Invalid run entrypoints document.")); + } + let items = result["entrypoints"] + .as_array() + .filter(|items| items.len() <= MAX_ENTRYPOINTS) + .ok_or_else(|| invalid_output("Run entrypoints hold at most 64 entries."))?; + let mut entrypoints: Vec = Vec::new(); + for item in items { + let entry: Entrypoint = serde_json::from_value(item.clone()) + .map_err(|_| invalid_output("Invalid run entrypoint."))?; + let runnable = build_system.run.iter().any(|run| { + run.id == entry.run && run.entrypoints && run.source == TaskSource::Provider + }); + let name = entry.name.trim(); + if !runnable + || name.is_empty() + || name.len() > MAX_NAME + || name.chars().any(char::is_control) + || entry.entrypoint.is_empty() + || entry.entrypoint.len() > MAX_ENTRYPOINT + || entry.entrypoint.contains('\0') + { + return Err(invalid_output( + "A run entrypoint names a run, a name or an entrypoint this build system cannot start.", + )); + } + let project = + plans::selection(&entry.project, &context.root, None, "project").map_err(|_| { + invalid_output("A run entrypoint's project is outside the build-system root.") + })?; + let decoded = json!({ + "run": entry.run, + "name": name, + "entrypoint": entry.entrypoint, + "project": {"name": project.name, "path": project.path}, + }); + if !entrypoints.contains(&decoded) { + entrypoints.push(decoded); + } + } + Ok(json!({ "entrypoints": entrypoints })) +} diff --git a/rust/crates/build/src/run_preparation.rs b/rust/crates/build/src/run_preparation.rs index a4213775..8aec3067 100644 --- a/rust/crates/build/src/run_preparation.rs +++ b/rust/crates/build/src/run_preparation.rs @@ -159,7 +159,9 @@ pub(crate) struct PrepareRunRequest { #[serde(flatten)] pub(crate) base: OutputPlanRequest, pub(crate) run: String, - pub(crate) target: SelectedEntity, + /// The target of a target run; an entrypoint run has none. + #[serde(default)] + pub(crate) target: Option, #[serde(default)] pub(crate) user_arguments: Vec, #[serde(default)] @@ -219,21 +221,37 @@ pub(crate) fn plan( .as_ref() .ok_or_else(|| plans::invalid_selection("A run target needs its project."))?; let project = plans::selection(project, &context.root, None, "project")?; - let target = plans::selection( - &request.target, - &context.root, - Some(&project.path), - "target", - )?; - if !declaration - .from_targets - .as_ref() - .is_some_and(|from| target.tags.iter().any(|tag| from.tags.contains(tag))) - { - return Err(plans::invalid_selection( - "This run does not apply to the selected target.", - )); - } + let target = if declaration.entrypoints { + // An entrypoint run starts the provider's entrypoint in the project; it + // has no target, and without an entrypoint there is nothing to start. + if request.target.is_some() + || !request + .launch_options + .as_ref() + .is_some_and(|options| options.entrypoint.is_some()) + { + return Err(plans::invalid_selection( + "An entrypoint run needs an entrypoint and no target.", + )); + } + None + } else { + let target = request + .target + .as_ref() + .ok_or_else(|| plans::invalid_selection("A target run needs its target."))?; + let target = plans::selection(target, &context.root, Some(&project.path), "target")?; + if !declaration + .from_targets + .as_ref() + .is_some_and(|from| target.tags.iter().any(|tag| from.tags.contains(tag))) + { + return Err(plans::invalid_selection( + "This run does not apply to the selected target.", + )); + } + Some(target) + }; plans::check_argument_limits(&request.user_arguments)?; let mut params = plans::provider_hints(&request.base)?; params.insert("run".to_string(), json!(declaration.id)); @@ -241,7 +259,8 @@ pub(crate) fn plan( if let Some(options) = &request.launch_options { params.insert("launchOptions".to_string(), json!(options)); } - for (name, selected) in [("project", project), ("target", target)] { + for (name, selected) in [("project", Some(project)), ("target", target)] { + let Some(selected) = selected else { continue }; params.insert( name.to_string(), json!({"name":selected.name,"path":selected.path, diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 72b194cb..dcbfea45 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -472,6 +472,10 @@ pub enum BuildCommand { TestDiscoveryPlan, /// Validates provider-owned test selectors (`build.decodeTestDiscovery`). DecodeTestDiscovery, + /// Asks a provider for the entrypoints of a file (`build.runEntrypointsPlan`). + RunEntrypointsPlan, + /// Validates the entrypoints a provider found (`build.decodeRunEntrypoints`). + DecodeRunEntrypoints, /// Expands the command that prints a project's dependencies (`build.dependencyPlan`). DependencyPlan, /// Normalizes a build model and derives its run entries (`build.decodeModel`). @@ -1175,6 +1179,8 @@ impl CoreCommand { "build.decodeRunPreparation" => Some(Self::Build(BuildCommand::DecodeRunPreparation)), "build.testDiscoveryPlan" => Some(Self::Build(BuildCommand::TestDiscoveryPlan)), "build.decodeTestDiscovery" => Some(Self::Build(BuildCommand::DecodeTestDiscovery)), + "build.runEntrypointsPlan" => Some(Self::Build(BuildCommand::RunEntrypointsPlan)), + "build.decodeRunEntrypoints" => Some(Self::Build(BuildCommand::DecodeRunEntrypoints)), "build.dependencyPlan" => Some(Self::Build(BuildCommand::DependencyPlan)), "build.decodeModel" => Some(Self::Build(BuildCommand::DecodeModel)), "build.decodeTestResults" => Some(Self::Build(BuildCommand::DecodeTestResults)), diff --git a/rust/crates/core/src/runtime/dispatcher/build.rs b/rust/crates/core/src/runtime/dispatcher/build.rs index 8e1e2fb1..45c03668 100644 --- a/rust/crates/core/src/runtime/dispatcher/build.rs +++ b/rust/crates/core/src/runtime/dispatcher/build.rs @@ -111,6 +111,16 @@ pub(super) fn dispatch(command: BuildCommand, id: Option, payload: Value payload, crate::build::build_decode_test_discovery_command::, ), + BuildCommand::RunEntrypointsPlan => plugin_response( + id, + payload, + crate::build::build_run_entrypoints_plan_command::, + ), + BuildCommand::DecodeRunEntrypoints => plugin_response( + id, + payload, + crate::build::build_decode_run_entrypoints_command::, + ), BuildCommand::DependencyPlan => plugin_response( id, payload, diff --git a/rust/crates/core/src/tests/build_systems.rs b/rust/crates/core/src/tests/build_systems.rs index e79e2afb..631beb64 100644 --- a/rust/crates/core/src/tests/build_systems.rs +++ b/rust/crates/core/src/tests/build_systems.rs @@ -5,10 +5,11 @@ use super::support::temporary_root; use crate::build::{ build_check_tool_version_command, build_decode_dependencies_command, build_decode_diagnostics_command, build_decode_model_command, - build_decode_run_preparation_command, build_decode_test_discovery_command, - build_decode_test_results_command, build_dependency_plan_command, build_detect_command, - build_invocation_plan_command, build_model_plan_command, build_prepare_run_plan_command, - build_resolve_options_command, build_sync_fingerprint_command, build_task_plan_command, + build_decode_run_entrypoints_command, build_decode_run_preparation_command, + build_decode_test_discovery_command, build_decode_test_results_command, + build_dependency_plan_command, build_detect_command, build_invocation_plan_command, + build_model_plan_command, build_prepare_run_plan_command, build_resolve_options_command, + build_run_entrypoints_plan_command, build_sync_fingerprint_command, build_task_plan_command, build_test_discovery_plan_command, build_test_plan_command, }; use crate::protocol::ErrorCode; @@ -2319,6 +2320,122 @@ fn provider_test_discovery_is_bounded_deterministic_and_runnable() { assert_eq!(validate(missing_filter)["status"], "rejected"); } +/// buildProviders 1: a provider names the entrypoints of a file, each of which an +/// entrypoint run starts in its project without a target. Malformed answers are +/// refused whole, and a manifest needs buildProviders 1 to declare such a run. +#[test] +fn provider_run_entrypoints_are_found_by_file_and_start_without_a_target() { + let manifest: Value = serde_json::from_str(contract_file!( + "fixtures/build-providers/build-provider-run-entrypoints.plugin.json" + )) + .unwrap(); + let fixture: Value = serde_json::from_str(contract_file!( + "fixtures/build-providers/build-run-entrypoints.json" + )) + .unwrap(); + assert_eq!(validate(manifest.clone())["status"], "ok"); + let mut old = manifest.clone(); + old["requires"]["buildProviders"] = json!(0); + let refused = validate(old); + assert_eq!( + refused["error"]["field"], "requires.buildProviders", + "{refused}" + ); + for (field, value) in [ + ("fromTargets", json!({"tags":["application"]})), + ("execution", json!("service")), + ("source", json!("command")), + ] { + let mut invalid = manifest.clone(); + invalid["buildSystems"][0]["run"][1][field] = value; + assert_eq!(validate(invalid)["status"], "rejected", "{field}"); + } + + let plan = |request: Value| { + build_run_entrypoints_plan_command::( + json!({"manifest":manifest,"buildSystemID":"gradle","request":request}), + ) + .unwrap() + }; + let planned = plan(fixture["plan"].clone()); + assert_eq!(planned["status"], "ok", "{planned}"); + let provider = &planned["plan"]["provider"]; + assert_eq!(provider["method"], "lithe/build/runEntrypoints"); + assert_eq!(provider["params"]["file"], fixture["plan"]["file"]); + assert_eq!(planned["plan"]["decoder"], "litheRunEntrypoints"); + for file in ["../outside/Tool.java", "/abs/Tool.java", "."] { + let mut request = fixture["plan"].clone(); + request["file"] = json!(file); + assert_eq!(plan(request)["status"], "rejected", "{file}"); + } + let mut by_project = fixture["plan"].clone(); + by_project["project"] = json!({"name":"app","path":"app"}); + assert_eq!(plan(by_project)["status"], "rejected"); + + let decode = |result: Value| { + build_decode_run_entrypoints_command::(json!({"manifest":manifest, + "buildSystemID":"gradle","request":{"root":".","result":result}})) + .unwrap() + }; + let decoded = decode(fixture["result"].clone()); + assert_eq!(decoded["status"], "ok", "{decoded}"); + assert_eq!( + decoded["entrypoints"]["entrypoints"], + fixture["entrypoints"] + ); + let mut repeated = fixture["result"].clone(); + repeated["entrypoints"] + .as_array_mut() + .unwrap() + .push(fixture["result"]["entrypoints"][0].clone()); + assert_eq!(decode(repeated), decoded); + let entry = |run: &str, name: &str, entrypoint: &str, path: &str| { + json!({"format":"litheRunEntrypoints","version":0,"entrypoints":[ + {"run":run,"name":name,"entrypoint":entrypoint,"project":{"name":"app","path":path}}]}) + }; + for invalid in [ + json!({"format":"litheRunEntrypoints","version":1,"entrypoints":[]}), + json!({"format":"litheRunEntrypoints","version":0,"entrypoints":vec![fixture["entrypoints"][0].clone();65]}), + entry("application", "Tool", "example.Tool", "app"), + entry("main", " ", "example.Tool", "app"), + entry("main", "Tool", "", "app"), + entry("main", "Tool", "bad\u{0}", "app"), + entry("main", "Tool", "example.Tool", "../escape"), + ] { + let rejected = decode(invalid); + assert_eq!( + rejected["error"]["code"], "plugin.build.invalidOutput", + "{rejected}" + ); + } + + let prepare = |request: Value| { + build_prepare_run_plan_command::( + json!({"manifest":manifest,"buildSystemID":"gradle","request":request}), + ) + .unwrap() + }; + let prepared = prepare(fixture["prepareRun"].clone()); + assert_eq!(prepared["status"], "ok", "{prepared}"); + let params = &prepared["plan"]["provider"]["params"]; + assert_eq!(params["run"], "main"); + assert!(params.get("target").is_none(), "{params}"); + assert_eq!(params["launchOptions"]["entrypoint"], "example.Tool"); + let mut without_entrypoint = fixture["prepareRun"].clone(); + without_entrypoint["launchOptions"] + .as_object_mut() + .unwrap() + .remove("entrypoint"); + assert_eq!(prepare(without_entrypoint)["status"], "rejected"); + let mut with_target = fixture["prepareRun"].clone(); + with_target["target"] = json!({"name":"Main","path":"app","tags":["application"]}); + assert_eq!(prepare(with_target)["status"], "rejected"); + let mut target_run = fixture["prepareRun"].clone(); + target_run["run"] = json!("application"); + target_run.as_object_mut().unwrap().remove("launchOptions"); + assert_eq!(prepare(target_run)["status"], "rejected"); +} + /// Preparation is a typed provider request, never an empty argv configuration. #[test] fn provider_run_preparation_selects_targets_and_validates_launch_data() { diff --git a/rust/crates/core/src/tests/run_configuration.rs b/rust/crates/core/src/tests/run_configuration.rs index c0b082d8..2a1a8bb7 100644 --- a/rust/crates/core/src/tests/run_configuration.rs +++ b/rust/crates/core/src/tests/run_configuration.rs @@ -2077,3 +2077,64 @@ fn powershell_and_program_editors_store_their_own_choices() { serde_json::json!([{"field":"program","code":"notFound"}]) ); } + +/// An entrypoint run (`buildProviders` 1) is saved without a target, with the +/// entrypoint it starts; each entrypoint is its own configuration, saving the +/// same one again reuses it, and the launch inputs carry the entrypoint. +#[test] +fn entrypoint_runs_are_saved_per_entrypoint_without_a_target() { + let root = temporary_root("saved-entrypoint-run"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(root.join("app")).unwrap(); + let plugin_path = ".lithe/run/plugin/dev.example.gradle.local.toml"; + let reference = serde_json::json!({ + "pluginID": "dev.example.gradle", "buildSystemID": "gradle", "root": "app", + "run": "main", "projectID": "project-id", "userArguments": [] + }); + let save = |name: &str, entrypoint: &str| { + run_config_command( + "runConfig.createUserConfiguration", + serde_json::json!({"root":root,"scope":"local","type":"buildProvider","name":name, + "build":reference,"entrypoint":entrypoint}), + ) + }; + let tool = save("Tool", "example.Tool"); + assert_eq!(tool["ok"], true, "{tool}"); + let document = changed_run_document(&tool["data"], plugin_path).unwrap(); + let saved = &document["configurations"][0]; + assert_eq!( + saved["extensions"]["build-run"]["entrypoint"], + "example.Tool" + ); + assert!( + saved["extensions"]["build"] + .get("targetID") + .is_none_or(|id| id == ""), + "{saved}" + ); + apply_run_changes(&root, &tool["data"]); + + let again = save("Tool", "example.Tool"); + assert_eq!(again["data"]["id"], tool["data"]["id"]); + let other = save("Other", "example.Other"); + assert_eq!(other["ok"], true, "{other}"); + assert_ne!(other["data"]["id"], tool["data"]["id"]); + apply_run_changes(&root, &other["data"]); + + let resolved = run_config_command("runConfig.resolve", serde_json::json!({"root":root})); + assert_eq!(resolved["ok"], true, "{resolved}"); + assert_eq!( + resolved["data"]["configurations"].as_array().unwrap().len(), + 2 + ); + let inputs = run_config_command( + "runConfig.providerLaunchInputs", + serde_json::json!({"root":root,"configurationId":tool["data"]["id"],"providerRoot":"app"}), + ); + assert_eq!(inputs["ok"], true, "{inputs}"); + assert_eq!( + inputs["data"]["launchOptions"]["entrypoint"], + "example.Tool" + ); + assert_eq!(save("Bad", "bad\u{0}")["ok"], false); +} diff --git a/rust/crates/execution/src/configuration/document.rs b/rust/crates/execution/src/configuration/document.rs index 3fa10df6..e25dc704 100644 --- a/rust/crates/execution/src/configuration/document.rs +++ b/rust/crates/execution/src/configuration/document.rs @@ -19,8 +19,9 @@ pub struct BuildProviderRunReference { /// Opaque project identity reported by the build model. #[serde(rename = "projectID")] pub project_id: String, - /// Opaque target identity reported by the build model. - #[serde(rename = "targetID")] + /// Opaque target identity reported by the build model; empty for an + /// entrypoint run, which starts an entrypoint in the project instead. + #[serde(rename = "targetID", default)] pub target_id: String, /// Omitted older references are applications; the current declaration must match at launch. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -59,9 +60,10 @@ impl BuildProviderRunReference { || !identifier(&self.plugin_id) || !identifier(&self.build_system_id) || !identifier(&self.run) + || self.project_id.is_empty() || [&self.project_id, &self.target_id] .iter() - .any(|id| id.is_empty() || id.len() > 2048 || id.contains('\0')) + .any(|id| id.len() > 2048 || id.contains('\0')) || self.user_arguments.len() > 64 || self .user_arguments diff --git a/rust/crates/execution/src/configuration/editing.rs b/rust/crates/execution/src/configuration/editing.rs index 7881d434..9d573538 100644 --- a/rust/crates/execution/src/configuration/editing.rs +++ b/rust/crates/execution/src/configuration/editing.rs @@ -284,6 +284,14 @@ fn create_build_provider_configuration( let mut document = layers.local.document.clone(); let mut ids = existing_ids(root, &layers); ids.extend(configuration_ids(&document)?.into_keys()); + // An entrypoint run's configurations differ only by the entrypoint they start. + let entrypoint = request.entrypoint.as_deref().unwrap_or_default(); + if entrypoint.len() > 4096 || entrypoint.contains('\0') { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid run entrypoint", + )); + } let encoded = serde_json::to_value(reference).expect("reference encodes"); let mut identity = encoded.clone(); identity.as_object_mut().unwrap().remove("userArguments"); @@ -300,7 +308,10 @@ fn create_build_provider_configuration( object.remove("userArguments"); object.remove("execution"); } - saved == identity + let saved_entrypoint = item["extensions"]["build-run"]["entrypoint"] + .as_str() + .unwrap_or_default(); + saved == identity && saved_entrypoint == entrypoint }); let id = existing .and_then(|index| items[index]["id"].as_str()) @@ -337,6 +348,19 @@ fn create_build_provider_configuration( ) })?; extensions.insert("build".to_string(), encoded); + if !entrypoint.is_empty() { + let options = extensions + .entry("build-run") + .or_insert_with(|| json!({})) + .as_object_mut() + .ok_or_else(|| { + CoreError::new( + ErrorCode::ParseFailed, + "Run configuration build-run options must be an object", + ) + })?; + options.insert("entrypoint".to_string(), json!(entrypoint)); + } let typed: RunConfiguration = serde_json::from_value(configuration.clone()) .map_err(|_| CoreError::new(ErrorCode::ParseFailed, "Invalid saved run configuration"))?; validate_configuration(&typed)?; diff --git a/rust/crates/execution/src/configuration/requests.rs b/rust/crates/execution/src/configuration/requests.rs index 012d4e5b..d4093238 100644 --- a/rust/crates/execution/src/configuration/requests.rs +++ b/rust/crates/execution/src/configuration/requests.rs @@ -159,6 +159,10 @@ pub struct CreateUserConfigurationRequest { /// A typed selector, never a cached executable or resolved launch payload. #[serde(default)] pub build: Option, + /// The provider entrypoint an entrypoint run starts, saved as + /// `extensions.build-run.entrypoint`; it is part of the entry's identity. + #[serde(default)] + pub entrypoint: Option, /// The installed plugins, whose identity a written plugin document records. #[serde(default)] pub plugins: Option>, diff --git a/rust/crates/lsp-client/src/build_provider.rs b/rust/crates/lsp-client/src/build_provider.rs index 39bb5ef8..027d81b0 100644 --- a/rust/crates/lsp-client/src/build_provider.rs +++ b/rust/crates/lsp-client/src/build_provider.rs @@ -45,6 +45,8 @@ pub(crate) const PREPARE_DEBUG_METHOD: &str = "lithe/build/prepareDebug"; pub const TEST_METHOD: &str = "lithe/build/test"; /// Returns exact selectors; decoding remains a separate Core command. pub(crate) const DISCOVER_TESTS_METHOD: &str = "lithe/build/discoverTests"; +/// `buildProviders` 1: the entrypoints of one source file; Core decodes them separately. +pub(crate) const RUN_ENTRYPOINTS_METHOD: &str = "lithe/build/runEntrypoints"; /// Progress never uses caller-chosen host operation IDs. pub(crate) const PROGRESS_METHOD: &str = "lithe/build/progress"; @@ -71,6 +73,7 @@ pub fn is_build_method(method: &str) -> bool { MODEL_METHODS.contains(&method) || is_execution_method(method) || method == DISCOVER_TESTS_METHOD + || method == RUN_ENTRYPOINTS_METHOD || method == PREPARE_RUN_METHOD || method == PREPARE_DEBUG_METHOD || method == CONFIGURATION_METHOD @@ -164,7 +167,7 @@ mod tests { assert!(!negotiated( &json!({ "experimental": { "litheBuild": {} } }) )); - assert!(!negotiated( + assert!(negotiated( &json!({ "experimental": { "litheBuild": { "version": 1 } } }) )); assert!(!negotiated( @@ -179,10 +182,10 @@ mod tests { } #[test] - fn the_host_offers_only_version_zero() { + fn the_host_offers_every_build_provider_version() { assert_eq!( client_experimental_capabilities(), - json!({ "litheBuild": { "versions": [0] } }) + json!({ "litheBuild": { "versions": [0, 1] } }) ); } @@ -194,6 +197,7 @@ mod tests { "lithe/build/execute", "lithe/build/test", "lithe/build/discoverTests", + "lithe/build/runEntrypoints", "lithe/build/prepareRun", "lithe/build/prepareDebug", "lithe/build/configuration", diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index 90106cb3..1d059a66 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -113,6 +113,20 @@ impl DeclarativePluginManifest { } } capabilities::check_used(&self.requires, &self.used_capabilities())?; + if self + .build_systems + .iter() + .any(|system| system.has_run_entrypoints()) + && self + .requires + .get(capabilities::BUILD_PROVIDERS) + .is_none_or(|version| *version < 1) + { + return Err(invalid( + "requires.buildProviders", + "Entrypoint runs need buildProviders 1.", + )); + } if self.languages.is_empty() && self.ui.is_none() && self.build_systems.is_empty() diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index 386a575b..05397a6b 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -65,6 +65,8 @@ pub const UI: &str = "ui"; /// Declarative build detection, models, and command plans. pub const BUILD_SYSTEMS: &str = "buildSystems"; /// `buildSystems[].provider`, whether it owns or shares a language server process. +/// Version 1 adds runs with `entrypoints: true`, which start an entrypoint the +/// provider finds in a source file (`lithe/build/runEntrypoints`). pub const BUILD_PROVIDERS: &str = "buildProviders"; /// Optional public model snapshots between enabled build providers. pub const BUILD_MODEL_INPUTS: &str = "buildModelInputs"; @@ -111,7 +113,7 @@ pub const OUTPUT_LINK_MATCHERS: &str = "outputLinkMatchers"; pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (BACKEND, &[0]), (BUILD_MODEL_INPUTS, &[0]), - (BUILD_PROVIDERS, &[0]), + (BUILD_PROVIDERS, &[0, 1]), (BUILD_SYSTEMS, &[0]), (COMMAND_INSTALLERS, &[0]), (DEBUG_ADAPTERS, &[0]), diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 92e61264..07b7751b 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -895,7 +895,7 @@ per capability. `buildProviders`, `litheFunctions` from `backend`, `litheVcs` from `vcsProviders`, the toolchain provider protocol from `toolchainProviders`, `litheKeymapImport` from `keymapImportProviders`, and `litheLogging` from - `pluginAPIVersion`. All of them are `0`. + `pluginAPIVersion`. `litheBuild` is at `1`; all the others are `0`. 3. **A host declares a capability version when it can serve every form of it.** See [Host capabilities](#host-capabilities). 4. **A future change gives one capability version `1`.** The manifest section @@ -916,7 +916,7 @@ The other versioned documents start at `0` too: | Plugin manifest ([schema](plugin-manifest.schema.json)); it names the file format, and any other value is `plugin.schema.unsupported` | `schemaVersion` | `0` | | Native UI document ([schema](native-ui.schema.json)) | `schemaVersion` | `0` | | Marketplace index ([schema](plugin-index.schema.json)) | `schemaVersion` | `0` | -| Canonical build documents (`litheBuildModel`, `litheDependencies`, `litheTestResults`, `litheTestDiscovery`, `litheBuildConfiguration`, `litheConfigurationEdit`) and the `modelInputs` snapshot | `version` | `0` | +| Canonical build documents (`litheBuildModel`, `litheDependencies`, `litheTestResults`, `litheTestDiscovery`, `litheRunEntrypoints`, `litheBuildConfiguration`, `litheConfigurationEdit`) and the `modelInputs` snapshot | `version` | `0` | | `plugins.editorActions.decode` request | `version` | `0` (required; Core accepts only `0`, otherwise `Unsupported editor action validation version.`) | | Plugin web bridge | `window.lithe.version` (`bridgeVersion`) | `0` | | `backend` member of a launch plan | `version` | the manifest's `requires.backend` | @@ -1894,9 +1894,11 @@ same invocation resolver; explicit invalid tool/runtime selection is a failure, never permission for independent discovery. It must reject stale project facts rather than guess a target. -The host offers `litheBuild.versions: [0]`: the protocol's version is the version -of `buildProviders` the manifest requires, and the provider answers -`{ "version": 0 }`. Unsupported negotiation fails explicitly. Task execution and +The host offers the `litheBuild` versions it implements, `[0, 1]` today: the +protocol's version is a version of `buildProviders`, and the provider answers +the newest one it speaks, such as `{ "version": 1 }`. Version 1 adds +`lithe/build/runEntrypoints` (see [Run entrypoints](#run-entrypoints-buildproviders-1)) +and changes nothing of version 0. Unsupported negotiation fails explicitly. Task execution and its progress notification belong to this protocol with `lithe/build/model` and `lithe/build/dependencies`. @@ -2077,6 +2079,48 @@ launch result validation and cancellation/stale-result behavior are unchanged. Canonical fixtures: `fixtures/build-providers/build-provider-run-options.plugin.json` and `fixtures/build-providers/build-run-options.json`. +#### Run entrypoints (`buildProviders` 1) + +A provider run may declare `entrypoints: true` instead of `fromTargets`. It is +an application that starts an entrypoint the provider names, such as a class +with a `main` method, in one of its projects. It requires `source: "provider"` +and `buildProviders` 1 in `requires`; `fromTargets`, `fromTasks`, `arguments`, +`extension`, `debug`, and a `service` or `task` execution are refused. It +applies to no target, so the host never lists it per target: the user starts +it from a source file. + +`build.runEntrypointsPlan` takes the common plan fields, optional `refresh` +and `tool`, and `file`, a workspace-relative file inside the instance root. +`project` and an output file are refused. It returns a request for +`lithe/build/runEntrypoints` whose params carry `file` beside the effective +options. The method uses the bounded request lifecycle of +`lithe/build/discoverTests`, without execution progress. The provider reads the +file and answers: + +```json +{"format":"litheRunEntrypoints","version":0,"entrypoints":[ + {"run":"main","name":"Tool","entrypoint":"example.Tool", + "project":{"name":"app","path":"app"}}]} +``` + +`run` names an entrypoint run, `name` is the display name (1–256 bytes, no +control characters), `entrypoint` is the opaque `launchOptions.entrypoint` +(1–4,096 bytes, no NUL), and `project` is a typed selection with a +workspace-relative path inside the instance. There are at most 64 entries, +in the provider's order, most relevant first. An empty list means the file +holds no entrypoint. The host passes the answer to `build.decodeRunEntrypoints` +with the plan's configuration; Core returns `entrypoints` without exact +duplicates and refuses a malformed answer whole with +`plugin.build.invalidOutput`. + +The host saves an answer as an ordinary provider run reference with an empty +`targetID` and `extensions.build-run.entrypoint`, then prepares it with +`build.prepareRunPlan`: an entrypoint run takes `project`, no `target`, and +requires `launchOptions.entrypoint`; a target run still requires its target. +The provider receives `lithe/build/prepareRun` without `target`. Canonical +fixtures: `fixtures/build-providers/build-provider-run-entrypoints.plugin.json` +and `fixtures/build-providers/build-run-entrypoints.json`. + #### Registry connection debugging A provider service run may declare @@ -2449,18 +2493,19 @@ The manifest only says how to start the provider and which sources use it. Everything else is negotiated in the LSP `initialize` exchange, so a provider can add optional data: -- The host sends `capabilities.experimental.litheBuild: { "versions": [0] }`. - The protocol has no version of its own: it is the version of `buildProviders` - the manifest requires. It is the two requests above with the params and result +- The host sends `capabilities.experimental.litheBuild: { "versions": [0, 1] }`, + the `buildProviders` versions it implements. The protocol has no version of + its own: it is a version of `buildProviders`, and version 1 only adds + `lithe/build/runEntrypoints`. It is the two requests above with the params and result formats of this section, together with the typed requests of the sections before it: task and test execution, test discovery, run preparation, native debug preparation, source-backed native configuration, inline test reports, opaque semantic test selectors, typed run options, and registry connection - debugging. Read-only model inputs travel in the plan requests. A host presents + debugging, and, from version 1, run entrypoints. Read-only model inputs travel in the plan requests. A host presents the features it implements; a provider must not depend on a host calling any of them. -- The provider answers `capabilities.experimental.litheBuild: { "version": 0 }` - with the version it chose from that list. A provider that answers no +- The provider answers `capabilities.experimental.litheBuild: { "version": 1 }` + with the version it chose from that list, the newest it speaks. A provider that answers no version, or one the host did not offer, is not used for build requests; a shared provider still serves its language. - Both sides ignore fields they do not know in these objects and in request diff --git a/shared/plugins/contract/v1/fixtures/build-providers/build-provider-run-entrypoints.plugin.json b/shared/plugins/contract/v1/fixtures/build-providers/build-provider-run-entrypoints.plugin.json new file mode 100644 index 00000000..40e66fc5 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/build-providers/build-provider-run-entrypoints.plugin.json @@ -0,0 +1,216 @@ +{ + "schemaVersion": 0, + "id": "dev.lithe.fixture.build-provider-run-entrypoints", + "displayName": "Provider Run Entrypoints Fixture", + "version": "0.1.0", + "pluginAPIVersion": 0, + "requires": { + "buildProviders": 1, + "buildSystems": 0, + "settings": 0 + }, + "requiresTools": [ + "java" + ], + "vendor": { + "id": "org.example", + "displayName": "Example", + "signatureRequirement": "publisherPackage" + }, + "permissions": [ + "languageServer.launch", + "process.build" + ], + "activationEvents": [ + "onBuildSystem:gradle" + ], + "languages": [], + "settings": [ + { + "id": "providerHeapMB", + "type": "integer", + "title": "Provider memory", + "description": "Upper bound of the Gradle provider's heap.", + "default": 1024, + "minimum": 256, + "maximum": 8192, + "unit": "MB" + } + ], + "buildSystems": [ + { + "id": "gradle", + "displayName": "Gradle", + "detection": { + "markers": [ + "build.gradle", + "build.gradle.kts", + "settings.gradle", + "settings.gradle.kts" + ], + "nesting": "outermost", + "priority": 60 + }, + "invocation": { + "executables": [ + { + "kind": "projectFile", + "path": "gradlew", + "requires": [ + "gradle/wrapper/gradle-wrapper.properties" + ], + "platforms": [ + "macos", + "linux" + ] + }, + { + "kind": "projectFile", + "path": "gradlew.bat", + "requires": [ + "gradle/wrapper/gradle-wrapper.properties" + ], + "platforms": [ + "windows" + ] + }, + { + "kind": "command", + "command": "gradle" + } + ], + "runtimeDependencies": [ + { + "id": "java", + "minimumVersion": "17" + } + ], + "globalArguments": [ + "--console=plain", + "${optionArguments}" + ] + }, + "provider": { + "launch": { + "kind": "runtime", + "tool": "java", + "minimumVersion": "17", + "runtimeArguments": [ + "-Xmx${setting:providerHeapMB}m" + ], + "entry": "provider/gradle-tooling-provider.jar" + }, + "arguments": [ + "--stdio", + "--cache", + "${workspaceStateDir}/tooling" + ], + "initializationOptions": { + "initScript": "${pluginDir}/provider/lithe-model.init.gradle" + }, + "executesProjectCode": true, + "mayUseNetwork": true + }, + "options": [ + { + "id": "offline", + "displayName": "Offline", + "kind": "boolean", + "arguments": [ + "--offline" + ] + } + ], + "model": { + "source": "provider" + }, + "tasks": [ + { + "id": "build", + "displayName": "Build", + "group": "build", + "scopes": [ + "workspace", + "project", + "target" + ], + "source": "provider", + "arguments": [] + }, + { + "id": "custom", + "displayName": "Custom", + "group": "other", + "scopes": [ + "workspace" + ], + "source": "provider", + "requiresUserArguments": true, + "arguments": [] + } + ], + "dependencies": { + "source": "provider", + "scopes": [ + "workspace", + "project" + ] + }, + "sync": { + "watch": [ + "build.gradle", + "build.gradle.kts", + "gradle.properties", + "gradle/libs.versions.toml", + "settings.gradle", + "settings.gradle.kts" + ] + }, + "layout": { + "excluded": [ + ".gradle", + "build" + ] + }, + "test": { + "source": "provider", + "scopes": [ + "workspace", + "project", + "target" + ], + "filters": [ + "suite", + "case" + ], + "arguments": [], + "results": { + "decoder": "junitXml", + "reports": [ + "build/test-results/**/*.xml" + ] + }, + "discovery": true + }, + "run": [ + { + "id": "application", + "source": "provider", + "name": "Run Application", + "fromTargets": { + "tags": [ + "application" + ] + }, + "arguments": [] + }, + { + "id": "main", + "source": "provider", + "name": "Main Class", + "entrypoints": true + } + ] + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/build-providers/build-run-entrypoints.json b/shared/plugins/contract/v1/fixtures/build-providers/build-run-entrypoints.json new file mode 100644 index 00000000..28a56fee --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/build-providers/build-run-entrypoints.json @@ -0,0 +1,68 @@ +{ + "plan": { + "root": ".", + "file": "app/src/main/java/example/Tool.java", + "refresh": false + }, + "result": { + "format": "litheRunEntrypoints", + "version": 0, + "entrypoints": [ + { + "run": "main", + "name": "Tool", + "entrypoint": "example.Tool", + "project": { + "name": "app", + "path": "app" + } + }, + { + "run": "main", + "name": "Tool.Inner", + "entrypoint": "example.Tool$Inner", + "project": { + "name": "app", + "path": "app" + } + } + ] + }, + "entrypoints": [ + { + "run": "main", + "name": "Tool", + "entrypoint": "example.Tool", + "project": { + "name": "app", + "path": "app" + } + }, + { + "run": "main", + "name": "Tool.Inner", + "entrypoint": "example.Tool$Inner", + "project": { + "name": "app", + "path": "app" + } + } + ], + "prepareRun": { + "root": ".", + "run": "main", + "project": { + "name": "app", + "path": "app" + }, + "launchOptions": { + "execution": "application", + "runtimeArguments": [], + "arguments": [ + "--verbose" + ], + "environment": {}, + "entrypoint": "example.Tool" + } + } +} diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 0c1747c2..b7462df4 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -3183,9 +3183,30 @@ "additionalProperties": { "type": "string" } + }, + "entrypoints": { + "description": "buildProviders 1: a provider application that starts an entrypoint lithe/build/runEntrypoints names in a source file, in its project and without a target. Requires source provider; refuses fromTargets, fromTasks, arguments, extension, debug and a service or task execution.", + "type": "boolean" } }, + "if": { "required": ["entrypoints"], "properties": { "entrypoints": { "const": true } } }, + "then": { "not": { "anyOf": [ { "required": ["fromTargets"] }, { "required": ["fromTasks"] } ] } }, "oneOf": [ + { + "required": [ + "entrypoints" + ], + "properties": { + "entrypoints": { "const": true }, + "source": { "const": "provider" } + }, + "not": { + "anyOf": [ + { "required": ["fromTargets"] }, + { "required": ["fromTasks"] } + ] + } + }, { "required": [ "fromTargets" diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 541a0251..c502309b 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -50,6 +50,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `ui` `0` | [`ui`](../contract/v1/README.md#host-owned-workbench-ui):文本、[包内网页](../contract/v1/README.md#web-content)和[原生控件](../contract/v1/README.md#host-rendered-native-content)的工具窗口、命令,以及[不打开工具窗口的后端命令](../contract/v1/README.md#backend-only-commands) | ✅ | ✅¹ | [界面](domains/ui.md) | | `buildSystems` `0` | 不带 `provider` 的 [`buildSystems[]`](../contract/v1/README.md#build-systems):检测、选项、项目模型、任务、运行入口、测试、诊断、依赖、同步和[声明式项目准备](../contract/v1/README.md#declarative-project-preparation) | ✅ | ✅¹ | [声明式构建系统](domains/build-systems.md) | | `buildProviders` `0` | `buildSystems[].provider`:[构建提供者](../contract/v1/README.md#build-providers),可以是自有进程或共享语言服务器;说 `litheBuild`,包含任务执行、测试执行与发现、运行准备、原生调试准备、原生配置、内联测试报告、语义测试选择器、类型化运行选项和注册表连接调试 | ✅ | ✅¹ | [构建提供者](domains/build-providers.md) | +| `buildProviders` `1` | 在 `0` 之上加:运行声明 `entrypoints: true`(入口运行,不需要目标),提供者用 `lithe/build/runEntrypoints` 回答一个源文件里可运行的入口,宿主把它保存为运行配置并按入口启动 | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `buildModelInputs` `0` | `buildSystems[].modelSharing` 与 `modelInputs`:[已启用工作区插件之间共享的只读模型输入](../contract/v1/README.md#optional-read-only-model-inputs)(可选) | ✅ | 未声明 | [构建提供者](domains/build-providers.md) | | `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers);说 `litheVcs` | ✅ | 未声明 | [版本控制提供者](domains/vcs.md) | | `debugAdapters` `0` | [`debugAdapters[]`](../contract/v1/README.md#debug-adapters):独立适配器、语言服务器内的适配器、[远程附加](../contract/v1/README.md#remote-attach)、参数和环境变量、[`features` 与 `defaults`](../contract/v1/README.md#adapter-features-and-defaults) | ✅ | ✅ | [调试适配器](domains/debug-adapters.md) | @@ -78,6 +79,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | --- | --- | --- | --- | --- | | `litheFunctions` `0`(`backend`) | 插件函数:注册、撤回、调用、结果、进度、取消;宿主服务 `lithe/host/*`(凭据、工作区上下文与能力发现、宿主通知、公共文档/文件/窗口方法、插件自有原生终端、独立编辑器动作、编辑器语言功能 Provider、运行与调试会话、语言服务器方法、内容提供者);跨插件调用 `functions/providers`、`functions/invoke`。提供给插件拥有的会话 | ✅ | ✅¹ | [Plugin functions](../contract/v1/README.md#plugin-functions) | | `litheBuild` `0`(`buildProviders`) | `lithe/build/*`:模型与依赖、任务执行、测试执行与发现、运行准备、原生调试准备、只读模型输入、原生配置、内联测试报告、语义测试选择器、类型化运行选项、注册表连接调试。提供给构建提供者 | ✅ | ✅¹ | [Build providers](../contract/v1/README.md#build-providers) | +| `litheBuild` `1`(`buildProviders`) | 在 `0` 之上加 `lithe/build/runEntrypoints`:按源文件找运行入口 | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `litheVcs` `0`(`vcsProviders`) | VCS 提供者的能力和请求(`lithe/vcs/*`)。提供给 VCS 提供者 | ✅ | 未声明 | [VCS providers](../contract/v1/README.md#vcs-providers) | | `litheToolchains` `0`(`toolchainProviders`) | `toolchains/query`;后端从声明的提供者中选出子集。提供给声明了工具链提供者的插件会话 | ✅ | 未声明 | [Provider backend negotiation](../contract/v1/toolchains/README.md#provider-backend-negotiation) | | `litheKeymapImport` `0`(`keymapImportProviders`) | 后端从声明的提供者中选出要启用的子集;`lithe/keymap/import`。提供给声明了 `keymapImportProviders` 的插件会话 | ✅ | 未声明 | [Shortcut import](../contract/v1/README.md#shortcut-import-providers-core-foundation) | @@ -156,6 +158,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `ui` `0` | [`ui`](../contract/v1/README.md#host-owned-workbench-ui): text, [web](../contract/v1/README.md#web-content), and [native](../contract/v1/README.md#host-rendered-native-content) tool windows, commands, and [backend-only commands](../contract/v1/README.md#backend-only-commands) without a tool window | ✅ | ✅¹ | [UI](domains/ui.md) | | `buildSystems` `0` | [`buildSystems[]`](../contract/v1/README.md#build-systems) without `provider`: detection, options, project model, tasks, run entries, tests, diagnostics, dependencies, sync, and [declarative preparation](../contract/v1/README.md#declarative-project-preparation) | ✅ | ✅¹ | [Declarative build systems](domains/build-systems.md) | | `buildProviders` `0` | `buildSystems[].provider`: [build providers](../contract/v1/README.md#build-providers), in their own process or a shared language server; they speak `litheBuild`, which covers task execution, test execution and discovery, run preparation, native debug preparation, native configuration, inline test reports, semantic test selectors, typed run options, and registry connection debugging | ✅ | ✅¹ | [Build providers](domains/build-providers.md) | +| `buildProviders` `1` | Adds to `0`: run declarations with `entrypoints: true` (entrypoint runs, without a target); the provider answers `lithe/build/runEntrypoints` with the runnable entrypoints of one source file, which the host saves as run configurations and starts | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `buildModelInputs` `0` | `buildSystems[].modelSharing` and `modelInputs`: [optional read-only model inputs](../contract/v1/README.md#optional-read-only-model-inputs) shared between enabled workspace plugins | ✅ | Not declared | [Build providers](domains/build-providers.md) | | `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers); they speak `litheVcs` | ✅ | Not declared | [VCS providers](domains/vcs.md) | | `debugAdapters` `0` | [`debugAdapters[]`](../contract/v1/README.md#debug-adapters): standalone adapters, adapters inside a language server, [remote attach](../contract/v1/README.md#remote-attach), arguments and environment, [`features` and `defaults`](../contract/v1/README.md#adapter-features-and-defaults) | ✅ | ✅ | [Debug adapters](domains/debug-adapters.md) | @@ -184,6 +187,7 @@ These protocols are negotiated when a process starts and never appear in the man | --- | --- | --- | --- | --- | | `litheFunctions` `0` (`backend`) | Plugin functions: register, withdraw, invoke, results, progress, cancellation; the `lithe/host/*` host services (credentials, workspace contexts and capability discovery, host notifications, public document, file, and window methods, plugin-owned native terminals, independent editor actions, editor language-feature providers, run and debug sessions, language server methods, content providers); cross-plugin calls `functions/providers` and `functions/invoke`. Offered to plugin-owned sessions | ✅ | ✅¹ | [Plugin functions](../contract/v1/README.md#plugin-functions) | | `litheBuild` `0` (`buildProviders`) | `lithe/build/*`: model and dependencies, task execution, test execution and discovery, run preparation, native debug preparation, read-only model inputs, native configuration, inline test reports, semantic test selectors, typed run options, registry connection debugging. Offered to build providers | ✅ | ✅¹ | [Build providers](../contract/v1/README.md#build-providers) | +| `litheBuild` `1` (`buildProviders`) | Adds `lithe/build/runEntrypoints` to `0`: the run entrypoints of a source file | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `litheVcs` `0` (`vcsProviders`) | VCS provider capabilities and requests (`lithe/vcs/*`). Offered to VCS providers | ✅ | Not declared | [VCS providers](../contract/v1/README.md#vcs-providers) | | `litheToolchains` `0` (`toolchainProviders`) | `toolchains/query`; the backend selects a subset of its declared providers. Offered to plugin sessions that declare toolchain providers | ✅ | Not declared | [Provider backend negotiation](../contract/v1/toolchains/README.md#provider-backend-negotiation) | | `litheKeymapImport` `0` (`keymapImportProviders`) | The backend selects a subset of its declared providers; `lithe/keymap/import`. Offered to plugin sessions with declared `keymapImportProviders` | ✅ | Not declared | [Shortcut import](../contract/v1/README.md#shortcut-import-providers-core-foundation) | diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java index 1e0b49ea..02aa4a6c 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java @@ -190,10 +190,13 @@ private enum Phase { IDLE, LISTENING, INITIALIZING, READY, SHUTTING_DOWN, EXITED formats.put(Protocol.BUILD_MODEL, "litheBuildModel"); formats.put(Protocol.BUILD_DEPENDENCIES, "litheDependencies"); formats.put(Protocol.BUILD_DISCOVER_TESTS, "litheTestDiscovery"); + formats.put(Protocol.BUILD_RUN_ENTRYPOINTS, "litheRunEntrypoints"); BUILD_FORMATS = Collections.unmodifiableMap(formats); } private volatile boolean logging; + /** The negotiated build protocol version, the newest the host offered; -1 before. */ + private volatile int buildVersion = -1; private boolean loggingReady; private final List> earlyDiagnostics = new ArrayList<>(); private final java.util.Set quietSuccess = new java.util.HashSet<>(); @@ -327,6 +330,14 @@ public Backend onPrepareRun(Handler handler) { return declareBuild(Protocol.BUILD_PREPARE_RUN, handler); } + /** + * Names the entrypoints of one source file that an entrypoint run starts + * ({@code buildProviders} 1), with the format stamped. + */ + public Backend onRunEntrypoints(Handler handler) { + return declareBuild(Protocol.BUILD_RUN_ENTRYPOINTS, handler); + } + /** * Declares a plugin function offered from the start, in the {@code initialize} * answer. To add one later, use {@link #registerFunction}. @@ -803,9 +814,15 @@ private void initialize(Object id, Map params) { "The backend requires litheLogging version " + Protocol.LOGGING_VERSION + ".")); return; } + buildVersion = -1; + for (int version = Protocol.BUILD_VERSION; version >= 0 && buildVersion < 0; version--) { + if (offers(offered.get("litheBuild"), version)) { + buildVersion = version; + } + } agreed = new Negotiated( offers(offered.get("litheFunctions"), Protocol.FUNCTIONS_VERSION), - !buildHandlers.isEmpty() && offers(offered.get("litheBuild"), Protocol.BUILD_VERSION)); + !buildHandlers.isEmpty() && buildVersion >= 0); negotiated = agreed; hooks = new ArrayList<>(initializeHooks); } @@ -852,7 +869,7 @@ private void initialize(Object id, Map params) { } } if (agreed.build()) { - experimental.put("litheBuild", singleton("version", Protocol.BUILD_VERSION)); + experimental.put("litheBuild", singleton("version", buildVersion)); } if (agreed.functions()) { List offered = new ArrayList<>(); diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java index c4d9bd4a..77f422a6 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java @@ -13,6 +13,7 @@ public final class Diagnostics { "initialize", "shutdown", "notification", "function-call", "result-encoding", "lithe/build/model", "lithe/build/dependencies", "lithe/build/execute", "lithe/build/test", "lithe/build/discoverTests", "lithe/build/prepareRun", "lithe/build/prepareDebug", + "lithe/build/runEntrypoints", "lithe/vcs/status", "lithe/vcs/baseContent", "lithe/vcs/history", "lithe/vcs/fileHistory", "lithe/vcs/annotate", "lithe/vcs/checkin", "lithe/vcs/rollback", "lithe/vcs/update", "lithe/vcs/fileOperation", "lithe/vcs/resolve", "lithe/vcs/cleanup", diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java index 0d987438..66f57caa 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java @@ -14,7 +14,12 @@ public final class Protocol { /** The version of each protocol this SDK speaks; the host offers it in {@code initialize}. */ public static final int FUNCTIONS_VERSION = 0; - public static final int BUILD_VERSION = 0; + /** + * The newest build protocol version ({@code buildProviders} 1 adds + * {@code lithe/build/runEntrypoints}). The SDK also speaks every earlier + * version and answers the newest one the host offers. + */ + public static final int BUILD_VERSION = 1; public static final int LOGGING_VERSION = 0; public static final int KEYMAP_IMPORT_VERSION = 0; @@ -34,6 +39,7 @@ public final class Protocol { public static final String BUILD_DISCOVER_TESTS = "lithe/build/discoverTests"; public static final String BUILD_PREPARE_DEBUG = "lithe/build/prepareDebug"; public static final String BUILD_PREPARE_RUN = "lithe/build/prepareRun"; + public static final String BUILD_RUN_ENTRYPOINTS = "lithe/build/runEntrypoints"; public static final String BUILD_PROGRESS = "lithe/build/progress"; /** diff --git a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/BuildTest.java b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/BuildTest.java index 31665165..6afcc2d0 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/BuildTest.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/BuildTest.java @@ -32,16 +32,19 @@ private static Object errorCode(Map response) { @Test void versionZeroAdmitsEveryTypedMethod() { - List methods = Arrays.asList("execute", "test", "discoverTests", "prepareRun", "prepareDebug"); + List methods = Arrays.asList("execute", "test", "discoverTests", "prepareRun", "prepareDebug", "runEntrypoints"); List> replies = Arrays.asList(map("exitCode", 0, "output", "built\n"), map("exitCode", 2, "output", "test failed\n"), - map("tests", Arrays.asList(map("suite", "Suite", "case", "exact # [case]"))), LAUNCH, map("program", "app/bin/main", "arguments", Arrays.asList("a b"), "workingDirectory", "app", "environment", map())); + map("tests", Arrays.asList(map("suite", "Suite", "case", "exact # [case]"))), LAUNCH, map("program", "app/bin/main", "arguments", Arrays.asList("a b"), "workingDirectory", "app", "environment", map()), + map("entrypoints", Arrays.asList(map("run", "main", "name", "Tool", "entrypoint", "example.Tool", + "project", map("name", "app", "path", "app"))))); Backend backend = Backend.create(null, null) .onExecute((params, context) -> replies.get(0)) .onTest((params, context) -> replies.get(1)) .onDiscoverTests((params, context) -> replies.get(2)) .onPrepareRun((params, context) -> replies.get(3)) - .onPrepareDebug((params, context) -> replies.get(4)); + .onPrepareDebug((params, context) -> replies.get(4)) + .onRunEntrypoints((params, context) -> replies.get(5)); TestHost host = new TestHost(backend); try { Map result = Json.object(host.initialize(offered(0, 99)).get("result")); @@ -53,6 +56,7 @@ void versionZeroAdmitsEveryTypedMethod() { // Compare JSON-normalized numeric types, as seen on the wire. Map expected = Json.object(Json.parse(Json.stringify(replies.get(index)))); if (index == 2) { expected.put("format", "litheTestDiscovery"); expected.put("version", 0L); } + if (index == 5) { expected.put("format", "litheRunEntrypoints"); expected.put("version", 0L); } assertEquals(expected, response.get("result")); } } finally { host.close(); } @@ -77,16 +81,18 @@ void modelInputsReachTheHandlerAndPreserveHostIdentity() { } @Test - void negotiationRequiresTheHostToOfferVersionZeroAsAnInteger() { - for (Object[] versions : new Object[][] {{0}, {99, 0, 1}}) { + void negotiationAnswersTheNewestOfferedVersionAsAnInteger() { + for (Object[][] row : new Object[][][] {{{0}, {0L}}, {{99, 0, 1}, {1L}}, {{1, 4, 3, 2}, {1L}}}) { Backend backend = Backend.create(null, null).onExecute((params, context) -> map("exitCode", 0, "output", "")); TestHost host = new TestHost(backend); try { - host.initialize(offered(versions)); + Map result = Json.object(host.initialize(offered(row[0])).get("result")); + Map experimental = Json.object(Json.object(result.get("capabilities")).get("experimental")); assertTrue(backend.negotiated().build()); + assertEquals(row[1][0], Json.object(experimental.get("litheBuild")).get("version")); } finally { host.close(); } } - for (Object[] versions : new Object[][] {{1, 4, 3, 2}, {99, "0", false}, {}}) { + for (Object[] versions : new Object[][] {{4, 3, 2}, {99, "0", false}, {}}) { Backend backend = Backend.create(null, null).onExecute((params, context) -> map("exitCode", 0, "output", "")); TestHost host = new TestHost(backend); try { diff --git a/shared/plugins/sdk/node/src/backend.mjs b/shared/plugins/sdk/node/src/backend.mjs index 261c2b5a..7723edd0 100644 --- a/shared/plugins/sdk/node/src/backend.mjs +++ b/shared/plugins/sdk/node/src/backend.mjs @@ -42,6 +42,7 @@ const BUILD_FORMATS = Object.freeze({ [METHODS.buildModel]: 'litheBuildModel', [METHODS.buildDependencies]: 'litheDependencies', [METHODS.buildDiscoverTests]: 'litheTestDiscovery', + [METHODS.buildRunEntrypoints]: 'litheRunEntrypoints', }); /** Host notifications the SDK routes itself; see `onCommand`, `onContextsChanged`, and `host.subscribe`. */ @@ -133,6 +134,7 @@ class Backend { execute: (handler) => this.#declareBuild(METHODS.buildExecute, handler), test: (handler) => this.#declareBuild(METHODS.buildTest, handler), discoverTests: (handler) => this.#declareBuild(METHODS.buildDiscoverTests, handler), + runEntrypoints: (handler) => this.#declareBuild(METHODS.buildRunEntrypoints, handler), /** Prepares a plan; the application itself belongs to the host. */ prepareRun: (handler) => this.#declareBuild(METHODS.buildPrepareRun, handler), prepareDebug: (handler) => this.#declareBuild(METHODS.buildPrepareDebug, handler), @@ -574,7 +576,12 @@ class Backend { this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: `The backend requires litheLogging version ${LOGGING_VERSION}.` }); return; } - this.#buildVersion = this.#buildHandlers.size > 0 && offers(offered.litheBuild, BUILD_VERSION) ? BUILD_VERSION : null; + // The newest build protocol version the host offers; each one adds to the one before. + let buildVersion = null; + for (let version = BUILD_VERSION; version >= 0 && buildVersion === null; version -= 1) { + if (offers(offered.litheBuild, version)) buildVersion = version; + } + this.#buildVersion = this.#buildHandlers.size > 0 ? buildVersion : null; this.#functionsVersion = offers(offered.litheFunctions, FUNCTIONS_VERSION) ? FUNCTIONS_VERSION : null; this.#negotiated = Object.freeze({ functions: this.#functionsVersion !== null, diff --git a/shared/plugins/sdk/node/src/diagnostics.mjs b/shared/plugins/sdk/node/src/diagnostics.mjs index 8fcdc99a..54deb0c4 100644 --- a/shared/plugins/sdk/node/src/diagnostics.mjs +++ b/shared/plugins/sdk/node/src/diagnostics.mjs @@ -3,7 +3,7 @@ import { PluginSdkError } from './errors.mjs'; export const KNOWN_OPERATIONS = new Set([ 'initialize', 'shutdown', 'notification', 'function-call', 'result-encoding', - ...['model', 'dependencies', 'execute', 'test', 'discoverTests', 'prepareRun', 'prepareDebug'].map((name) => `lithe/build/${name}`), + ...['model', 'dependencies', 'execute', 'test', 'discoverTests', 'prepareRun', 'prepareDebug', 'runEntrypoints'].map((name) => `lithe/build/${name}`), ...['status', 'baseContent', 'history', 'fileHistory', 'annotate', 'checkin', 'rollback', 'update', 'fileOperation', 'resolve', 'cleanup'].map((name) => `lithe/vcs/${name}`), 'lithe/keymap/import', ]); diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 003443d5..060b829b 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -471,6 +471,12 @@ export interface BuildTestDiscovery { version?: 0; tests: { suite: string; case: string; project?: BuildSelection; target?: BuildSelection }[]; } +/** buildProviders 1: the entrypoints of one source file an entrypoint run starts. */ +export interface BuildRunEntrypoints { + format?: 'litheRunEntrypoints'; + version?: 0; + entrypoints: { run: string; name: string; entrypoint: string; project: BuildSelection }[]; +} export interface BuildRunPreparation { executable: { kind: 'toolchain' | 'command'; value: string }; arguments: string[]; @@ -479,6 +485,7 @@ export interface BuildRunPreparation { } export type BuildExecutionHandler = (params: BuildExecutionParams, context: BuildContext) => BuildExecutionResult | Promise; export type BuildTestHandler = (params: BuildTestParams, context: BuildContext) => BuildExecutionResult | Promise; +export type BuildRunEntrypointsHandler = (params: BuildRequestParams & { file: string }, context: RequestContext) => BuildRunEntrypoints | Promise; export type BuildDiscoveryHandler = (params: BuildRequestParams, context: RequestContext) => BuildTestDiscovery | Promise; export interface BuildDebugPreparation { program: string; @@ -569,6 +576,8 @@ export interface Backend { test(handler: BuildTestHandler): Backend; discoverTests(handler: BuildDiscoveryHandler): Backend; prepareRun(handler: BuildRunHandler): Backend; + /** buildProviders 1: answers lithe/build/runEntrypoints with the format stamped. */ + runEntrypoints(handler: BuildRunEntrypointsHandler): Backend; prepareDebug(handler: BuildDebugHandler): Backend; }; vcs(id: string, handlers: VcsHandlers, traits?: VcsTraits): Backend; diff --git a/shared/plugins/sdk/node/src/protocol.mjs b/shared/plugins/sdk/node/src/protocol.mjs index 54a5365c..e28303c0 100644 --- a/shared/plugins/sdk/node/src/protocol.mjs +++ b/shared/plugins/sdk/node/src/protocol.mjs @@ -6,7 +6,8 @@ /** The protocol versions this SDK speaks. */ export const FUNCTIONS_VERSION = 0; -export const BUILD_VERSION = 0; +/** The newest build protocol version (buildProviders 1 adds lithe/build/runEntrypoints); every earlier one is spoken too. */ +export const BUILD_VERSION = 1; export const VCS_VERSION = 0; export const LOGGING_VERSION = 0; export const KEYMAP_IMPORT_VERSION = 0; @@ -26,6 +27,7 @@ export const METHODS = Object.freeze({ buildExecute: 'lithe/build/execute', buildTest: 'lithe/build/test', buildDiscoverTests: 'lithe/build/discoverTests', + buildRunEntrypoints: 'lithe/build/runEntrypoints', buildPrepareRun: 'lithe/build/prepareRun', buildPrepareDebug: 'lithe/build/prepareDebug', buildProgress: 'lithe/build/progress', diff --git a/shared/plugins/sdk/node/test/build.test.mjs b/shared/plugins/sdk/node/test/build.test.mjs index 6313ad71..2d9fc380 100644 --- a/shared/plugins/sdk/node/test/build.test.mjs +++ b/shared/plugins/sdk/node/test/build.test.mjs @@ -12,6 +12,7 @@ const methods = [ ['test', { exitCode: 2, output: 'test failed\n' }], ['discoverTests', { tests: [{ suite: 'Suite', case: 'exact # [case]' }] }], ['prepareRun', launch], + ['runEntrypoints', { entrypoints: [{ run: 'main', name: 'Tool', entrypoint: 'example.Tool', project: { name: 'app', path: 'app' } }] }], ['prepareDebug', { program: 'app/bin/main', arguments: [], workingDirectory: 'app', environment: {} }], ]; @@ -25,22 +26,21 @@ test('the build protocol answers version 0 and routes each of its typed methods' assert.equal(backend.buildVersion, 0); for (const [method, reply] of methods) { const response = await host.request(`lithe/build/${method}`, { operationID: `wire-${method}` }); - assert.deepEqual(response.result, method === 'discoverTests' - ? { ...reply, format: 'litheTestDiscovery', version: 0 } : reply); + const format = { discoverTests: 'litheTestDiscovery', runEntrypoints: 'litheRunEntrypoints' }[method]; + assert.deepEqual(response.result, format ? { ...reply, format, version: 0 } : reply); } }); -test('build negotiation needs the host to offer version 0', { timeout: 15000 }, async (t) => { - for (const versions of [[0], [99, 0], [1, 4], [99, '0', true], []]) { +test('build negotiation answers the newest version the host offers', { timeout: 15000 }, async (t) => { + for (const [versions, chosen] of [[[0], 0], [[99, 0], 0], [[1, 4], 1], [[0, 1], 1], [[4, 2], null], [[99, '0', true], null], [[], null]]) { const backend = createBackend(); backend.build.execute(() => ({ exitCode: 0, output: '' })); const host = new TestHost(backend); t.after(() => host.close()); - const offered = versions.includes(0); const response = await host.initialize({ litheBuild: { versions } }); - assert.equal(backend.buildVersion, offered ? 0 : null, JSON.stringify(versions)); + assert.equal(backend.buildVersion, chosen, JSON.stringify(versions)); assert.deepEqual(response.result.capabilities.experimental, - offered ? { litheLogging: { version: 0 }, litheBuild: { version: 0 } } : { litheLogging: { version: 0 } }); + chosen !== null ? { litheLogging: { version: 0 }, litheBuild: { version: chosen } } : { litheLogging: { version: 0 } }); await host.close(); } }); diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/diagnostics.rs b/shared/plugins/sdk/rust/plugin-sdk/src/diagnostics.rs index 841e47cf..ee0da5e8 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/diagnostics.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/diagnostics.rs @@ -19,6 +19,7 @@ pub(crate) const OPERATIONS: &[&str] = &[ "lithe/build/discoverTests", "lithe/build/prepareRun", "lithe/build/prepareDebug", + "lithe/build/runEntrypoints", "lithe/vcs/status", "lithe/vcs/baseContent", "lithe/vcs/history", From 76bab3918db54da41edf3b261c1401993934ba18 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Tue, 17 Nov 2026 18:54:07 -0800 Subject: [PATCH 2/2] Offer litheBuild 1 in engine tests; document runEntrypoints Co-Authored-By: Claude Opus 5.5 --- rust/crates/lsp-engine/src/tests.rs | 8 ++++---- .../plugins/reference/capabilities-and-versions.md | 4 ++-- .../plugins/reference/domains/build-providers.md | 14 ++++++++------ shared/plugins/reference/protocol-changelog.md | 3 +++ 4 files changed, 17 insertions(+), 12 deletions(-) diff --git a/rust/crates/lsp-engine/src/tests.rs b/rust/crates/lsp-engine/src/tests.rs index e5f9a5c6..b503563c 100644 --- a/rust/crates/lsp-engine/src/tests.rs +++ b/rust/crates/lsp-engine/src/tests.rs @@ -3211,7 +3211,7 @@ fn build_requests_need_a_negotiated_protocol_version() { .expect("initialize should have been written"); assert_eq!( initialize["params"]["capabilities"]["experimental"]["litheBuild"], - json!({ "versions": [0] }) + json!({ "versions": [0, 1] }) ); let error = build_request(&harness, "lithe/build/model", json!({}), None) @@ -3229,11 +3229,11 @@ fn build_requests_need_a_negotiated_protocol_version() { #[test] fn a_reply_naming_an_unoffered_version_negotiates_nothing() { let harness = plugin_backend(json!({ - "litheBuild": { "version": 1 }, + "litheBuild": { "version": 2 }, "litheFunctions": { "version": 1, "functions": [{ "id": "snapshot.refresh" }] } })); let error = build_request(&harness, "lithe/build/model", json!({}), None) - .expect_err("version 1 was not offered"); + .expect_err("version 2 was not offered"); assert!(matches!(error.code, ErrorCode::NotSupported)); let error = invoke(&harness, FUNCTION_PLUGIN, "snapshot.refresh", None) .expect_err("version 1 was not offered"); @@ -4059,7 +4059,7 @@ fn a_plugin_function_is_routed_to_its_plugin_and_returns_its_result() { assert_eq!( initialize["params"]["capabilities"]["experimental"], json!({ - "litheBuild": { "versions": [0] }, + "litheBuild": { "versions": [0, 1] }, "litheFunctions": { "versions": [0] }, "litheLogging": { "versions": [0] }, "litheVcs": { "versions": [0] } diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index c502309b..4d4e0907 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -106,7 +106,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https ### 官方 SDK -Node.js SDK 0.5.0、Java SDK 0.5.0 和 Rust SDK 0.4.0 说的是版本 `0` 的协议;各 SDK 封装哪些协议见契约的 [Official backend SDK](../contract/v1/README.md#official-backend-sdk) 和各自的 [Node.js](../sdk/node/README.md)、[Java](../sdk/java/README.md)、[Rust](../sdk/rust/README.md) README。下载地址在 [Lithe-core-rust 的 Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases)。 +Node.js SDK 0.5.0、Java SDK 0.5.0 和 Rust SDK 0.4.0 说的是版本 `0` 的协议;`main` 上的 SDK 源码另外支持 `litheBuild` `1`(`lithe/build/runEntrypoints`),回答宿主提供的最新版本,随下一次 SDK 发布提供;各 SDK 封装哪些协议见契约的 [Official backend SDK](../contract/v1/README.md#official-backend-sdk) 和各自的 [Node.js](../sdk/node/README.md)、[Java](../sdk/java/README.md)、[Rust](../sdk/rust/README.md) README。下载地址在 [Lithe-core-rust 的 Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases)。 --- @@ -214,4 +214,4 @@ The `version` of an exported or called plugin function (1 to 1000) is not a cont ### Official SDKs -Node.js SDK 0.5.0, Java SDK 0.5.0, and Rust SDK 0.4.0 speak the version `0` protocols; which protocols each SDK wraps is in the contract's [Official backend SDK](../contract/v1/README.md#official-backend-sdk) and in the [Node.js](../sdk/node/README.md), [Java](../sdk/java/README.md), and [Rust](../sdk/rust/README.md) READMEs. Downloads are on the [Lithe-core-rust Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases) page. +Node.js SDK 0.5.0, Java SDK 0.5.0, and Rust SDK 0.4.0 speak the version `0` protocols; the SDK sources on `main` also speak `litheBuild` `1` (`lithe/build/runEntrypoints`) and answer the newest version the host offers, which the next SDK release ships; which protocols each SDK wraps is in the contract's [Official backend SDK](../contract/v1/README.md#official-backend-sdk) and in the [Node.js](../sdk/node/README.md), [Java](../sdk/java/README.md), and [Rust](../sdk/rust/README.md) READMEs. Downloads are on the [Lithe-core-rust Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases) page. diff --git a/shared/plugins/reference/domains/build-providers.md b/shared/plugins/reference/domains/build-providers.md index 25585565..4c0835b0 100644 --- a/shared/plugins/reference/domains/build-providers.md +++ b/shared/plugins/reference/domains/build-providers.md @@ -15,7 +15,7 @@ | --- | --- | | 清单字段 | `buildSystems[].provider`,以及各声明里的 `source: "provider"` | | 能力版本 | `buildProviders` `0`;任何 `buildSystems[].provider` 都要同时有 `buildSystems: 0` 和 `buildProviders: 0`,不论它自己启动进程还是共用语言服务器;只用模板的构建插件不写 `buildProviders`。`requires` 必须恰好列出清单用到的能力;启动进程是基础契约,不是能力,不写 `requires.serverProcess`。见[版本对照](../capabilities-and-versions.md#能力版本requires) | -| 协议 | `litheBuild` `0`:宿主在 `initialize` 里提供 `capabilities.experimental.litheBuild: {"versions": [0]}`,提供者回答 `{"version": 0}`。协议没有自己的版本,就是 `buildProviders` 的版本,见[进程协议版本](../capabilities-and-versions.md#进程协议版本) | +| 协议 | `litheBuild` `0` 和 `1`:宿主在 `initialize` 里提供 `capabilities.experimental.litheBuild: {"versions": [0, 1]}`,提供者回答自己支持的最新版本,例如 `{"version": 1}`;版本 `1` 只多了 `lithe/build/runEntrypoints`。协议没有自己的版本,就是 `buildProviders` 的版本,见[进程协议版本](../capabilities-and-versions.md#进程协议版本) | | API 编号 | [API-29](../api-catalog.md#现在能用的-api):构建、任务、测试、运行准备 | | 权限 | `process.build`;自有进程的提供者加 `languageServer.launch`;原生调试准备加 `debug.launch` | | 激活事件 | `onBuildSystem:`;提供者在第一次由用户操作触发的构建请求时启动 | @@ -34,7 +34,7 @@ ### 提供者能做什么 -所有功能都属于 `buildProviders` `0`,用同一个 `litheBuild` 协议。一次会话里能用到哪些,取决于清单声明了哪个来源,以及宿主实现了哪些。 +除运行入口属于 `buildProviders` `1` 外,所有功能都属于 `buildProviders` `0`,用同一个 `litheBuild` 协议。一次会话里能用到哪些,取决于清单声明了哪个来源,以及宿主实现了哪些。 | 功能 | 清单里的声明 | 方法 | 契约章节 | 示例(在 `fixtures/build-providers/`,另有说明的除外) | | --- | --- | --- | --- | --- | @@ -44,6 +44,7 @@ | 测试发现 | provider 测试声明 `discovery: true`,同时需要 `suite` 和 `case` 过滤器 | `lithe/build/discoverTests` | [Test discovery](../../contract/v1/README.md#test-discovery) | `build-test-discovery.json` | | 运行准备 | `run[].source: "provider"`,用 `fromTargets.tags`;`execution` 为 `application`(默认)、`service` 或 `task` | `lithe/build/prepareRun` | [Provider run preparation](../../contract/v1/README.md#provider-run-preparation) | `build-provider-run-preparation`、`build-run-preparation.json` | | 类型化运行选项 | 服务和任务的准备带 `launchOptions`(`execution`、`runtimeArguments`、`arguments`、`environment`,可选 `entrypoint`、`workingDirectory`) | 扩展 `lithe/build/prepareRun` | [Typed run options and service/task preparation](../../contract/v1/README.md#typed-run-options-and-servicetask-preparation) | `build-provider-run-options`、`build-run-options.json` | +| 运行入口(`buildProviders` 1) | 运行声明 `entrypoints: true`,不写 `fromTargets`;`requires` 写 `buildProviders: 1` | `lithe/build/runEntrypoints`(按源文件回答可运行的入口);准备时 `lithe/build/prepareRun` 不带 `target`、带 `launchOptions.entrypoint` | [Run entrypoints](../../contract/v1/README.md#run-entrypoints-buildproviders-1) | `build-provider-run-entrypoints`、`build-run-entrypoints.json` | | 注册表连接调试 | 服务运行声明 `debug: {"configurationType": "…"}`,由宿主选择已启用、声明了该类型且支持 `attach` 的调试适配器 | 沿用 `lithe/build/prepareRun` | [Registry connection debugging](../../contract/v1/README.md#registry-connection-debugging) | `build-connection-debug-options.json`(没有单独的清单示例) | | 原生调试准备 | 运行声明 `debug: {"adapter": "native"}`;`requires` 要有 `debugAdapters: 0`,并申请 `debug.launch`;适配器必须是本插件自己声明的 | `lithe/build/prepareDebug` | [Native debug preparation](../../contract/v1/README.md#native-debug-preparation) | `build-provider-debug-preparation`、`build-debug-preparation.json` | | 只读模型输入 | 消费者声明 `modelInputs`(最多 8 个槽),`requires` 要有 `buildModelInputs: 0` 和 `buildProviders: 0`;生产者声明 `modelSharing` | 沿用模型、依赖和各计划请求,快照在 `params.modelInputs` | [Optional read-only model inputs](../../contract/v1/README.md#optional-read-only-model-inputs) | `build-systems/build-model-producer`、`build-systems/build-model-consumer` | @@ -58,7 +59,7 @@ ### 协商与隔离 -- 宿主发 `capabilities.experimental.litheBuild: {"versions": [0]}`,提供者回答自己选的 `{"version": 0}`。提供者没有回答版本,或回答了宿主没给出的版本,就不用于构建请求;共享形式的提供者仍然服务它的语言。双方都忽略这些对象和请求参数、结果里不认识的字段,所以任何一方都可以增加可选数据;只有对方不能忽略的改动,才会给 `buildProviders` 版本 `1`,协议随之变化。 +- 宿主发 `capabilities.experimental.litheBuild: {"versions": [0, 1]}`,提供者回答自己选的版本,例如 `{"version": 1}`。提供者没有回答版本,或回答了宿主没给出的版本,就不用于构建请求;共享形式的提供者仍然服务它的语言。双方都忽略这些对象和请求参数、结果里不认识的字段,所以任何一方都可以增加可选数据;只有对方不能忽略的改动,才会给 `buildProviders` 版本 `1`,协议随之变化。 - 一个插件、一个构建系统、一个工作区一个进程。两个插件从不共享进程,宿主也从不在进程之间转发消息;每个进程只经自己的标准输入输出与宿主说 JSON-RPC。共享形式只复用同一插件的语言服务器会话。 - 提供者在第一次构建请求时启动(只有用户操作才会发出),在工作区关闭、插件停用,或者包被替换、回滚、卸载之前停止。插件设置改变后,下一次请求重启它,所以启动参数总是反映当前值;退出的提供者由下一次请求重新启动。 - 安装时拒绝这样的包:提供者的启动指向不存在的文件、包外路径或经符号链接的路径,或者打包的可执行文件和运行时不是常规可执行文件。 @@ -134,7 +135,7 @@ Some build tools expose their project model only through their own API (the Grad | --- | --- | | Manifest fields | `buildSystems[].provider`, and `source: "provider"` in individual declarations | | Capability versions | `buildProviders` `0`; every `buildSystems[].provider` needs both `buildSystems: 0` and `buildProviders: 0`, whether it starts its own process or shares a language server; a template-only build plugin omits `buildProviders`. `requires` must list exactly the capabilities the manifest uses; process start is base contract, not a capability, so do not write `requires.serverProcess`. See [versions](../capabilities-and-versions.md#capability-versions-requires) | -| Protocols | `litheBuild` `0`: the host offers `capabilities.experimental.litheBuild: {"versions": [0]}` in `initialize`, and the provider answers `{"version": 0}`. The protocol has no version of its own: it is the version of `buildProviders`; see [process protocol versions](../capabilities-and-versions.md#process-protocol-versions) | +| Protocols | `litheBuild` `0` and `1`: the host offers `capabilities.experimental.litheBuild: {"versions": [0, 1]}` in `initialize`, and the provider answers the newest version it speaks, such as `{"version": 1}`; version `1` only adds `lithe/build/runEntrypoints`. The protocol has no version of its own: it is the version of `buildProviders`; see [process protocol versions](../capabilities-and-versions.md#process-protocol-versions) | | API IDs | [API-29](../api-catalog.md#apis-usable-now): build, tasks, tests, run preparation | | Permissions | `process.build`; `languageServer.launch` for an own-process provider; `debug.launch` for native debug preparation | | Activation events | `onBuildSystem:`; a provider starts on the first build request, which only a user action sends | @@ -153,7 +154,7 @@ Detection never starts a provider: an instance with a `provider` source only rep ### What a provider can do -Every feature belongs to `buildProviders` `0` and uses the same `litheBuild` protocol. Which of them a session uses depends on the sources the manifest declares and on what the host implements. +Every feature but run entrypoints, which belong to `buildProviders` `1`, belongs to `buildProviders` `0`, and all use the same `litheBuild` protocol. Which of them a session uses depends on the sources the manifest declares and on what the host implements. | Feature | Declared in the manifest | Methods | Contract section | Example (in `fixtures/build-providers/` unless noted) | | --- | --- | --- | --- | --- | @@ -163,6 +164,7 @@ Every feature belongs to `buildProviders` `0` and uses the same `litheBuild` pro | Test discovery | A provider test declares `discovery: true`, which needs both `suite` and `case` filters | `lithe/build/discoverTests` | [Test discovery](../../contract/v1/README.md#test-discovery) | `build-test-discovery.json` | | Run preparation | `run[].source: "provider"` with `fromTargets.tags`; `execution` is `application` (default), `service`, or `task` | `lithe/build/prepareRun` | [Provider run preparation](../../contract/v1/README.md#provider-run-preparation) | `build-provider-run-preparation`, `build-run-preparation.json` | | Typed run options | Service and task preparation carry `launchOptions` (`execution`, `runtimeArguments`, `arguments`, `environment`, optional `entrypoint` and `workingDirectory`) | Extends `lithe/build/prepareRun` | [Typed run options and service/task preparation](../../contract/v1/README.md#typed-run-options-and-servicetask-preparation) | `build-provider-run-options`, `build-run-options.json` | +| Run entrypoints (`buildProviders` 1) | A run declares `entrypoints: true` instead of `fromTargets`; `requires` lists `buildProviders: 1` | `lithe/build/runEntrypoints` (the runnable entrypoints of one source file); preparation sends `lithe/build/prepareRun` without `target` and with `launchOptions.entrypoint` | [Run entrypoints](../../contract/v1/README.md#run-entrypoints-buildproviders-1) | `build-provider-run-entrypoints`, `build-run-entrypoints.json` | | Registry connection debugging | A service run declares `debug: {"configurationType": "…"}`, and the host picks an enabled debug adapter that advertises the type and supports `attach` | The same `lithe/build/prepareRun` | [Registry connection debugging](../../contract/v1/README.md#registry-connection-debugging) | `build-connection-debug-options.json` (no manifest example of its own) | | Native debug preparation | A run declares `debug: {"adapter": "native"}`; `requires` needs `debugAdapters: 0`, the plugin requests `debug.launch`, and the adapter must be one the plugin declares itself | `lithe/build/prepareDebug` | [Native debug preparation](../../contract/v1/README.md#native-debug-preparation) | `build-provider-debug-preparation`, `build-debug-preparation.json` | | Read-only model inputs | A consumer declares `modelInputs` (at most 8 slots), and `requires` needs `buildModelInputs: 0` and `buildProviders: 0`; a producer declares `modelSharing` | The model, dependency, and plan requests; the snapshot is in `params.modelInputs` | [Optional read-only model inputs](../../contract/v1/README.md#optional-read-only-model-inputs) | `build-systems/build-model-producer`, `build-systems/build-model-consumer` | @@ -177,7 +179,7 @@ Every feature belongs to `buildProviders` `0` and uses the same `litheBuild` pro ### Negotiation and isolation -- The host sends `capabilities.experimental.litheBuild: {"versions": [0]}`, and the provider answers the `{"version": 0}` it chose. A provider that answers no version, or one the host did not offer, is not used for build requests; a shared provider still serves its language. Both sides ignore fields they do not know in these objects and in request params and results, so either side can add optional data; only a change the other side must not ignore gives `buildProviders` version `1`, and the protocol moves with it. +- The host sends `capabilities.experimental.litheBuild: {"versions": [0, 1]}`, and the provider answers the version it chose, such as `{"version": 1}`. A provider that answers no version, or one the host did not offer, is not used for build requests; a shared provider still serves its language. Both sides ignore fields they do not know in these objects and in request params and results, so either side can add optional data; only a change the other side must not ignore gives `buildProviders` version `1`, and the protocol moves with it. - One process per plugin, build system, and workspace. Two plugins never share a process, and the host never relays messages between processes; each speaks JSON-RPC only with the host, over its own stdio. The shared form reuses a language server session of the same plugin only. - A provider starts on the first build request, which only a user action sends, and stops when its workspace closes, its plugin is disabled, or before its package is replaced, rolled back, or uninstalled. A change of the plugin's settings restarts it on the next request, so its launch arguments always reflect the current values; a provider that exits is started again by the next request. - Installation refuses a package whose provider launch points at a missing file, a path outside the package or through a symbolic link, or a packaged executable or runtime that is not a regular executable file. diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 18a92a78..a73dec47 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -39,6 +39,7 @@ | `backend` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildModelInputs` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| `buildProviders` | 1 | 2026-11-18 | [#89](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/89) | | `buildSystems` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `commandInstallers` | 0 | 2026-11-15 | [#53](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/53) | | `debugAdapters` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | @@ -66,6 +67,7 @@ | --- | --- | --- | --- | | `litheFunctions`(`backend`) | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `litheBuild`(`buildProviders`) | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| `litheBuild`(`buildProviders`) | 1 | 2026-11-18 | [#89](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/89) | | `litheVcs`(`vcsProviders`) | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `litheToolchains`(`toolchainProviders`) | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `litheKeymapImport`(`keymapImportProviders`) | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | @@ -138,6 +140,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#89](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/89) | [@1lck](https://github.com/1lck) | — | **`buildProviders` 1**、**`litheBuild` 1** | 按源文件找运行入口([1lck/Lithe-IDEA#2104](https://github.com/1lck/Lithe-IDEA/issues/2104)):运行声明可写 `entrypoints: true`(只能是提供者的 `application`,不写 `fromTargets`、`fromTasks`、`arguments`、`extension`、`debug`),它不对应任何目标,宿主不按目标列出它。新提供者方法 `lithe/build/runEntrypoints`(参数多一个工作区相对路径 `file`)返回 `litheRunEntrypoints` 0 文档,列出这个文件里可运行的入口 `{run, name, entrypoint, project}`,最多 64 个;Core 新增 `build.runEntrypointsPlan` 和 `build.decodeRunEntrypoints` 校验。`lithe/build/prepareRun` 对入口运行不带 `target`,必须带 `launchOptions.entrypoint`。宿主提供 `litheBuild` 版本 `[0, 1]`,三个 SDK 回答宿主提供的最新版本,Java/Node SDK 新增 `onRunEntrypoints`/`build.runEntrypoints`。用入口运行的插件声明 `buildProviders: 1`,只支持 0 的宿主不会安装;其他插件不受影响。新增 fixture `build-provider-run-entrypoints.plugin.json`、`build-run-entrypoints.json`。没有新增宿主方法或通知。 | | [#85](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/85) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 插件清单 `schemaVersion` 0 内的补充 | 清单新增可选字段 `repository`([1lck/Lithe-IDEA#2100](https://github.com/1lck/Lithe-IDEA/issues/2100)):值是插件源码仓库的 GitHub 地址 `https://github.com/<作者>/<仓库>`,格式不对时以 `plugin.manifest.invalid`(字段 `repository`)拒绝。项目里由插件提供的 Run 配置改存 `.lithe/run/plugin/<插件 ID>.toml`(共享)和 `<插件 ID>.local.toml`(本机),文件头 `[plugin]` 记录插件 ID、名称、作者、仓库、版本、版本要求(默认 `>=保存时的版本`)、`pluginAPIVersion` 和用到的能力,作者和仓库取自 `repository`,用来区分同名插件;插件没有安装、仓库不一致或版本不满足要求时,这些配置在 Run 列表里显示为不可用并说明原因,不会让整个列表读取失败。Core 自带的脚本和程序运行(shell、PowerShell、Windows 批处理、可执行文件)不依赖任何插件。没写 `repository` 的插件照常安装,Run 文件里不记作者和仓库、也不比对仓库;清单格式和能力版本不变,没有新增宿主方法或通知。 | ### 2026-11-17