From 9a0190e72e97303a485e28fe8867a9fb602822bc Mon Sep 17 00:00:00 2001 From: mirakyux Date: Mon, 23 Nov 2026 22:33:29 +0800 Subject: [PATCH 1/2] feat(plugin-api): add editor color decorations --- rust/contracts/rust-core-api.md | 16 +- rust/crates/plugin-editor/src/providers.rs | 490 +++++++++++++++++- shared/plugins/contract/v1/README.md | 36 +- .../v1/editor-color-decorations.schema.json | 95 ++++ .../v1/fixtures/editor/editor-providers.json | 57 +- shared/plugins/reference/api-catalog.md | 12 +- shared/plugins/reference/domains/editor.md | 16 +- .../plugins/reference/protocol-changelog.md | 1 + shared/plugins/sdk/e2e/plugin_sdk/backend.rs | 1 + shared/plugins/sdk/e2e/plugin_sdk/colors.rs | 117 +++++ shared/plugins/sdk/e2e/plugin_sdk/mod.rs | 6 +- shared/plugins/sdk/e2e/plugin_sdk_go.rs | 8 + shared/plugins/sdk/e2e/plugin_sdk_java.rs | 15 + shared/plugins/sdk/e2e/plugin_sdk_node.rs | 15 + shared/plugins/sdk/e2e/plugin_sdk_rust.rs | 8 + .../sdk/go/examples/sample-backend/main.go | 12 + .../org/example/samplebuild/SampleBuild.java | 4 + .../examples/sample-build/backend/main.mjs | 4 + .../rust/examples/sample-backend/src/main.rs | 12 + 19 files changed, 883 insertions(+), 42 deletions(-) create mode 100644 shared/plugins/contract/v1/editor-color-decorations.schema.json create mode 100644 shared/plugins/sdk/e2e/plugin_sdk/colors.rs diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 4fe6cdc9..030e608d 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5389,10 +5389,11 @@ actions section. (the provider types the host routes) and returns `{registration}` with lowercased literal selectors and Core's per-type `budgetMs`; a type outside `types` is `not_supported` with details `providers.`. It also accepts -`{kind:"result",type,value,legend?}` (one provider function's LSP 3.17 shaped -result; semantic tokens need the registered legend) and returns `{result}` -normalized to `{locations}`, `{contents,range?}`, `{isIncomplete,items}`, -`{lenses}`, `{ranges}`, `{data}` or `{links}`. Hosts own calls, budgets, +`{kind:"result",type,value,legend?,colorLegend?}` (one provider function's +result; semantic tokens need the registered token legend and color decorations +need the registered color legend) and returns `{result}` normalized to +`{locations}`, `{contents,range?}`, `{isIncomplete,items}`, `{lenses}`, +`{ranges}`, `{data}`, `{decorations}` or `{links}`. Hosts own calls, budgets, stale-version drops and the merge after language-server answers; see the plugin contract's editor language-feature providers section. The definition merge is Core's too: `{kind:"mergeDefinitions",value:{documentUri,position,server,plugin}}` @@ -5400,7 +5401,12 @@ takes the language server's and the plugins' validated `Location[]` and returns the indices each side keeps as `{server,plugin}`. The server's answer comes first; a plugin location equal to one already kept is dropped, and a server location that covers the requested position itself (the caret already sits on -the declaration) yields when a plugin answered. +the declaration) yields when a plugin answered. Color decorations also merge +in Core: `{kind:"mergeColorDecorations",value:{sources:[{sourceId,colorLegend,value}]}}` +validates each source's light/dark color legend and non-overlapping, single-line +UTF-16 ranges, sorts sources by `sourceId`, and clips later ranges where an +earlier source already covers a position. The ordered result is +`{decorations:[{sourceId,colorId,light,dark,range}]}`. `toolchains.instantiateLaunch` accepts `{ registry, tool, executable, home?, entry?, runtimeArguments, arguments }` and returns `{ status: "ok", launch: diff --git a/rust/crates/plugin-editor/src/providers.rs b/rust/crates/plugin-editor/src/providers.rs index ba4fff9e..70907361 100644 --- a/rust/crates/plugin-editor/src/providers.rs +++ b/rust/crates/plugin-editor/src/providers.rs @@ -1,19 +1,18 @@ //! Editor language-feature providers a plugin backend registers through //! `lithe/host/editor/registerProviders`. //! -//! Core validates registrations and the LSP 3.17 shaped results of each -//! provider function, and owns the per-type answer budgets. Hosts own the -//! document versions, the calls and the merge with language-server results: -//! a language server answers first and a plugin only supplements it. Core -//! never interprets selectors, function names or result payloads beyond -//! their shape, so no tool or language has a branch here. +//! Core validates registrations and provider results, and owns the per-type +//! answer budgets. Hosts own document versions and calls. Language-feature +//! providers supplement language-server results; color decorations are merged +//! in stable source order so overlapping plugin colors are deterministic. +//! Core never interprets selectors, function names or tool-specific payloads. use crate::actions::{normalize_names, uri, Location, LspPosition, LspRange}; use lithe_plugin_model::is_function_id; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; /// Provider types Core can validate, in the order the contract lists them. pub const PROVIDER_TYPES: &[&str] = &[ @@ -23,6 +22,7 @@ pub const PROVIDER_TYPES: &[&str] = &[ "codeLens", "foldingRange", "semanticTokens", + "colorDecorations", "documentLink", ]; @@ -35,6 +35,10 @@ const MAX_COMPLETION_ITEMS: usize = 5000; const MAX_CODE_LENSES: usize = 1000; const MAX_FOLDING_RANGES: usize = 5000; const MAX_DOCUMENT_LINKS: usize = 1000; +const MAX_COLOR_DECORATIONS: usize = 10_000; +const MAX_COLOR_DECORATION_SOURCES: usize = 64; +const MAX_COLOR_DECORATION_SOURCE_ID_BYTES: usize = 257; +const MAX_MERGED_COLOR_DECORATIONS: usize = 10_000; const MAX_HOVER_BYTES: usize = 64 * 1024; /// Semantic token integers: five per token, 1 MiB of 4-byte integers. const MAX_SEMANTIC_TOKEN_INTEGERS: usize = 1024 * 1024 / 4; @@ -81,6 +85,15 @@ struct Legend { token_modifiers: Vec, } +/// The light- and dark-appearance colors registered for one provider. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DecorationColor { + id: String, + light: String, + dark: String, +} + /// One provider entry: the plugin function the host calls and the options /// its type takes. `budgetMs` is Core's output, never the plugin's input. #[derive(Debug, Deserialize, Serialize)] @@ -91,6 +104,8 @@ struct Provider { trigger_characters: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] legend: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + color_legend: Option>, #[serde(default, skip_deserializing)] budget_ms: u64, } @@ -118,6 +133,9 @@ struct Payload { /// For a semantic tokens result, the legend the provider registered. #[serde(default)] legend: Option, + /// For a color decoration result, the colors declared by its registration. + #[serde(default)] + color_legend: Option>, } fn registration(value: Value, types: &[String]) -> Result { @@ -172,6 +190,7 @@ fn registration(value: Value, types: &[String]) -> Result { let options_fit = match kind.as_str() { "completion" => { provider.legend.is_none() + && provider.color_legend.is_none() && provider.trigger_characters.len() <= MAX_TRIGGER_CHARACTERS && triggers.len() == provider.trigger_characters.len() && provider.trigger_characters.iter().all(|character| { @@ -183,9 +202,22 @@ fn registration(value: Value, types: &[String]) -> Result { } "semanticTokens" => { provider.trigger_characters.is_empty() + && provider.color_legend.is_none() && provider.legend.as_ref().is_some_and(legend_valid) } - _ => provider.trigger_characters.is_empty() && provider.legend.is_none(), + "colorDecorations" => { + provider.trigger_characters.is_empty() + && provider.legend.is_none() + && provider + .color_legend + .as_deref() + .is_some_and(color_legend_valid) + } + _ => { + provider.trigger_characters.is_empty() + && provider.legend.is_none() + && provider.color_legend.is_none() + } }; if !is_function_id(&provider.function) || !options_fit { return Err(invalid(format!("Invalid {kind} provider options."))); @@ -214,6 +246,29 @@ fn legend_valid(legend: &Legend) -> bool { !legend.token_types.is_empty() && names(&legend.token_types) && names(&legend.token_modifiers) } +fn color_legend_valid(colors: &[DecorationColor]) -> bool { + let ids: BTreeSet<&str> = colors.iter().map(|color| color.id.as_str()).collect(); + !colors.is_empty() + && colors.len() <= MAX_LEGEND_ENTRIES + && ids.len() == colors.len() + && colors.iter().all(|color| { + identifier(&color.id) + && color.id.as_bytes()[0].is_ascii_alphanumeric() + && color + .id + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')) + && hex_color_valid(&color.light) + && hex_color_valid(&color.dark) + }) +} + +fn hex_color_valid(value: &str) -> bool { + value.len() == 7 + && value.starts_with('#') + && value[1..].bytes().all(|byte| byte.is_ascii_hexdigit()) +} + fn range(value: &Value) -> Option { let range: LspRange = serde_json::from_value(value.clone()).ok()?; range.ordered().then(|| json!(range)) @@ -521,6 +576,247 @@ fn semantic_tokens(value: Value, legend: Option<&Legend>) -> Result, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +struct DecorationSpan { + line: u32, + start: u32, + end: u32, +} + +#[derive(Debug)] +struct ParsedColorDecoration { + span: DecorationSpan, + color_id: String, +} + +fn parse_color_decorations( + value: Value, + colors: &[DecorationColor], +) -> Result, CoreError> { + if !color_legend_valid(colors) { + return Err(invalid( + "A color decoration result needs its registered color legend.", + )); + } + let result: ColorDecorationResult = serde_json::from_value(value) + .map_err(|_| invalid("A color decoration result has a decorations array."))?; + if result.decorations.len() > MAX_COLOR_DECORATIONS { + return Err(invalid("A color decoration result exceeds 10000 ranges.")); + } + let known_colors: BTreeSet<&str> = colors.iter().map(|color| color.id.as_str()).collect(); + let mut decorations = Vec::with_capacity(result.decorations.len()); + for decoration in result.decorations { + let range = decoration.range; + if !range.ordered() + || range.start.line != range.end.line + || range.start.character >= range.end.character + || !known_colors.contains(decoration.color_id.as_str()) + { + return Err(invalid( + "A color decoration has a nonempty single-line range and a registered color ID.", + )); + } + decorations.push(ParsedColorDecoration { + span: DecorationSpan { + line: range.start.line, + start: range.start.character, + end: range.end.character, + }, + color_id: decoration.color_id, + }); + } + decorations.sort_by_key(|decoration| decoration.span); + if decorations + .windows(2) + .any(|pair| pair[0].span.line == pair[1].span.line && pair[0].span.end > pair[1].span.start) + { + return Err(invalid( + "Color decoration ranges from one source must not overlap.", + )); + } + Ok(decorations) +} + +fn color_decorations(value: Value, colors: Option<&[DecorationColor]>) -> Result { + let colors = + colors.ok_or_else(|| invalid("A color decoration result needs its color legend."))?; + let decorations = parse_color_decorations(value, colors)?; + Ok(json!({"decorations": decorations.iter().map(|decoration| { + let span = decoration.span; + json!({"range": {"start": {"line": span.line, "character": span.start}, + "end": {"line": span.line, "character": span.end}}, "colorId": decoration.color_id}) + }).collect::>() })) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ColorDecorationSource { + source_id: String, + color_legend: Vec, + value: Value, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ColorDecorationMerge { + sources: Vec, +} + +#[derive(Default)] +struct ColorDecorationEvents { + ends: Vec, + starts: Vec<(usize, String)>, +} + +struct MergedColorDecoration { + source_id: String, + color_id: String, + light: String, + dark: String, + span: DecorationSpan, +} + +/// Merges provider colors by stable source identity. The lexicographically +/// earlier source wins at each UTF-16 position; later ranges are clipped to +/// the still-uncovered portions. +fn merge_color_decorations(value: Value) -> Result { + let mut merge: ColorDecorationMerge = serde_json::from_value(value) + .map_err(|_| invalid("A color decoration merge has sources."))?; + if merge.sources.len() > MAX_COLOR_DECORATION_SOURCES { + return Err(invalid("A color decoration merge exceeds 64 sources.")); + } + merge + .sources + .sort_by(|left, right| left.source_id.cmp(&right.source_id)); + if merge.sources.iter().any(|source| { + source.source_id.is_empty() + || source.source_id.len() > MAX_COLOR_DECORATION_SOURCE_ID_BYTES + || source.source_id.chars().any(char::is_control) + }) || merge + .sources + .windows(2) + .any(|pair| pair[0].source_id == pair[1].source_id) + { + return Err(invalid( + "Color decoration source IDs must be unique and valid.", + )); + } + + let mut events: BTreeMap<(u32, u32), ColorDecorationEvents> = BTreeMap::new(); + let mut source_colors = Vec::with_capacity(merge.sources.len()); + let mut input_count = 0usize; + for (source_index, source) in merge.sources.iter().enumerate() { + if !color_legend_valid(&source.color_legend) { + return Err(invalid( + "A color decoration source has an invalid color legend.", + )); + } + let decorations = parse_color_decorations(source.value.clone(), &source.color_legend)?; + input_count += decorations.len(); + if input_count > MAX_COLOR_DECORATIONS { + return Err(invalid("A color decoration merge exceeds 10000 ranges.")); + } + for decoration in decorations { + events + .entry((decoration.span.line, decoration.span.start)) + .or_default() + .starts + .push((source_index, decoration.color_id)); + events + .entry((decoration.span.line, decoration.span.end)) + .or_default() + .ends + .push(source_index); + } + source_colors.push( + source + .color_legend + .iter() + .map(|color| (color.id.as_str(), color)) + .collect::>(), + ); + } + + let mut active: BTreeMap = BTreeMap::new(); + let mut active_line = None; + let mut merged: Vec = Vec::new(); + let mut positions = events.iter().peekable(); + while let Some((&(line, character), event)) = positions.next() { + if active_line != Some(line) { + active.clear(); + active_line = Some(line); + } + for source_index in &event.ends { + active.remove(source_index); + } + for (source_index, color_id) in &event.starts { + active.insert(*source_index, color_id.clone()); + } + let Some((&(next_line, next_character), _)) = positions.peek() else { + continue; + }; + if next_line != line || next_character <= character { + continue; + } + let Some((&source_index, color_id)) = active.first_key_value() else { + continue; + }; + let source = &merge.sources[source_index]; + let color = source_colors[source_index][color_id.as_str()]; + let span = DecorationSpan { + line, + start: character, + end: next_character, + }; + if let Some(previous) = merged.last_mut() { + if previous.source_id == source.source_id + && previous.color_id == *color_id + && previous.span.line == span.line + && previous.span.end == span.start + { + previous.span.end = span.end; + continue; + } + } + merged.push(MergedColorDecoration { + source_id: source.source_id.clone(), + color_id: color_id.clone(), + light: color.light.clone(), + dark: color.dark.clone(), + span, + }); + if merged.len() > MAX_MERGED_COLOR_DECORATIONS { + return Err(invalid( + "A merged color decoration result exceeds 10000 ranges.", + )); + } + } + let result = json!({"decorations": merged.into_iter().map(|decoration| { + let span = decoration.span; + json!({"sourceId": decoration.source_id, "colorId": decoration.color_id, + "light": decoration.light, "dark": decoration.dark, + "range": {"start": {"line": span.line, "character": span.start}, + "end": {"line": span.line, "character": span.end}}}) + }).collect::>() }); + if result.to_string().len() > MAX_BYTES { + return Err(invalid("A merged color decoration result exceeds 1 MiB.")); + } + Ok(result) +} + fn document_link(value: Value) -> Result { let items = list(value, MAX_DOCUMENT_LINKS, "document link")?; let mut links = Vec::with_capacity(items.len()); @@ -599,11 +895,9 @@ fn merge_definitions(value: Value) -> Result { Ok(json!({ "server": server, "plugin": plugin })) } -/// Validates a provider registration (`kind: registration`, with the -/// host's `types`) or one provider function's result (`kind: result`, with -/// its `type` and, for semantic tokens, the registered `legend`). Results -/// come back normalized. `kind: mergeDefinitions` applies the merge rule of -/// definitions. No I/O occurs. +/// Validates a provider registration or one provider function's result. +/// Results come back normalized. Merge kinds apply deterministic cross-source +/// rules for definitions and color decorations. No I/O occurs. pub fn decode_command(payload: Value) -> Result { let payload: Payload = serde_json::from_value(payload) .map_err(|_| invalid("Invalid editor provider validation payload."))?; @@ -615,6 +909,7 @@ pub fn decode_command(payload: Value) -> Result { Ok(json!({ "registration": registration(payload.value, &payload.types)? })) } ("mergeDefinitions", None) => merge_definitions(payload.value), + ("mergeColorDecorations", None) => merge_color_decorations(payload.value), ("result", Some(kind)) => Ok(json!({ "result": match kind { "definition" => definition(payload.value)?, "hover" => hover(payload.value)?, @@ -622,6 +917,7 @@ pub fn decode_command(payload: Value) -> Result { "codeLens" => code_lens(payload.value)?, "foldingRange" => folding_range(payload.value)?, "semanticTokens" => semantic_tokens(payload.value, payload.legend.as_ref())?, + "colorDecorations" => color_decorations(payload.value, payload.color_legend.as_deref())?, "documentLink" => document_link(payload.value)?, _ => return Err(invalid("Unknown editor provider type.")), }})), @@ -765,6 +1061,158 @@ mod tests { .map(|value| value["result"].clone()) } + fn color_result(value: Value, color_legend: Value) -> Result { + decode_command( + json!({"kind":"result","type":"colorDecorations","value":value, + "colorLegend":color_legend}), + ) + .map(|value| value["result"].clone()) + } + + fn color_source(source_id: &str, color_id: &str, start: u32, end: u32) -> Value { + json!({"sourceId":source_id, + "colorLegend":[{"id":color_id,"light":"#112233","dark":"#445566"}], + "value":{"decorations":[{"range":{"start":{"line":0,"character":start}, + "end":{"line":0,"character":end}},"colorId":color_id}]}}) + } + + #[test] + fn color_decoration_registration_results_and_merges_are_deterministic() { + let registration = decode_command(json!({"kind":"registration","types":types(),"value":{ + "id":"rainbow","selector":{"fileExtensions":["rs"]}, + "providers":{"colorDecorations":{"function":"rainbow.decorate","colorLegend":[ + {"id":"depth-0","light":"#112233","dark":"#445566"}]}} + }})) + .unwrap(); + assert_eq!( + registration["registration"]["providers"]["colorDecorations"]["budgetMs"], + 2000 + ); + + let colors = json!([{"id":"depth-0","light":"#112233","dark":"#445566"}]); + let decoration = |start, end| { + json!({"range":{"start":{"line":0,"character":start}, + "end":{"line":0,"character":end}},"colorId":"depth-0"}) + }; + assert_eq!( + color_result(json!({"decorations":[decoration(2, 5)]}), colors.clone()).unwrap(), + json!({"decorations":[decoration(2, 5)]}) + ); + for value in [ + json!({"decorations":[decoration(2, 2)]}), + json!({"decorations":[decoration(5, 2)]}), + json!({"decorations":[decoration(2, 5), decoration(4, 7)]}), + json!({"decorations":[{"range":{"start":{"line":0,"character":2}, + "end":{"line":1,"character":0}},"colorId":"depth-0"}]}), + json!({"decorations":[{"range":{"start":{"line":0,"character":2}, + "end":{"line":0,"character":5}},"colorId":"unknown"}]}), + ] { + assert!(color_result(value, colors.clone()).is_err()); + } + + let merged = decode_command(json!({"kind":"mergeColorDecorations","value":{"sources":[ + {"sourceId":"z-plugin/1","colorLegend":[{"id":"z","light":"#112233","dark":"#445566"}], + "value":{"decorations":[{"range":{"start":{"line":0,"character":1},"end":{"line":0,"character":8}},"colorId":"z"}]}}, + {"sourceId":"a-plugin/1","colorLegend":[{"id":"a","light":"#AABBCC","dark":"#DDEEFF"}], + "value":{"decorations":[{"range":{"start":{"line":0,"character":3},"end":{"line":0,"character":5}},"colorId":"a"}]}} + ]}})).unwrap(); + assert_eq!( + merged["decorations"], + json!([ + {"sourceId":"z-plugin/1","colorId":"z","light":"#112233","dark":"#445566", + "range":{"start":{"line":0,"character":1},"end":{"line":0,"character":3}}}, + {"sourceId":"a-plugin/1","colorId":"a","light":"#AABBCC","dark":"#DDEEFF", + "range":{"start":{"line":0,"character":3},"end":{"line":0,"character":5}}}, + {"sourceId":"z-plugin/1","colorId":"z","light":"#112233","dark":"#445566", + "range":{"start":{"line":0,"character":5},"end":{"line":0,"character":8}}} + ]) + ); + let merged_reversed = decode_command(json!({"kind":"mergeColorDecorations","value":{"sources":[ + {"sourceId":"a-plugin/1","colorLegend":[{"id":"a","light":"#AABBCC","dark":"#DDEEFF"}], + "value":{"decorations":[{"range":{"start":{"line":0,"character":3},"end":{"line":0,"character":5}},"colorId":"a"}]}}, + color_source("z-plugin/1", "z", 1, 8) + ]}})).unwrap(); + assert_eq!(merged_reversed, merged); + } + + #[test] + fn color_decoration_legends_and_merge_limits_are_enforced() { + for colors in [ + json!([]), + json!([{"id":"x","light":"red","dark":"#445566"}]), + json!([{"id":"x","light":"#112233","dark":"#445566"},{"id":"x","light":"#000000","dark":"#000000"}]), + ] { + assert!(decode_command(json!({"kind":"registration","types":types(),"value":{ + "id":"rainbow","selector":{"fileExtensions":["rs"]}, + "providers":{"colorDecorations":{"function":"rainbow.decorate","colorLegend":colors}} + }})).is_err()); + } + assert!( + decode_command(json!({"kind":"mergeColorDecorations","value":{"sources":[ + color_source("same", "x", 0, 1), color_source("same", "x", 2, 3) + ]}})) + .is_err() + ); + assert!( + decode_command(json!({"kind":"mergeColorDecorations","value":{"sources": + vec![color_source("plugin", "x", 0, 1); MAX_COLOR_DECORATION_SOURCES + 1] + }})) + .is_err() + ); + let long_source_id = "x".repeat(MAX_COLOR_DECORATION_SOURCE_ID_BYTES + 1); + assert!( + decode_command(json!({"kind":"mergeColorDecorations","value":{"sources":[ + color_source(&long_source_id, "x", 0, 1) + ]}})) + .is_err() + ); + + let over_limit = (0..=MAX_COLOR_DECORATIONS) + .map(|index| { + json!({"range":{"start":{"line":0,"character":index * 2}, + "end":{"line":0,"character":index * 2 + 1}},"colorId":"x"}) + }) + .collect::>(); + let colors = vec![DecorationColor { + id: "x".into(), + light: "#112233".into(), + dark: "#445566".into(), + }]; + assert!(parse_color_decorations(json!({"decorations":over_limit}), &colors).is_err()); + + let many_ranges = (0..3000) + .map(|index| { + json!({"range":{"start":{"line":0,"character":index * 2}, + "end":{"line":0,"character":index * 2 + 1}},"colorId":"x"}) + }) + .collect::>(); + assert!( + decode_command(json!({"kind":"mergeColorDecorations","value":{"sources":[{ + "sourceId":"x".repeat(MAX_COLOR_DECORATION_SOURCE_ID_BYTES), + "colorLegend":[{"id":"x","light":"#112233","dark":"#445566"}], + "value":{"decorations":many_ranges} + }]}})) + .is_err() + ); + + let many_ranges = |prefix: u32| { + (0..=MAX_COLOR_DECORATIONS / 2) + .map(|index| { + let start = prefix + index as u32 * 2; + json!({"range":{"start":{"line":0,"character":start}, + "end":{"line":0,"character":start + 1}},"colorId":"x"}) + }) + .collect::>() + }; + assert!(merge_color_decorations(json!({"sources":[ + {"sourceId":"a","colorLegend":[{"id":"x","light":"#112233","dark":"#445566"}], + "value":{"decorations":many_ranges(0)}}, + {"sourceId":"b","colorLegend":[{"id":"x","light":"#112233","dark":"#445566"}], + "value":{"decorations":many_ranges(MAX_COLOR_DECORATIONS as u32 + 2)}} + ]})) + .is_err()); + } + #[test] fn results_normalize_lsp_shapes() { let span = json!({"start":{"line":1,"character":2},"end":{"line":1,"character":8}}); @@ -901,6 +1349,9 @@ mod tests { if let Some(legend) = case.get("legend") { payload["legend"] = legend.clone(); } + if let Some(color_legend) = case.get("colorLegend") { + payload["colorLegend"] = color_legend.clone(); + } let decoded = decode_command(payload); match case["expected"]["status"].as_str().unwrap() { "accepted" => assert_eq!( @@ -911,5 +1362,18 @@ mod tests { _ => assert!(decoded.is_err(), "{name}"), } } + for case in fixture["merges"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let decoded = + decode_command(json!({"kind":"mergeColorDecorations","value":case["value"]})); + match case["expected"]["status"].as_str().unwrap() { + "accepted" => assert_eq!( + decoded.unwrap_or_else(|error| panic!("{name}: {error:?}"))["decorations"], + case["expected"]["decorations"], + "{name}" + ), + _ => assert!(decoded.is_err(), "{name}"), + } + } } } diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 55db84a5..959757c6 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4844,7 +4844,9 @@ per workspace context: "hover": {"function": "keys.hover"}, "completion": {"function": "keys.complete", "triggerCharacters": ["."]}, "semanticTokens": {"function": "keys.tokens", - "legend": {"tokenTypes": ["property", "string"], "tokenModifiers": ["declaration"]}} + "legend": {"tokenTypes": ["property", "string"], "tokenModifiers": ["declaration"]}}, + "colorDecorations": {"function": "rainbow.decorate", + "colorLegend": [{"id": "depth-0", "light": "#B03060", "dark": "#F08AAA"}]} } } ``` @@ -4857,16 +4859,27 @@ per workspace context: (optional leading dot) and literal file names, matched case-insensitively. A document matches when any entry matches. At most 32 registrations per plugin across contexts; duplicate IDs in a context are refused. -- `providers` maps a provider type to `{function}`. The Lithe desktop host routes +- `providers` maps a provider type to its function and any type-specific options. The Lithe desktop host routes `definition`, `hover`, `completion`, `codeLens`, `foldingRange`, - `semanticTokens` and `documentLink`. Completion may add 1 to 16 + `semanticTokens`, `colorDecorations` and `documentLink`. Completion may add 1 to 16 single-character `triggerCharacters`; semantic tokens must add their - `legend` (at most 64 types and 64 modifiers). A type outside the host's + `legend` (at most 64 types and 64 modifiers). `colorDecorations` adds a + `colorLegend` of 1 to 64 unique `{id, light, dark}` entries; each color is + `#RRGGBB`. The provider returns `{decorations: [{range, colorId}]}` with + nonempty, single-line, zero-based UTF-16 ranges. Ranges from one source may + touch but must not overlap. Each provider result is limited to 10,000 ranges. + A merged answer accepts at most 64 sources and 10,000 input ranges total; + its output is limited to 10,000 ranges and 1 MiB. A type + outside the host's `providerTypes` fails with `unsupportedOption` and `details.option: "providers."` before anything is registered. Diagnostics are not a provider type. +- The [`colorDecorations` registration and result schema](editor-color-decorations.schema.json) + describes the provider-specific JSON shape. Registration itself remains a + runtime `editor/registerProviders` request and is validated by Core, not a + plugin manifest field. - The host calls the function through `lithe/function/invoke` with the - workspace context and `{documentID,version}`; definition, hover and + workspace context and `params: {document: {documentID, version}}`; definition, hover and completion add `position: {line,character}` (zero-based, UTF-16), and completion adds `triggerCharacter` when typing started it. The plugin reads the text with `documents/getSnapshot` and answers for that version. @@ -4874,7 +4887,8 @@ per workspace context: `Location | Location[] | LocationLink[] | null`, `Hover | null`, `CompletionItem[] | CompletionList | null` (no `data`, `command` or resolve round trip), `CodeLens[] | null`, `FoldingRange[] | null`, - `SemanticTokens | null` indexed by the registered legend, and + `SemanticTokens | null` indexed by the registered legend, + `{decorations: [{range, colorId}]}` for `colorDecorations`, and `DocumentLink[] | null` with absolute targets. Every code lens carries its `command`, whose `command` is a function of the same plugin and whose `arguments` holds at most one params object; a click calls that function @@ -4887,7 +4901,15 @@ per workspace context: server's; definitions add plugin locations to the server's (a location at the requested position itself yields to the plugin's); code lenses, folding ranges and links are added; semantic tokens apply only to files whose - language server has none. A plugin location equal to one already kept is + language server has none. Color decorations are independent of semantic + tokens and are merged across matching sources by + `plugins.editorProviders.decode` with `kind: "mergeColorDecorations"`. + The host supplies sources using the stable `sourceId` form + `/`. Core sorts sources by `sourceId` using + Unicode code-point order; the lexicographically earliest source wins at + each UTF-16 position, and later ranges are clipped to uncovered portions. + The merged result is sorted by line and start position and contains resolved + light/dark colors. A plugin location equal to one already kept is dropped. The merge is Core command `plugins.editorProviders.decode` with `kind: "mergeDefinitions"`, so every host merges definitions alike. - Validation is shared Core command `plugins.editorProviders.decode`. Cases: diff --git a/shared/plugins/contract/v1/editor-color-decorations.schema.json b/shared/plugins/contract/v1/editor-color-decorations.schema.json new file mode 100644 index 00000000..903ca45d --- /dev/null +++ b/shared/plugins/contract/v1/editor-color-decorations.schema.json @@ -0,0 +1,95 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/Lithe-IDEA/Lithe-core-rust/main/shared/plugins/contract/v1/editor-color-decorations.schema.json", + "title": "Editor color decoration provider (plugin contract v1)", + "description": "Registration options and function result for the colorDecorations provider on editor/registerProviders. Core enforces cross-field rules JSON Schema cannot express, including unique color IDs, same-line ordered UTF-16 ranges, non-overlap within one source, and the 10,000-decoration budget.", + "$defs": { + "color": { + "type": "object", + "additionalProperties": false, + "required": ["id", "light", "dark"], + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$" + }, + "light": { "$ref": "#/$defs/rgb" }, + "dark": { "$ref": "#/$defs/rgb" } + } + }, + "rgb": { + "type": "string", + "pattern": "^#[0-9A-Fa-f]{6}$", + "description": "An opaque RGB foreground color in #RRGGBB form." + }, + "colorLegend": { + "type": "array", + "minItems": 1, + "maxItems": 64, + "items": { "$ref": "#/$defs/color" }, + "description": "Color IDs must be unique within the provider registration." + }, + "position": { + "type": "object", + "additionalProperties": false, + "required": ["line", "character"], + "properties": { + "line": { "type": "integer", "minimum": 0, "maximum": 4294967295 }, + "character": { "type": "integer", "minimum": 0, "maximum": 4294967295 } + }, + "description": "A zero-based LSP position; character counts UTF-16 code units." + }, + "range": { + "type": "object", + "additionalProperties": false, + "required": ["start", "end"], + "properties": { + "start": { "$ref": "#/$defs/position" }, + "end": { "$ref": "#/$defs/position" } + }, + "description": "Core requires a nonempty, ordered range on one line." + }, + "decoration": { + "type": "object", + "additionalProperties": false, + "required": ["range", "colorId"], + "properties": { + "range": { "$ref": "#/$defs/range" }, + "colorId": { "type": "string", "minLength": 1, "maxLength": 128 } + }, + "description": "colorId must name an entry in the registration's colorLegend." + } + }, + "oneOf": [ + { + "title": "Registration options", + "type": "object", + "additionalProperties": false, + "required": ["function", "colorLegend"], + "properties": { + "function": { + "type": "string", + "maxLength": 128, + "pattern": "^([a-z][A-Za-z0-9]*)(\\.[a-z][A-Za-z0-9]*)*$" + }, + "colorLegend": { "$ref": "#/$defs/colorLegend" } + } + }, + { + "title": "Provider function result", + "type": "object", + "additionalProperties": false, + "required": ["decorations"], + "properties": { + "decorations": { + "type": "array", + "maxItems": 10000, + "items": { "$ref": "#/$defs/decoration" }, + "description": "Ranges from this provider may touch but must not overlap." + } + } + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/editor/editor-providers.json b/shared/plugins/contract/v1/fixtures/editor/editor-providers.json index 671aaea0..fddd45f6 100644 --- a/shared/plugins/contract/v1/fixtures/editor/editor-providers.json +++ b/shared/plugins/contract/v1/fixtures/editor/editor-providers.json @@ -1,8 +1,8 @@ { "schemaVersion": 1, - "description": "lithe/host/editor/registerProviders validation. `host.providerTypes` is what the host declared in getCapabilities (`services.editor.options.providerTypes`). Registration cases carry the method params without `context`; result cases carry one provider function's LSP 3.17 shaped result and the normalized value the host merges after the language server's own answer. Positions are zero-based LSP positions. A rejected registration names the host failure code; a rejected result is dropped whole.", + "description": "lithe/host/editor/registerProviders validation. `host.providerTypes` is what the host declared in getCapabilities (`services.editor.options.providerTypes`). Registration cases carry method params without `context`; result cases carry provider results and the normalized value the host merges. Positions are zero-based LSP positions. Color decoration results use single-line UTF-16 ranges, and merge cases define deterministic source priority. A rejected registration names the host failure code; a rejected result is dropped whole.", "host": { - "providerTypes": ["definition", "hover", "completion", "codeLens", "foldingRange", "semanticTokens", "documentLink"] + "providerTypes": ["definition", "hover", "completion", "codeLens", "foldingRange", "semanticTokens", "colorDecorations", "documentLink"] }, "registrations": [ { @@ -38,6 +38,16 @@ "params": { "id": "message-keys", "selector": { "fileExtensions": ["properties"] }, "providers": { "signatureHelp": { "function": "keys.signature" } } }, "expected": { "status": "rejected", "code": "plugin.host.unsupportedOption", "details": { "option": "providers.signatureHelp" } } }, + { + "name": "color decorations declare light and dark colors", + "params": { "id": "rainbow", "selector": { "fileExtensions": ["rs"] }, "providers": { "colorDecorations": { "function": "rainbow.decorate", "colorLegend": [{ "id": "depth-0", "light": "#112233", "dark": "#445566" }, { "id": "depth-1", "light": "#AABBCC", "dark": "#DDEEFF" }] } } }, + "expected": { "status": "accepted", "registration": { "id": "rainbow", "selector": { "languages": [], "fileExtensions": ["rs"], "fileNames": [] }, "providers": { "colorDecorations": { "function": "rainbow.decorate", "colorLegend": [{ "id": "depth-0", "light": "#112233", "dark": "#445566" }, { "id": "depth-1", "light": "#AABBCC", "dark": "#DDEEFF" }], "budgetMs": 2000 } } } } + }, + { + "name": "color decoration legend IDs are unique", + "params": { "id": "rainbow", "selector": { "fileExtensions": ["rs"] }, "providers": { "colorDecorations": { "function": "rainbow.decorate", "colorLegend": [{ "id": "depth", "light": "#112233", "dark": "#445566" }, { "id": "depth", "light": "#AABBCC", "dark": "#DDEEFF" }] } } }, + "expected": { "status": "rejected", "code": "plugin.host.invalidParams" } + }, { "name": "diagnostics are not a provider", "params": { "id": "message-keys", "selector": { "fileExtensions": ["properties"] }, "providers": { "diagnostics": { "function": "keys.check" } } }, @@ -116,6 +126,27 @@ "value": { "data": [0, 0, 9, 1, 0] }, "expected": { "status": "rejected" } }, + { + "name": "color decorations return legend IDs and normalized UTF-16 ranges", + "type": "colorDecorations", + "colorLegend": [{ "id": "depth-0", "light": "#112233", "dark": "#445566" }], + "value": { "decorations": [{ "range": { "start": { "line": 2, "character": 1 }, "end": { "line": 2, "character": 4 } }, "colorId": "depth-0" }] }, + "expected": { "status": "accepted", "value": { "decorations": [{ "range": { "start": { "line": 2, "character": 1 }, "end": { "line": 2, "character": 4 } }, "colorId": "depth-0" }] } } + }, + { + "name": "color decorations reject unknown IDs", + "type": "colorDecorations", + "colorLegend": [{ "id": "depth-0", "light": "#112233", "dark": "#445566" }], + "value": { "decorations": [{ "range": { "start": { "line": 0, "character": 1 }, "end": { "line": 0, "character": 4 } }, "colorId": "missing" }] }, + "expected": { "status": "rejected" } + }, + { + "name": "color decoration ranges cannot overlap within one source", + "type": "colorDecorations", + "colorLegend": [{ "id": "depth-0", "light": "#112233", "dark": "#445566" }], + "value": { "decorations": [{ "range": { "start": { "line": 0, "character": 1 }, "end": { "line": 0, "character": 4 } }, "colorId": "depth-0" }, { "range": { "start": { "line": 0, "character": 3 }, "end": { "line": 0, "character": 5 } }, "colorId": "depth-0" }] }, + "expected": { "status": "rejected" } + }, { "name": "a document link needs an absolute target", "type": "documentLink", @@ -128,5 +159,27 @@ "value": [ { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 4 } }, "target": "file:///workspace/messages.properties", "tooltip": "Open bundle" } ], "expected": { "status": "accepted", "value": { "links": [ { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 4 } }, "target": "file:///workspace/messages.properties", "tooltip": "Open bundle" } ] } } } + ], + "merges": [ + { + "name": "earlier source wins and later ranges are clipped", + "value": { "sources": [ + { "sourceId": "plugin-z/registration", "colorLegend": [{ "id": "z", "light": "#112233", "dark": "#445566" }], "value": { "decorations": [{ "range": { "start": { "line": 0, "character": 1 }, "end": { "line": 0, "character": 8 } }, "colorId": "z" }] } }, + { "sourceId": "plugin-a/registration", "colorLegend": [{ "id": "a", "light": "#AABBCC", "dark": "#DDEEFF" }], "value": { "decorations": [{ "range": { "start": { "line": 0, "character": 3 }, "end": { "line": 0, "character": 5 } }, "colorId": "a" }] } } + ] }, + "expected": { "status": "accepted", "decorations": [ + { "sourceId": "plugin-z/registration", "colorId": "z", "light": "#112233", "dark": "#445566", "range": { "start": { "line": 0, "character": 1 }, "end": { "line": 0, "character": 3 } } }, + { "sourceId": "plugin-a/registration", "colorId": "a", "light": "#AABBCC", "dark": "#DDEEFF", "range": { "start": { "line": 0, "character": 3 }, "end": { "line": 0, "character": 5 } } }, + { "sourceId": "plugin-z/registration", "colorId": "z", "light": "#112233", "dark": "#445566", "range": { "start": { "line": 0, "character": 5 }, "end": { "line": 0, "character": 8 } } } + ] } + }, + { + "name": "duplicate source IDs are rejected", + "value": { "sources": [ + { "sourceId": "same", "colorLegend": [{ "id": "x", "light": "#112233", "dark": "#445566" }], "value": { "decorations": [] } }, + { "sourceId": "same", "colorLegend": [{ "id": "x", "light": "#112233", "dark": "#445566" }], "value": { "decorations": [] } } + ] }, + "expected": { "status": "rejected" } + } ] } diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 8cf00e14..4487a3ac 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -49,8 +49,8 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-22 | 输出、日志、进度 | 部分完成 | [插件函数的进度和取消](../contract/v1/README.md#progress);面向开发者的[结构化诊断日志 `litheLogging`](../contract/v1/README.md#structured-plugin-diagnostics);[`languageServer/setStatus`](../contract/v1/README.md#language-server-host-methods) 在宿主状态界面显示插件自己的语言服务器准备状态(只有消息和百分比,没有 actions);[`outputLinkMatchers`](../contract/v1/README.md#output-link-matchers):插件声明的匹配器让 Run 与测试控制台的输出出现链接 | 独立的输出面板、面向用户的日志和进度 API | [插件后端](domains/backend.md) | | API-23 | 工具链与受管进程 | 部分完成 | [进程启动](../contract/v1/README.md#process-start)、运行时解析、[共享可执行文件候选](../contract/v1/README.md#executable-resolution)、工具定义、工具链提供者(`toolchainProviders`);[按工具定义 ID 引用运行时](../contract/v1/README.md#tool-references)(清单 `requiresTools`);后端发起的[`run/start`、`run/stop` 和 `run/didExit` 通知](../contract/v1/README.md#run-and-debug-sessions),由宿主拥有 Run 会话(权限 `run.start`;工具解析不到可执行文件时返回 `plugin.host.toolUnresolved`);[安装缺失的命令](../contract/v1/README.md#command-installers)(`commandInstallers`,权限 `commands.install`;版本 1 增加[下载安装](../contract/v1/README.md#download-installers));[受管运行时](../contract/v1/README.md#managed-runtimes)(`managedRuntimes`,权限 `runtimes.install`,Core 计划与应答校验,无新增宿主 RPC) | 后端可调用的通用工具链和进程服务;保存固定(pin)、`toolchainConsumers`;Lithe 桌面端未声明 `commandInstallers` 1(下载安装) | [工具链](domains/toolchains.md) | | API-24 | 终端 | 部分完成 | [插件自有原生终端](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`、`show`、`close`、`reopen`、`dispose`、`onExit`(本机工作区) | 向终端发送文本、读取终端输出 | [插件后端](domains/backend.md) | -| API-25 | 语言、语法、LSP | 部分完成 | [语言](../contract/v1/README.md#languages)与[语言服务器](../contract/v1/README.md#language-servers);[`languages` 的包内 TextMate 语法和编辑器配置](../contract/v1/README.md#grammars-and-editor-configuration)及[无后缀文件首行关联](../contract/v1/README.md#first-line-matching);[编辑器语言功能 Provider `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers),把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`documentLink` 这 7 种类型绑定到普通插件函数,语言服务器优先、插件结果只补充;插件自有的语言服务器会话:[`languageServers` 的会话声明](../contract/v1/README.md#plugin-owned-sessions)给出后端可用的请求、命令、转发通知,[`languageServer/request`、`notify`、`setStatus`](../contract/v1/README.md#language-server-host-methods) 与 `languageServer/didChangeState`、`languageServer/didReceiveNotification` 两个通知,会话策略由 Core 执行;[`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) 由插件后端决定启动方式 | 符号、格式化、重命名、Code Action、签名帮助、内联提示、运行期传入 JSON 动态注册高亮;远程工作区中由后端决定启动方式的服务器 | [语言](domains/languages.md)、[编辑器](domains/editor.md) | -| API-27 | 编辑器动作、主题、装饰 | 部分完成 | [独立编辑器动作 `editor/registerActions`](../contract/v1/README.md#independent-editor-actions),绑定普通函数和文件范围,不依赖 LSP、构建或运行;支持行首多图标、至多 4 个 `alternatives`、点击结果的 `reveal` | 主题、代码片段、其他装饰 | [编辑器](domains/editor.md) | +| API-25 | 语言、语法、LSP | 部分完成 | [语言](../contract/v1/README.md#languages)与[语言服务器](../contract/v1/README.md#language-servers);[`languages` 的包内 TextMate 语法和编辑器配置](../contract/v1/README.md#grammars-and-editor-configuration)及[无后缀文件首行关联](../contract/v1/README.md#first-line-matching);[编辑器语言功能 Provider `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers),把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`colorDecorations`、`documentLink` 这 8 种类型绑定到普通插件函数;`colorDecorations` 通过颜色 legend 提供可与语义标记叠加的 UTF-16 颜色范围,语言服务器优先、插件结果只补充;插件自有的语言服务器会话:[`languageServers` 的会话声明](../contract/v1/README.md#plugin-owned-sessions)给出后端可用的请求、命令、转发通知,[`languageServer/request`、`notify`、`setStatus`](../contract/v1/README.md#language-server-host-methods) 与 `languageServer/didChangeState`、`languageServer/didReceiveNotification` 两个通知,会话策略由 Core 执行;[`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) 由插件后端决定启动方式 | 符号、格式化、重命名、Code Action、签名帮助、内联提示、运行期传入 JSON 动态注册高亮;远程工作区中由后端决定启动方式的服务器 | [语言](domains/languages.md)、[编辑器](domains/editor.md) | +| API-27 | 编辑器动作、主题、装饰 | 部分完成 | [独立编辑器动作 `editor/registerActions`](../contract/v1/README.md#independent-editor-actions),绑定普通函数和文件范围,不依赖 LSP、构建或运行;支持行首多图标、至多 4 个 `alternatives`、点击结果的 `reveal` | 完整主题控制、代码片段、其他装饰;`editor/registerProviders` 的 `colorDecorations` 可为文本范围提供明暗前景色 | [编辑器](domains/editor.md) | | API-29 | 构建、任务、测试、运行准备 | 部分完成 | [`buildSystems`](../contract/v1/README.md#build-systems)、[`buildProviders`](../contract/v1/README.md#build-providers)、[`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs)、[`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types)、[`beforeLaunchTasks`](../contract/v1/README.md#before-launch-tasks) | 开发指南还不完整;Lithe 桌面端未声明 `buildModelInputs`;`runConfigurationTypes` 自 [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148) 起声明,插件类型只能运行、不能调试;`beforeLaunchTasks` 自 [1lck/Lithe-IDEA#2169](https://github.com/1lck/Lithe-IDEA/pull/2169) 起声明 | [声明式构建](domains/build-systems.md)、[构建提供者](domains/build-providers.md) | | API-30 | 调试适配器 | 部分完成 | [`debugAdapters`](../contract/v1/README.md#debug-adapters) 与宿主的 DAP 会话;[`features`、`defaults`](../contract/v1/README.md#adapter-features-and-defaults)(热代码替换、步进过滤器);后端发起的 [`debug/start`](../contract/v1/README.md#run-and-debug-sessions)(权限 `debug.start`) | 后端只能在本插件自己声明的适配器上启动会话,不能使用其他插件的适配器 | [调试适配器](domains/debug-adapters.md) | | API-31 | VCS 提供者 | 既有能力 | [`vcsProviders`](../contract/v1/README.md#vcs-providers) | 不含内置 Git 的公共读取(见 API-42);Lithe 桌面端未声明 `vcsProviders` | [VCS](domains/vcs.md) | @@ -133,7 +133,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-24 | `terminal/reopen` | 经重新确认,用原启动配置创建新进程,`generation` 加 1,并恢复有界的显示历史 | `terminal.create` | 0 | | API-24 | `terminal/dispose` | 关闭终端,彻底释放句柄、启动配置和历史 | `terminal.create` | 0 | | API-24 | `terminal/onExit` | 订阅终端每个 `generation` 的退出结果 | `terminal.create` | 0 | -| API-25 | `editor/registerProviders` | 注册编辑器语言功能 Provider:把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`documentLink` 绑定到后端的普通函数和文件范围(`selector`),返回 `subscriptionID`;语言服务器优先,插件结果只补充 | `editor.providers`(同时需要 `documents.read`) | 0 | +| API-25 | `editor/registerProviders` | 注册编辑器语言功能 Provider:把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`colorDecorations`、`documentLink` 绑定到后端的普通函数和文件范围(`selector`);颜色范围用单独的明暗色 legend,跨来源按稳定 sourceId 字典序合并,返回 `subscriptionID`;语言服务器优先,插件结果只补充 | `editor.providers`(同时需要 `documents.read`) | 0 | | API-25 | `languageServer/request` | 向本插件自己的语言服务器发 JSON-RPC 请求,受会话策略检查,返回 `{value}` | `languageServer.request` | 0 | | API-25 | `languageServer/notify` | 向本插件自己的语言服务器发通知,返回 `{delivered}` | `languageServer.request` | 0 | | API-27 | `editor/registerActions` | 注册编辑器动作:把后端的普通函数绑定到文件范围(`selector`),返回 `subscriptionID` | `editor.actions`(同时需要 `documents.read`) | 0 | @@ -232,8 +232,8 @@ Status meanings: | API-22 | Output, log, progress | Partial | [Plugin function progress and cancellation](../contract/v1/README.md#progress); developer-facing [structured diagnostics `litheLogging`](../contract/v1/README.md#structured-plugin-diagnostics); [`languageServer/setStatus`](../contract/v1/README.md#language-server-host-methods) shows the plugin's own language server preparation state in the host's status UI (a message and a percentage only, no actions); [`outputLinkMatchers`](../contract/v1/README.md#output-link-matchers): matchers a plugin declares make output in the Run and Test consoles clickable | A dedicated output panel, user-facing log and progress APIs | [Plugin backend](domains/backend.md) | | API-23 | Toolchains and managed processes | Partial | [Process start](../contract/v1/README.md#process-start), runtime resolution, [shared executable candidates](../contract/v1/README.md#executable-resolution), tool definitions, toolchain providers (`toolchainProviders`); [references to runtimes by tool-definition ID](../contract/v1/README.md#tool-references) (manifest `requiresTools`); backend-started [`run/start`, `run/stop`, and the `run/didExit` notification](../contract/v1/README.md#run-and-debug-sessions), where the host owns the Run session (permission `run.start`; a tool that resolves to no executable returns `plugin.host.toolUnresolved`); [installing missing commands](../contract/v1/README.md#command-installers) (`commandInstallers`, permission `commands.install`; version 1 adds [download installers](../contract/v1/README.md#download-installers)); [managed runtimes](../contract/v1/README.md#managed-runtimes) (`managedRuntimes`, permission `runtimes.install`, Core plans and reply validation with no new host RPC) | A general toolchain and process service backends can call; saving pins, `toolchainConsumers`; the Lithe desktop client does not declare `commandInstallers` 1 (download installers) | [Toolchains](domains/toolchains.md) | | API-24 | Terminals | Partial | [Plugin-owned native terminals](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`, `show`, `close`, `reopen`, `dispose`, `onExit` (local workspaces) | Sending text to a terminal, reading its output | [Plugin backend](domains/backend.md) | -| API-25 | Languages, grammars, LSP | Partial | [Languages](../contract/v1/README.md#languages) and [language servers](../contract/v1/README.md#language-servers); [packaged TextMate grammars and editor configuration in `languages`](../contract/v1/README.md#grammars-and-editor-configuration) and [first-line associations for extensionless files](../contract/v1/README.md#first-line-matching); [editor language-feature providers `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers), binding 7 types (`definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, `documentLink`) to ordinary plugin functions, where the language server answers first and plugin results only add; plugin-owned language server sessions: [the session declaration of `languageServers`](../contract/v1/README.md#plugin-owned-sessions) lists the requests, commands, and forwarded notifications a backend may use, with [`languageServer/request`, `notify`, `setStatus`](../contract/v1/README.md#language-server-host-methods) and the `languageServer/didChangeState` and `languageServer/didReceiveNotification` notifications, and Core enforces the session policy; [`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) lets the plugin backend decide how the server starts | Symbols, formatting, rename, code actions, signature help, inlay hints, dynamic registration of highlighting from JSON passed at runtime; servers whose launch the backend decides in remote workspaces | [Languages](domains/languages.md), [Editor](domains/editor.md) | -| API-27 | Editor actions, themes, decorations | Partial | [Independent editor actions `editor/registerActions`](../contract/v1/README.md#independent-editor-actions), binding ordinary functions to file ranges without LSP, build, or run; several icons at a line start, up to 4 `alternatives`, and a `reveal` in the click result | Themes, snippets, other decorations | [Editor](domains/editor.md) | +| API-25 | Languages, grammars, LSP | Partial | [Languages](../contract/v1/README.md#languages) and [language servers](../contract/v1/README.md#language-servers); [packaged TextMate grammars and editor configuration in `languages`](../contract/v1/README.md#grammars-and-editor-configuration) and [first-line associations for extensionless files](../contract/v1/README.md#first-line-matching); [editor language-feature providers `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers), binding 8 types (`definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, `colorDecorations`, `documentLink`) to ordinary plugin functions; color ranges use a separate light/dark legend and merge across sources by stable `sourceId` lexical order; language-server answers take priority for language features, while color ranges layer independently over syntax and semantic tokens; plugin-owned language server sessions: [the session declaration of `languageServers`](../contract/v1/README.md#plugin-owned-sessions) lists the requests, commands, and forwarded notifications a backend may use, with [`languageServer/request`, `notify`, `setStatus`](../contract/v1/README.md#language-server-host-methods) and the `languageServer/didChangeState` and `languageServer/didReceiveNotification` notifications, and Core enforces the session policy; [`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) lets the plugin backend decide how the server starts | Symbols, formatting, rename, code actions, signature help, inlay hints, dynamic registration of syntax highlighting from JSON passed at runtime; servers whose launch the backend decides in remote workspaces | [Languages](domains/languages.md), [Editor](domains/editor.md) | +| API-27 | Editor actions, themes, decorations | Partial | [Independent editor actions `editor/registerActions`](../contract/v1/README.md#independent-editor-actions), binding ordinary functions to file ranges without LSP, build, or run; several icons at a line start, up to 4 `alternatives`, and a `reveal` in the click result | Full theme control, snippets, other decorations; `colorDecorations` on `editor/registerProviders` supplies light/dark foreground colors for text ranges | [Editor](domains/editor.md) | | API-29 | Build, tasks, tests, run preparation | Partial | [`buildSystems`](../contract/v1/README.md#build-systems), [`buildProviders`](../contract/v1/README.md#build-providers), [`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs), [`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types), [`beforeLaunchTasks`](../contract/v1/README.md#before-launch-tasks) | The developer guides are incomplete; the Lithe desktop client does not declare `buildModelInputs`; it declares `runConfigurationTypes` since [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148) and runs plugin types without debugging them, and it declares `beforeLaunchTasks` since [1lck/Lithe-IDEA#2169](https://github.com/1lck/Lithe-IDEA/pull/2169) | [Build systems](domains/build-systems.md), [Build providers](domains/build-providers.md) | | API-30 | Debug adapters | Partial | [`debugAdapters`](../contract/v1/README.md#debug-adapters) and the host's DAP sessions; [`features` and `defaults`](../contract/v1/README.md#adapter-features-and-defaults) (hot code replace, step filters); backend-started [`debug/start`](../contract/v1/README.md#run-and-debug-sessions) (permission `debug.start`) | A backend can start sessions only on adapters its own plugin declares, not on another plugin's adapters | [Debug adapters](domains/debug-adapters.md) | | API-31 | VCS providers | Existing | [`vcsProviders`](../contract/v1/README.md#vcs-providers) | Public reads of built-in Git are not included (see API-42); the Lithe desktop client does not declare `vcsProviders` | [VCS](domains/vcs.md) | @@ -316,7 +316,7 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | API-24 | `terminal/reopen` | After renewed consent, starts a new process with the original launch settings, increments `generation`, and restores bounded display history | `terminal.create` | 0 | | API-24 | `terminal/dispose` | Closes the terminal and releases its handle, launch settings, and history for good | `terminal.create` | 0 | | API-24 | `terminal/onExit` | Subscribes to the exit outcome of each `generation` of a terminal | `terminal.create` | 0 | -| API-25 | `editor/registerProviders` | Registers editor language-feature providers: binds `definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, or `documentLink` to an ordinary backend function and file ranges (`selector`), and returns a `subscriptionID`; the language server answers first and plugin results only add | `editor.providers` (also needs `documents.read`) | 0 | +| API-25 | `editor/registerProviders` | Registers editor language-feature providers: binds `definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, `colorDecorations`, or `documentLink` to an ordinary backend function and file ranges (`selector`), and returns a `subscriptionID`; color ranges use a separate light/dark legend and merge by stable `sourceId` lexical order; the language server answers first for language features, while color ranges layer independently over syntax and semantic tokens | `editor.providers` (also needs `documents.read`) | 0 | | API-25 | `languageServer/request` | Sends a JSON-RPC request to the plugin's own language server, checked against the session policy, and returns `{value}` | `languageServer.request` | 0 | | API-25 | `languageServer/notify` | Sends a notification to the plugin's own language server and returns `{delivered}` | `languageServer.request` | 0 | | API-27 | `editor/registerActions` | Registers editor actions that bind an ordinary backend function to file ranges (`selector`) and returns a `subscriptionID` | `editor.actions` (also needs `documents.read`) | 0 | diff --git a/shared/plugins/reference/domains/editor.md b/shared/plugins/reference/domains/editor.md index b1c7d683..e4693513 100644 --- a/shared/plugins/reference/domains/editor.md +++ b/shared/plugins/reference/domains/editor.md @@ -27,7 +27,7 @@ | `preview/openHTML` | `preview.open` | API-16 | `editorAndPreview` 或 `previewOnly` | | `browser/openExternal` | `browser.open` | API-16 | HTTP(S) 地址或已保存的 HTML | | `editor/registerActions` | `editor.actions` + `documents.read` | API-27 | 先用 `getCapabilities` 发现,再按工作区上下文注册;动作绑定普通函数和文件范围,不依赖 LSP、构建或运行。动作可以带多个图标、最多 4 个 `alternatives` 和点击结果 `reveal`,可用图标由宿主在 `services.editor.options.actionIcons` 中声明 | -| `editor/registerProviders` | `editor.providers` + `documents.read` | API-25 | 先用 `getCapabilities` 发现方法和 `services.editor.options.providerTypes`,再按工作区上下文注册;把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`documentLink` 这 7 种类型绑定到普通函数,不在 `providerTypes` 中的类型返回 `unsupportedOption`;语言服务器的结果优先,插件结果只补充;预算由宿主决定 | +| `editor/registerProviders` | `editor.providers` + `documents.read` | API-25 | 先用 `getCapabilities` 发现方法和 `services.editor.options.providerTypes`,再按工作区上下文注册;把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`colorDecorations`、`documentLink` 这 8 种类型绑定到普通函数;颜色范围通过单独的 `colorLegend` 定义明暗色并可与语义标记叠加;不在 `providerTypes` 中的类型返回 `unsupportedOption`;语言服务器的语言功能结果优先,插件结果只补充;预算由宿主决定 | 所有方法都要带 `context: {contextID, generation}`;除 `documents/registerContentProvider` 外,远程工作区上下文返回 `plugin.host.authorityUnsupported`。`documents/registerContentProvider` 见下一节。 @@ -39,7 +39,7 @@ | 图标 | `icon` 是宿主声明的展示标记,图标只表示一张图,不表示操作:测试图标不会让动作变成测试,宿主也不会因为图标启动任何东西 | | 采集与点击 | 采集只读,不能发网络请求或执行业务;编辑会立即让旧动作失效并取消旧的采集;点击时宿主再次校验文档、上下文、会话和注册。点击要运行或调试代码,应在 `getCapabilities` 列出 `run/start`、`debug/start` 后通过这两个方法发起,让运行出现在宿主的 Run 和 Debug 窗口里,见[调试适配器](debug-adapters.md) | | 动作校验 | 共享的 Core 命令 `plugins.editorActions.decode`,请求带 `version`(必须为 `0`)、`kind`(`registration`、`actions` 或 `invokeResult`)、宿主声明的 `icons` 和 `sourceBytes` | -| Provider 合并 | 语言服务器的结果在先:悬浮段落和补全项跟在语言服务器之后,定义把插件位置加到服务器的位置上,代码镜头、折叠范围和链接直接加入,语义标记只用于语言服务器没有语义标记的文件;合并由 Core 命令 `plugins.editorProviders.decode`(`kind: "mergeDefinitions"`)完成,所以每个宿主合并结果一致 | +| Provider 合并 | 语言服务器的结果在先:悬浮段落和补全项跟在语言服务器之后,定义把插件位置加到服务器的位置上,代码镜头、折叠范围和链接直接加入,语义标记只用于语言服务器没有语义标记的文件;颜色范围不取代语义标记。Core 命令 `plugins.editorProviders.decode` 的 `kind: "mergeColorDecorations"` 按 `/` 的字典序合并颜色来源,较早来源在重叠位置优先,后续范围裁切为未覆盖部分 | | 预算 | 悬浮和补全 400 ms,定义 1500 ms,其余 2000 ms;迟到的或属于旧文档版本的答案被无声丢弃;注册不能自定预算 | | 没有这些方法的宿主 | `getCapabilities` 没有列出 `editor/registerActions` 或 `editor/registerProviders` 时宿主不呈现对应功能,插件仍保留自己的命令和窗口入口;不认识 `editor.actions` 或 `editor.providers` 权限的宿主拒绝安装该包,不会悄悄授予 | @@ -70,7 +70,7 @@ | --- | --- | | [Public document, file and window methods](../../contract/v1/README.md#public-document-file-and-window-methods) | 文档、编辑、打开、预览、浏览器方法的参数、限制和失败码 | | [Independent editor actions](../../contract/v1/README.md#independent-editor-actions) | `editor/registerActions` 的注册、范围、调用和撤回,以及图标、`alternatives` 和点击结果 | -| [Editor language-feature providers](../../contract/v1/README.md#editor-language-feature-providers) | `editor/registerProviders` 的注册、选择器、结果形状、预算和合并规则 | +| [Editor language-feature providers](../../contract/v1/README.md#editor-language-feature-providers) | `editor/registerProviders` 的注册、选择器、结果形状、预算和合并规则,包括 [color decorations schema](../../contract/v1/editor-color-decorations.schema.json) | | [Content providers](../../contract/v1/README.md#content-providers) | `documents/registerContentProvider` 的 scheme 规则、调用、只读文档和撤回 | | [Workspace contexts and capability discovery](../../contract/v1/README.md#workspace-contexts-and-capability-discovery) | `contextID`/`generation` 与 `getCapabilities` | | [Outcomes and error codes](../../contract/v1/README.md#outcomes-and-error-codes) | 结果与错误码 | @@ -82,7 +82,7 @@ | [`editor/editor-actions.plugin.json`](../../contract/v1/fixtures/editor/editor-actions.plugin.json) | `backend` 加 `editor.actions`、`documents.read`:`onWorkspaceOpen` 启动后注册编辑器动作 | | [`editor/editor-actions.json`](../../contract/v1/fixtures/editor/editor-actions.json) | `plugins.editorActions.decode` 的 8 个 Core 用例:宿主声明的图标和源码上限、`alternatives`、点击结果 `reveal`,以及整个结果被拒绝的情形 | | [`editor/editor-providers.plugin.json`](../../contract/v1/fixtures/editor/editor-providers.plugin.json) | `backend` 加 `editor.providers`、`documents.read`:`onWorkspaceOpen` 启动后注册编辑器语言功能 Provider | -| [`editor/editor-providers.json`](../../contract/v1/fixtures/editor/editor-providers.json) | 注册与结果的 Core 用例:6 个注册用例(选择器和类型校验、`unsupportedOption`)和 11 个结果用例(7 种类型的结果形状与被丢弃的结果) | +| [`editor/editor-providers.json`](../../contract/v1/fixtures/editor/editor-providers.json) | Core 注册、结果与合并用例:8 个注册用例、14 个结果用例,以及颜色来源排序、裁切和重复来源 ID 校验 | | [`backend/command-backend.plugin.json`](../../contract/v1/fixtures/backend/command-backend.plugin.json) | 无工具窗口的 `ui` 命令读取文档并编辑 | | [`backend/function-protocol.json`](../../contract/v1/fixtures/backend/function-protocol.json) | `editor/applyEdits`、`editor/registerActions` 的标准请求与回复,以及 `versionConflict`、`readOnly` 等宿主失败码;还有 `documents/registerContentProvider` 的用例:需要 `documents.contentProvider` 授权、聚合名 `documents` 不够、保留 scheme、大写或数字开头的 scheme、非法函数名、缺少 `context` | @@ -117,7 +117,7 @@ Through the plugin-function protocol, a plugin backend reads open documents and | `preview/openHTML` | `preview.open` | API-16 | `editorAndPreview` or `previewOnly` | | `browser/openExternal` | `browser.open` | API-16 | An HTTP(S) URL or saved HTML | | `editor/registerActions` | `editor.actions` + `documents.read` | API-27 | Discover it with `getCapabilities`, then register per workspace context; actions bind ordinary functions and file scopes, independent of LSP, build, or run. An action can carry multiple icons, up to 4 `alternatives`, and a click result `reveal`; the host declares the usable icons in `services.editor.options.actionIcons` | -| `editor/registerProviders` | `editor.providers` + `documents.read` | API-25 | Discover the method and `services.editor.options.providerTypes` with `getCapabilities`, then register per workspace context; binds the 7 types `definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, and `documentLink` to ordinary functions, and a type outside `providerTypes` returns `unsupportedOption`; language-server results come first and plugin results only add to them; the host sets the budgets | +| `editor/registerProviders` | `editor.providers` + `documents.read` | API-25 | Discover the method and `services.editor.options.providerTypes` with `getCapabilities`, then register per workspace context; binds the 8 types `definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, `colorDecorations`, and `documentLink` to ordinary functions; color ranges use a separate `colorLegend` for light and dark appearances and can layer over semantic tokens; a type outside `providerTypes` returns `unsupportedOption`; language-server language-feature results come first and plugin results only add to them; the host sets the budgets | Every method takes `context: {contextID, generation}`; except for `documents/registerContentProvider`, a remote workspace context returns `plugin.host.authorityUnsupported`. `documents/registerContentProvider` is described in the next section. @@ -129,7 +129,7 @@ Every method takes `context: {contextID, generation}`; except for `documents/reg | Icons | `icon` is a presentation token the host declares; an icon names a picture, not an operation: a test icon does not make the action a test, and the host never starts anything because of an icon | | Collection and click | Collection is read-only, with no network request or business execution; an edit invalidates the old actions immediately and cancels older collection; a click makes the host validate document, context, session, and registration again. A click that runs or debugs code should use `run/start` and `debug/start` once `getCapabilities` lists them, so the run appears in the host's Run and Debug windows; see [Debug adapters](debug-adapters.md) | | Action validation | The shared Core command `plugins.editorActions.decode`; its request carries `version` (must be `0`), `kind` (`registration`, `actions`, or `invokeResult`), and the host-declared `icons` and `sourceBytes` | -| Provider merging | Language-server results come first: hover sections and completion items follow the server's, definitions add plugin locations to the server's, code lenses, folding ranges, and links are added, and semantic tokens apply only to files whose language server has none; the merge is the Core command `plugins.editorProviders.decode` with `kind: "mergeDefinitions"`, so every host merges alike | +| Provider merging | Language-server results come first: hover sections and completion items follow the server's, definitions add plugin locations to the server's, code lenses, folding ranges, and links are added, and semantic tokens apply only to files whose language server has none; color ranges do not replace semantic tokens. The Core command `plugins.editorProviders.decode` with `kind: "mergeColorDecorations"` merges colors by `/` in lexical order; the earlier source wins at overlapping positions and later ranges are clipped to uncovered portions | | Budgets | Hover and completion 400 ms, definition 1500 ms, the rest 2000 ms; a late answer, or one for an older document version, is dropped without an error; a registration cannot set its own budget | | A host without these methods | A host whose `getCapabilities` does not list `editor/registerActions` or `editor/registerProviders` presents no such feature, and the plugin keeps its own command and window entry points; a host that does not recognize the `editor.actions` or `editor.providers` permission refuses the package instead of granting it silently | @@ -160,7 +160,7 @@ A language server may hand out documents that have no file (such as the decompil | --- | --- | | [Public document, file and window methods](../../contract/v1/README.md#public-document-file-and-window-methods) | Parameters, limits, and failure codes for document, edit, open, preview, and browser methods | | [Independent editor actions](../../contract/v1/README.md#independent-editor-actions) | Registering, scoping, invoking, and withdrawing `editor/registerActions`, plus icons, `alternatives`, and click results | -| [Editor language-feature providers](../../contract/v1/README.md#editor-language-feature-providers) | Registering `editor/registerProviders`, selectors, result shapes, budgets, and merge rules | +| [Editor language-feature providers](../../contract/v1/README.md#editor-language-feature-providers) | Registering `editor/registerProviders`, selectors, result shapes, budgets, and merge rules, including the [color decorations schema](../../contract/v1/editor-color-decorations.schema.json) | | [Content providers](../../contract/v1/README.md#content-providers) | Scheme rules, invoking, read-only documents, and withdrawing for `documents/registerContentProvider` | | [Workspace contexts and capability discovery](../../contract/v1/README.md#workspace-contexts-and-capability-discovery) | `contextID`/`generation` and `getCapabilities` | | [Outcomes and error codes](../../contract/v1/README.md#outcomes-and-error-codes) | Outcomes and error codes | @@ -172,7 +172,7 @@ A language server may hand out documents that have no file (such as the decompil | [`editor/editor-actions.plugin.json`](../../contract/v1/fixtures/editor/editor-actions.plugin.json) | `backend` with `editor.actions` and `documents.read`: registers editor actions after `onWorkspaceOpen` | | [`editor/editor-actions.json`](../../contract/v1/fixtures/editor/editor-actions.json) | 8 Core cases for `plugins.editorActions.decode`: the host-declared icons and source limit, `alternatives`, click-result `reveal`, and results refused whole | | [`editor/editor-providers.plugin.json`](../../contract/v1/fixtures/editor/editor-providers.plugin.json) | `backend` with `editor.providers` and `documents.read`: registers editor language-feature providers after `onWorkspaceOpen` | -| [`editor/editor-providers.json`](../../contract/v1/fixtures/editor/editor-providers.json) | Core cases for registrations and results: 6 registration cases (selector and type validation, `unsupportedOption`) and 11 result cases (result shapes for the 7 types, and dropped results) | +| [`editor/editor-providers.json`](../../contract/v1/fixtures/editor/editor-providers.json) | Core cases for registrations, results, and merges, including color legend and range validation and stable source priority | | [`backend/command-backend.plugin.json`](../../contract/v1/fixtures/backend/command-backend.plugin.json) | A `ui` command without a tool window that reads and edits documents | | [`backend/function-protocol.json`](../../contract/v1/fixtures/backend/function-protocol.json) | Canonical requests and replies for `editor/applyEdits` and `editor/registerActions`, plus host failure codes such as `versionConflict` and `readOnly`; also the `documents/registerContentProvider` cases: it needs the `documents.contentProvider` grant, the aggregate `documents` name is not enough, reserved schemes, an uppercase or digit-first scheme, a malformed function name, and a missing `context` | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index a477a50e..ab625b3f 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,7 @@ ## 待合入 +- 当前工作分支(PR 待创建),`pluginAPIVersion` 0 内补充(API-25):`editor/registerProviders` 新增 `colorDecorations`,注册普通后端函数和最多 64 个有稳定 ID 的明暗 `#RRGGBB` 颜色;结果为 UTF-16 单行范围与颜色 ID。Core 拒绝单源重叠、空范围、未知颜色 ID 和超限结果,并用 `plugins.editorProviders.decode` 的 `kind: "mergeColorDecorations"` 按 `/` 字典序合并,较早来源优先且裁切后续范围。没有新增宿主方法、通知、能力版本或 SDK 包装;待创建 PR 后补 PR 作者、编号与合入日期。 - [#182](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/182)(关联 [1lck/Lithe-IDEA#2260](https://github.com/1lck/Lithe-IDEA/issues/2260)),`lithe-support[bot]`,**`toolchainProviders` 1 / `litheToolchains` 1**(API-23):权限和 authority 错误改用 `-32082`、`-32083`,稳定字符串码不变。Core 按重新校验的清单版本解码;版本 0 保留 `-32070`、`-32071`,不同版本的号码互不接受。Rust SDK 保留版本 0 默认语义,通过 `Backend::toolchain_provider_version(ToolchainProviderVersion::V1)` 显式选择新版本;没有匹配的协商版本就不启用提供者。四个 SDK 的 `plugin.function.*` 号码不变。 - [#184](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/184),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):`workspace/create` 的 `kind` 新增 `symlink`,配合新字段 `linkTarget`(1–4096 字节,不含 NUL)新建符号链接。链接原样保存目标,可以是绝对路径,也可以相对链接所在目录,可以指向根目录外或不存在的路径;新建链接不放宽任何检查,`workspace/readFile`、列表和 `editor/open` 仍做根目录检查,也不能穿过离开根目录的父目录新建任何东西;Windows 上目标里的 `/` 存成 `\`,目标是已存在的目录就建目录链接,否则建文件链接,系统拒绝建链接时返回 `failed`。API-11 七个方法的参数改为在路由前严格检查:`resource`、`target` 只能是 `{rootID,path}`,路径只有一种写法(`/` 分隔,没有空段、`.`、`..`,最长 4096 字节,Windows 上不能原样保存的名字也拒绝),移动的目标在同一根目录且不在源之内,`create` 的字段必须和 `kind` 一致,否则返回 `invalidParams`。fixture `backend/function-protocol.json` 新增 3 个用例,四个官方 SDK 的 `create` 注释写明 `symlink`,Node 类型按 `kind` 分成三种参数形状。Rust Core 新增内核命令 `workspace.createEntry`、`renameEntry`、`copyEntry`、`resolveEntry` 和错误码 `entry_not_found`、`entry_exists`,路径解析、不覆盖的重命名、符号链接和复制都在 Core 里完成,宿主只负责文档、视图和系统废纸篓。桌面端接入见 [1lck/Lithe-IDEA#2358](https://github.com/1lck/Lithe-IDEA/pull/2358)。没有新增能力版本、宿主方法、通知或 SDK 版本。 - [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):新增宿主方法 `documents/save`、`documents/saveAs`、`documents/close`(新权限 `documents.save`)和 `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash`(新权限 `workspace.files.write`)。每个权限只授予自己的方法,原有权限(包括聚合的 `workspace` 授权和 `documents.read`)都不授予它们。宿主经文档所有者保存,保留版本、撤销记录和语言会话;`close` 先保存再关闭,从不丢弃修改;`saveAs`、`create`、`rename`、`copy` 的目标已存在时失败,从不覆盖;`trash` 只移到系统废纸篓,没有永久删除;`rename`、`trash` 先保存其下打开的文档,保存失败就不动。这些方法不弹询问:需要用户选择的情形(未命名文档、硬链接文件、文件在磁盘上已改变)直接拒绝。新增失败码 `plugin.host.alreadyExists`(`-32080`,目标已存在)和 `plugin.host.diskChanged`(`-32081`,文件在磁盘上被改动或删除,没有写入)。清单 schema 的权限枚举加上两个新权限,fixture `backend/function-protocol.json` 新增 4 个宿主请求用例和 2 个失败码用例,`rust/fixtures/plugins/host-api-v1.json` 新增 4 个授权用例。四个官方 SDK 新增 7 个方法的封装和两个失败码。桌面端实现见 [1lck/Lithe-IDEA#2358](https://github.com/1lck/Lithe-IDEA/pull/2358)。没有新增能力版本、通知或 SDK 版本。 diff --git a/shared/plugins/sdk/e2e/plugin_sdk/backend.rs b/shared/plugins/sdk/e2e/plugin_sdk/backend.rs index 3787b6d8..f5ebeb06 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/backend.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/backend.rs @@ -61,6 +61,7 @@ pub fn run_backend_scenario(package: &Path) { [ "fail.unexpectedly", "files.nextChange", + "fixture.colors", "note.read", "note.save", "secret.check", diff --git a/shared/plugins/sdk/e2e/plugin_sdk/colors.rs b/shared/plugins/sdk/e2e/plugin_sdk/colors.rs new file mode 100644 index 00000000..1c84f3fe --- /dev/null +++ b/shared/plugins/sdk/e2e/plugin_sdk/colors.rs @@ -0,0 +1,117 @@ +//! Color decoration registration and results through each SDK's generic host API. + +use super::{core, Fixture, Session, WAIT}; +use serde_json::{json, Value}; +use std::fs; + +/// Starts a sample with only the editor provider grant, forwards its generic +/// registration through Core, and decodes a versioned color decoration answer. +pub fn run(label: &str, executable: &str, prefix: &[String]) { + let fixture = Fixture::new(&format!("colors-{label}")); + let workspace = fixture.workspace(); + let state = fixture.root.join("state"); + fs::create_dir_all(&workspace).expect("fixture workspace"); + fs::create_dir_all(&state).expect("fixture state"); + let uri = core( + "lsp.documentUri", + json!({"path": workspace, "platform":"auto"}), + ); + let state_uri = lithe_document_uri::DocumentPathPlatform::Auto + .document_uri(&state.to_string_lossy()) + .expect("state URI"); + let state_argument = lithe_document_uri::file_path_from_uri(&state_uri); + let mut arguments: Vec = prefix.iter().map(|argument| json!(argument)).collect(); + arguments.extend([json!("--state"), json!(state_argument)]); + let plugin_id = format!("dev.lithe.test.colors.{label}"); + let started = core( + "lsp.startServer", + json!({ + "providerId":format!("pluginBackend:{plugin_id}"), "pluginId":plugin_id, + "executablePath":executable, "arguments":arguments, + "rootUri":uri["uri"], "workingDirectory":workspace, + "hostServices":["lithe/host/editor/registerProviders"], + "hostOptions":{"editor":{"actionIcons":["run"],"actionSourceBytes":131072, + "providerTypes":["colorDecorations"]}}, + "initializeTimeoutMilliseconds":WAIT.as_millis() as u64, + "requestTimeoutMilliseconds":WAIT.as_millis() as u64, + "shutdownTimeoutMilliseconds":5000 + }), + ); + let mut session = Session { + id: started["sessionId"].as_str().expect("session ID").into(), + plugin_id: plugin_id.clone(), + events: Vec::new(), + }; + let state = session.await_event("color fixture initialization", |event| { + event["type"] == "stateChanged" + && matches!(event["state"].as_str(), Some("ready" | "failed")) + }); + assert_eq!( + state["state"], "ready", + "color fixture failed: {:#?}", + session.events + ); + let colors = json!([{"id":"accent-1","light":"#8B2050","dark":"#EE8CAA"}]); + let registration = json!({"context":{"contextID":"colors","generation":1}, + "id":"color-fixture","selector":{"fileExtensions":["txt"]}, + "providers":{"colorDecorations":{"function":"fixture.colors","colorLegend":colors}}}); + session.invoke( + "colors-register", + "fixture.colors", + json!({"registration":registration}), + ); + let request = session.await_event("color registration host request", |event| { + event["type"] == "hostRequest" && event["method"] == "lithe/host/editor/registerProviders" + }); + let mut params = request["result"]["params"].clone(); + assert_eq!(params, registration); + params + .as_object_mut() + .expect("registration") + .remove("context"); + let normalized = core( + "plugins.editorProviders.decode", + json!({ + "kind":"registration","types":["colorDecorations"],"value":params}), + ); + assert_eq!( + normalized["registration"]["providers"]["colorDecorations"]["budgetMs"], + 2000 + ); + core( + "lsp.hostResponse", + json!({"sessionId":session.id, + "hostRequestID":request["result"]["hostRequestID"],"result":{"subscriptionID":"colors-1"}}), + ); + assert_eq!( + session.completion("colors-register")["result"]["value"], + json!({"subscriptionID":"colors-1"}) + ); + + let value = json!({"decorations":[{"range":{"start":{"line":0,"character":2}, + "end":{"line":0,"character":4}},"colorId":"accent-1"}]}); + let answer = session.call( + "colors-result", + "fixture.colors", + json!({ + "document":{"documentID":"doc-1","version":3},"value":value}), + ); + let result = core( + "plugins.editorProviders.decode", + json!({"kind":"result", + "type":"colorDecorations","colorLegend":colors,"value":answer["result"]["value"]}), + ); + assert_eq!(result["result"], value); + let merged = core( + "plugins.editorProviders.decode", + json!({"kind":"mergeColorDecorations", + "value":{"sources":[{"sourceId":format!("{plugin_id}/color-fixture"), + "colorLegend":colors,"value":result["result"]}]}}), + ); + assert_eq!(merged["decorations"][0]["dark"], "#EE8CAA"); + assert_eq!( + merged["decorations"][0]["range"], + value["decorations"][0]["range"] + ); + session.stop(); +} diff --git a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs index ce5e867e..4947af93 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs @@ -20,6 +20,7 @@ #![allow(dead_code)] pub mod backend; +pub mod colors; pub mod keymap; pub mod native_build; pub mod toolchains; @@ -456,7 +457,10 @@ pub fn run_sample_scenario(sample: &Sample) { } let mut session = Session::start(&plugin_id, runtime, &arguments, &workspace); - assert_eq!(session.functions(), ["snapshot.read", "workspace.build"]); + assert_eq!( + session.functions(), + ["fixture.colors", "snapshot.read", "workspace.build"] + ); // Typed build requests: Core plans them and decodes the answers. The fixture workspace is // the test's own, so it is trusted: a plan that runs the workspace's code needs that. diff --git a/shared/plugins/sdk/e2e/plugin_sdk_go.rs b/shared/plugins/sdk/e2e/plugin_sdk_go.rs index 5980050c..6428c2d5 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk_go.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk_go.rs @@ -9,6 +9,14 @@ mod plugin_sdk; +#[test] +fn the_go_sdk_registers_and_answers_color_decorations() { + let Some(executable) = std::env::var_os("LITHE_PLUGIN_SDK_GO_SAMPLE") else { + return; + }; + plugin_sdk::colors::run("go", &executable.to_string_lossy(), &[]); +} + #[test] fn the_go_sdk_import_provider_reads_a_selected_source_through_core() { let Some(executable) = std::env::var_os("LITHE_PLUGIN_SDK_GO_SAMPLE") else { diff --git a/shared/plugins/sdk/e2e/plugin_sdk_java.rs b/shared/plugins/sdk/e2e/plugin_sdk_java.rs index 7b70f7f1..4217fb94 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk_java.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk_java.rs @@ -10,6 +10,21 @@ mod plugin_sdk; +#[test] +fn the_java_sdk_registers_and_answers_color_decorations() { + let (Some(java), Some(jar)) = ( + std::env::var_os("LITHE_PLUGIN_SDK_JAVA"), + std::env::var_os("LITHE_PLUGIN_SDK_JAVA_SAMPLE"), + ) else { + return; + }; + plugin_sdk::colors::run( + "java", + &java.to_string_lossy(), + &["-jar".into(), jar.to_string_lossy().into_owned()], + ); +} + #[test] fn the_java_sdk_import_provider_reads_a_selected_source_through_core() { let (Some(java), Some(jar)) = ( diff --git a/shared/plugins/sdk/e2e/plugin_sdk_node.rs b/shared/plugins/sdk/e2e/plugin_sdk_node.rs index e8de26ed..e1b14ff3 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk_node.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk_node.rs @@ -6,6 +6,21 @@ mod plugin_sdk; +#[test] +fn the_node_sdk_registers_and_answers_color_decorations() { + let Some(node) = plugin_sdk::node_from_environment("Node color providers") else { + return; + }; + let script = plugin_sdk::repository_path("sdk/node/examples/sample-build/backend/main.mjs"); + // Node's command-line resolver cannot use Windows extended-length paths. + // The existing URI adapter gives it the equivalent ordinary native path. + let uri = lithe_document_uri::DocumentPathPlatform::Auto + .document_uri(&script.to_string_lossy()) + .expect("sample URI"); + let script = lithe_document_uri::file_path_from_uri(&uri); + plugin_sdk::colors::run("node", &node, &[script]); +} + #[test] fn the_node_sdk_import_provider_reads_a_selected_source_through_core() { let Some(node) = plugin_sdk::node_from_environment("the Node keymap provider") else { diff --git a/shared/plugins/sdk/e2e/plugin_sdk_rust.rs b/shared/plugins/sdk/e2e/plugin_sdk_rust.rs index 9ee24015..3e73bfea 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk_rust.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk_rust.rs @@ -8,6 +8,14 @@ mod plugin_sdk; +#[test] +fn the_rust_sdk_registers_and_answers_color_decorations() { + let Some(executable) = std::env::var_os("LITHE_PLUGIN_SDK_RUST_SAMPLE") else { + return; + }; + plugin_sdk::colors::run("rust", &executable.to_string_lossy(), &[]); +} + #[test] fn the_rust_sdk_toolchain_provider_negotiates_and_answers_through_core() { let Some(executable) = std::env::var_os("LITHE_PLUGIN_SDK_RUST_SAMPLE") else { diff --git a/shared/plugins/sdk/go/examples/sample-backend/main.go b/shared/plugins/sdk/go/examples/sample-backend/main.go index 938e9c31..59c73089 100644 --- a/shared/plugins/sdk/go/examples/sample-backend/main.go +++ b/shared/plugins/sdk/go/examples/sample-backend/main.go @@ -47,6 +47,18 @@ func main() { } backend := lithe.NewBackend("sample-backend").Version(version) + // A generic request supports new provider options without an SDK wrapper. + must(backend.Function("fixture.colors", func(params json.RawMessage, call *lithe.Context) (any, error) { + var value map[string]json.RawMessage + if err := json.Unmarshal(params, &value); err != nil { + return nil, err + } + if registration, ok := value["registration"]; ok { + return call.Host().Request("lithe/host/editor/registerProviders", registration) + } + return value["value"], nil + })) + // Exercised only when the Core end-to-end harness offers this provider. must(backend.KeymapImportProvider("fixture", func(request lithe.KeymapImportRequest, call *lithe.Context) (any, error) { files, err := request.ListInputs(call.Host()) diff --git a/shared/plugins/sdk/java/examples/sample-build/src/main/java/org/example/samplebuild/SampleBuild.java b/shared/plugins/sdk/java/examples/sample-build/src/main/java/org/example/samplebuild/SampleBuild.java index f29e44db..31836ac9 100644 --- a/shared/plugins/sdk/java/examples/sample-build/src/main/java/org/example/samplebuild/SampleBuild.java +++ b/shared/plugins/sdk/java/examples/sample-build/src/main/java/org/example/samplebuild/SampleBuild.java @@ -106,6 +106,10 @@ private void serve() { backend.function("workspace.build", this::build); backend.function("snapshot.read", (params, context) -> store.read("snapshot", null)); + // A generic request supports new provider options without an SDK wrapper. + backend.function("fixture.colors", (params, context) -> params.containsKey("registration") + ? context.host().request("lithe/host/editor/registerProviders", params.get("registration")).join() + : params.get("value")); backend.listen(); } diff --git a/shared/plugins/sdk/node/examples/sample-build/backend/main.mjs b/shared/plugins/sdk/node/examples/sample-build/backend/main.mjs index fa813ed7..0c2e1fe9 100644 --- a/shared/plugins/sdk/node/examples/sample-build/backend/main.mjs +++ b/shared/plugins/sdk/node/examples/sample-build/backend/main.mjs @@ -24,6 +24,10 @@ import { fileURLToPath } from 'node:url'; import { createBackend, openStateStore, PluginError } from '../../../src/index.mjs'; const backend = createBackend({ name: 'sample-build', version: '0.1.0' }); +// A generic request supports new provider options without an SDK wrapper. +backend.function('fixture.colors', (params, context) => params.registration + ? context.host.request('lithe/host/editor/registerProviders', params.registration) + : params.value); // Exercised only when the Core end-to-end harness offers this provider. backend.keymapImportProvider('fixture', async (snapshot) => { const files = await snapshot.listInputs(); diff --git a/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs b/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs index 0d19b199..8b8af026 100644 --- a/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs +++ b/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs @@ -63,6 +63,18 @@ fn main() { }) .expect("valid toolchain fixture provider"); + // A generic request supports new provider options without an SDK wrapper. + backend + .function("fixture.colors", |params, context| { + if let Some(registration) = params.get("registration") { + return Ok(context + .host() + .request("lithe/host/editor/registerProviders", registration.clone())?); + } + Ok(params["value"].clone()) + }) + .expect("valid color fixture function"); + let notes = Arc::clone(&state); backend .function("note.save", move |params, context| { From 21b60f650cb8bc5905e65ea514ab4a58505a8656 Mon Sep 17 00:00:00 2001 From: mirakyux Date: Mon, 23 Nov 2026 22:36:25 +0800 Subject: [PATCH 2/2] docs(plugin-api): link color decorations pull request --- shared/plugins/reference/protocol-changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index ab625b3f..0ff9a73f 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- 当前工作分支(PR 待创建),`pluginAPIVersion` 0 内补充(API-25):`editor/registerProviders` 新增 `colorDecorations`,注册普通后端函数和最多 64 个有稳定 ID 的明暗 `#RRGGBB` 颜色;结果为 UTF-16 单行范围与颜色 ID。Core 拒绝单源重叠、空范围、未知颜色 ID 和超限结果,并用 `plugins.editorProviders.decode` 的 `kind: "mergeColorDecorations"` 按 `/` 字典序合并,较早来源优先且裁切后续范围。没有新增宿主方法、通知、能力版本或 SDK 包装;待创建 PR 后补 PR 作者、编号与合入日期。 +- [#188](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/188),[@mirakyux](https://github.com/mirakyux),`pluginAPIVersion` 0 内补充(API-25):`editor/registerProviders` 新增 `colorDecorations`,注册普通后端函数和最多 64 个有稳定 ID 的明暗 `#RRGGBB` 颜色;结果为 UTF-16 单行范围与颜色 ID。Core 拒绝单源重叠、空范围、未知颜色 ID 和超限结果,并用 `plugins.editorProviders.decode` 的 `kind: "mergeColorDecorations"` 按 `/` 字典序合并,较早来源优先且裁切后续范围。没有新增宿主方法、通知、能力版本或 SDK 包装。 - [#182](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/182)(关联 [1lck/Lithe-IDEA#2260](https://github.com/1lck/Lithe-IDEA/issues/2260)),`lithe-support[bot]`,**`toolchainProviders` 1 / `litheToolchains` 1**(API-23):权限和 authority 错误改用 `-32082`、`-32083`,稳定字符串码不变。Core 按重新校验的清单版本解码;版本 0 保留 `-32070`、`-32071`,不同版本的号码互不接受。Rust SDK 保留版本 0 默认语义,通过 `Backend::toolchain_provider_version(ToolchainProviderVersion::V1)` 显式选择新版本;没有匹配的协商版本就不启用提供者。四个 SDK 的 `plugin.function.*` 号码不变。 - [#184](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/184),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):`workspace/create` 的 `kind` 新增 `symlink`,配合新字段 `linkTarget`(1–4096 字节,不含 NUL)新建符号链接。链接原样保存目标,可以是绝对路径,也可以相对链接所在目录,可以指向根目录外或不存在的路径;新建链接不放宽任何检查,`workspace/readFile`、列表和 `editor/open` 仍做根目录检查,也不能穿过离开根目录的父目录新建任何东西;Windows 上目标里的 `/` 存成 `\`,目标是已存在的目录就建目录链接,否则建文件链接,系统拒绝建链接时返回 `failed`。API-11 七个方法的参数改为在路由前严格检查:`resource`、`target` 只能是 `{rootID,path}`,路径只有一种写法(`/` 分隔,没有空段、`.`、`..`,最长 4096 字节,Windows 上不能原样保存的名字也拒绝),移动的目标在同一根目录且不在源之内,`create` 的字段必须和 `kind` 一致,否则返回 `invalidParams`。fixture `backend/function-protocol.json` 新增 3 个用例,四个官方 SDK 的 `create` 注释写明 `symlink`,Node 类型按 `kind` 分成三种参数形状。Rust Core 新增内核命令 `workspace.createEntry`、`renameEntry`、`copyEntry`、`resolveEntry` 和错误码 `entry_not_found`、`entry_exists`,路径解析、不覆盖的重命名、符号链接和复制都在 Core 里完成,宿主只负责文档、视图和系统废纸篓。桌面端接入见 [1lck/Lithe-IDEA#2358](https://github.com/1lck/Lithe-IDEA/pull/2358)。没有新增能力版本、宿主方法、通知或 SDK 版本。 - [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):新增宿主方法 `documents/save`、`documents/saveAs`、`documents/close`(新权限 `documents.save`)和 `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash`(新权限 `workspace.files.write`)。每个权限只授予自己的方法,原有权限(包括聚合的 `workspace` 授权和 `documents.read`)都不授予它们。宿主经文档所有者保存,保留版本、撤销记录和语言会话;`close` 先保存再关闭,从不丢弃修改;`saveAs`、`create`、`rename`、`copy` 的目标已存在时失败,从不覆盖;`trash` 只移到系统废纸篓,没有永久删除;`rename`、`trash` 先保存其下打开的文档,保存失败就不动。这些方法不弹询问:需要用户选择的情形(未命名文档、硬链接文件、文件在磁盘上已改变)直接拒绝。新增失败码 `plugin.host.alreadyExists`(`-32080`,目标已存在)和 `plugin.host.diskChanged`(`-32081`,文件在磁盘上被改动或删除,没有写入)。清单 schema 的权限枚举加上两个新权限,fixture `backend/function-protocol.json` 新增 4 个宿主请求用例和 2 个失败码用例,`rust/fixtures/plugins/host-api-v1.json` 新增 4 个授权用例。四个官方 SDK 新增 7 个方法的封装和两个失败码。桌面端实现见 [1lck/Lithe-IDEA#2358](https://github.com/1lck/Lithe-IDEA/pull/2358)。没有新增能力版本、通知或 SDK 版本。