From 591766d15999c5d04832071180000d2192ceb363 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 24 Nov 2026 05:16:59 +0800 Subject: [PATCH 1/2] feat(plugin-api): add bounded workflow host APIs and SDKs --- rust/Cargo.lock | 1 + rust/contracts/rust-core-api.md | 15 + rust/crates/core/src/protocol/command.rs | 3 + .../core/src/runtime/dispatcher/plugins.rs | 3 + rust/crates/core/src/runtime/request_trace.rs | 1 + rust/crates/plugin-rpc/Cargo.toml | 1 + rust/crates/plugin-rpc/src/host_params.rs | 3 +- rust/crates/plugin-rpc/src/host_requests.rs | 126 +++- rust/crates/plugin-rpc/src/lib.rs | 10 + rust/crates/plugin-rpc/src/workflow.rs | 618 ++++++++++++++++++ rust/crates/plugin-ui/src/tree.rs | 14 +- rust/crates/project/src/html_preview.rs | 47 ++ rust/crates/project/src/markdown_reference.rs | 23 + rust/fixtures/plugins/host-api-v1.json | 19 + rust/fixtures/plugins/workflow-v1.json | 34 + shared/plugins/contract/v1/README.md | 128 +++- .../fixtures/backend/function-protocol.json | 19 + .../contract/v1/fixtures/ui/view-results.json | 27 + .../contract/v1/plugin-manifest.schema.json | 2 +- .../plugins/contract/v1/plugin-ui.schema.json | 4 +- shared/plugins/guides/plugin-workflows.md | 57 ++ shared/plugins/reference/api-catalog.md | 72 +- .../plugins/reference/protocol-changelog.md | 35 +- shared/plugins/sdk/go/README.md | 2 + shared/plugins/sdk/go/lithe/host.go | 158 ++++- shared/plugins/sdk/go/lithe/protocol.go | 141 ++-- shared/plugins/sdk/go/lithe/view.go | 11 +- shared/plugins/sdk/java/README.md | 2 + .../io/github/litheidea/plugin/sdk/Host.java | 76 ++- .../github/litheidea/plugin/sdk/Protocol.java | 19 + .../litheidea/plugin/sdk/ViewEvent.java | 10 +- shared/plugins/sdk/node/README.md | 2 + shared/plugins/sdk/node/src/host.mjs | 39 ++ shared/plugins/sdk/node/src/index.d.ts | 49 +- shared/plugins/sdk/node/src/protocol.mjs | 20 + shared/plugins/sdk/rust/README.md | 2 + .../plugins/sdk/rust/plugin-sdk/src/host.rs | 191 +++++- shared/plugins/sdk/rust/plugin-sdk/src/lib.rs | 5 +- .../sdk/rust/plugin-sdk/src/protocol.rs | 19 + .../plugins/sdk/rust/plugin-sdk/src/view.rs | 12 + 40 files changed, 1911 insertions(+), 109 deletions(-) create mode 100644 rust/crates/plugin-rpc/src/workflow.rs create mode 100644 rust/fixtures/plugins/workflow-v1.json create mode 100644 shared/plugins/guides/plugin-workflows.md diff --git a/rust/Cargo.lock b/rust/Cargo.lock index e0516d03..dd0737b2 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1424,6 +1424,7 @@ dependencies = [ "lithe-protocol", "serde", "serde_json", + "url", ] [[package]] diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 940ef8fc..4df21a34 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -8810,3 +8810,18 @@ editor and may explicitly set selected default handlers. macOS associates conten types, so extensions sharing a type may change together. The installed package stays read-only. No regex or all-files catch-all registration is permitted. See [fixtures](../fixtures/application/file-associations-v1.json). + +## Plugin workflow projections (`plugins.workflow`) + +`operation:"prepare"` takes `{method,params}` and returns strictly checked params +and `{textBytes,outputLines,outputBytes,resources}` limits. Network defaults are +resolved here. `quickPick` takes `{items,query}` and returns source `indices`; +`input` takes `{pick,value}` and returns `{valid}`. `status` takes bounded +`items:[{id,priority}]` and returns ordered `ids`. `treePage` takes `{cursor, +lastCursor,count,lastCount,rows,lastVisible}` and returns `{load}` only near the +end when both cursor and retained count advance. `output` takes `{open,text}` +and returns `{lines,open,maxLines,maxBytes}` as one bounded increment, never the +retained history. Unknown operations/fields and malformed projection input fail +with `invalid_request`. This hot path is excluded from request tracing; its text +may contain secrets. Public backend methods and lifecycle are specified in the +[plugin contract](../../shared/plugins/contract/v1/README.md#workflow-host-methods). diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 38ebc2be..c7f09d95 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -217,6 +217,8 @@ pub enum AiCommand { #[derive(Debug, Clone)] /// The `plugins.*` commands; their names live in [`CoreCommand::parse`]. pub enum PluginsCommand { + /// Plans bounded plugin interactions and projects their native input/output. + Workflow, /// Validates and normalizes a declarative plugin manifest (`plugins.declarative.validate`). DeclarativeValidate, /// Checks what a backend returned for a plugin view and gives the whole view to draw (`plugins.ui.applyResult`). @@ -1167,6 +1169,7 @@ impl CoreCommand { "plugins.declarative.validate" => { Some(Self::Plugins(PluginsCommand::DeclarativeValidate)) } + "plugins.workflow" => Some(Self::Plugins(PluginsCommand::Workflow)), "plugins.ui.applyResult" => Some(Self::Plugins(PluginsCommand::UIApplyResult)), "plugins.web.open" => Some(Self::Plugins(PluginsCommand::WebOpen)), "plugins.web.close" => Some(Self::Plugins(PluginsCommand::WebClose)), diff --git a/rust/crates/core/src/runtime/dispatcher/plugins.rs b/rust/crates/core/src/runtime/dispatcher/plugins.rs index 3f262182..3777eb0f 100644 --- a/rust/crates/core/src/runtime/dispatcher/plugins.rs +++ b/rust/crates/core/src/runtime/dispatcher/plugins.rs @@ -12,6 +12,9 @@ pub(super) fn dispatch( payload: Value, ) -> CoreResponse { match command { + PluginsCommand::Workflow => { + plugin_response(id, payload, lithe_plugin_rpc::workflow::command) + } PluginsCommand::UIApplyResult => { plugin_response(id, payload, lithe_plugin_manifest::apply_result_command) } diff --git a/rust/crates/core/src/runtime/request_trace.rs b/rust/crates/core/src/runtime/request_trace.rs index 06719610..2700e9c1 100644 --- a/rust/crates/core/src/runtime/request_trace.rs +++ b/rust/crates/core/src/runtime/request_trace.rs @@ -153,6 +153,7 @@ pub(crate) fn is_hot(method: &str) -> bool { method, "document.classifyText" | "document.lifecycle" + | "plugins.workflow" | "markdown.render" | "markdown.outline" | "markdown.resolveReference" diff --git a/rust/crates/plugin-rpc/Cargo.toml b/rust/crates/plugin-rpc/Cargo.toml index 762475c4..616471a4 100644 --- a/rust/crates/plugin-rpc/Cargo.toml +++ b/rust/crates/plugin-rpc/Cargo.toml @@ -14,3 +14,4 @@ lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } +url = "2.5" diff --git a/rust/crates/plugin-rpc/src/host_params.rs b/rust/crates/plugin-rpc/src/host_params.rs index 36b2803e..91847a48 100644 --- a/rust/crates/plugin-rpc/src/host_params.rs +++ b/rust/crates/plugin-rpc/src/host_params.rs @@ -30,6 +30,7 @@ pub(crate) fn check_host_params( _ => return Err(invalid("Params must be an object.")), }; let allowed: &[&str] = match rule { + HostParams::Workflow => return Err(invalid("Workflow validation requires a method.")), HostParams::Empty => &[], HostParams::Credential { with_secret: true } => &["key", "secret"], HostParams::Credential { with_secret: false } => &["key"], @@ -284,7 +285,7 @@ pub(crate) fn check_host_params( | HostParams::WorkspaceWatch | HostParams::WorkspaceFindFiles | HostParams::WorkspaceFindText => check_workspace_read_params(rule, params, &invalid)?, - HostParams::Empty | HostParams::Object => {} + HostParams::Empty | HostParams::Object | HostParams::Workflow => {} } Ok(()) } diff --git a/rust/crates/plugin-rpc/src/host_requests.rs b/rust/crates/plugin-rpc/src/host_requests.rs index ea9b77ac..e5e801f2 100644 --- a/rust/crates/plugin-rpc/src/host_requests.rs +++ b/rust/crates/plugin-rpc/src/host_requests.rs @@ -89,6 +89,8 @@ pub(crate) enum HostParams { WorkspaceFindFiles, /// A bounded text search at the workspace root (plan API-08). WorkspaceFindText, + /// Strict, bounded interactive, presentation and managed-network requests. + Workflow, /// Any object whose `context`, when present, is a well-formed /// reference. The service checks the rest and answers /// `plugin.host.invalidParams` or, for a field it does not know, @@ -112,6 +114,120 @@ pub(crate) struct HostMethod { /// service adds its rows here, its grant to `GRANTABLE_HOST_SERVICES` and /// the manifest permission, and its handler to the host's dispatcher. pub(crate) const HOST_METHODS: &[HostMethod] = &[ + HostMethod { + method: "lithe/host/window/showQuickPick", + service: "window", + permission: Some("window.input"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/window/showInputBox", + service: "window", + permission: Some("window.input"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/preview/openMarkdown", + service: "preview", + permission: Some("preview.open"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/editor/showDiff", + service: "editor", + permission: Some("editor.open"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/views/refresh", + service: "views", + permission: Some("views.refresh"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/output/create", + service: "output", + permission: Some("output.write"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/output/append", + service: "output", + permission: Some("output.write"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/output/clear", + service: "output", + permission: Some("output.write"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/output/show", + service: "output", + permission: Some("output.write"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/output/dispose", + service: "output", + permission: Some("output.write"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/progress/create", + service: "progress", + permission: Some("window.progress"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/progress/report", + service: "progress", + permission: Some("window.progress"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/progress/end", + service: "progress", + permission: Some("window.progress"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/statusBar/setItem", + service: "statusBar", + permission: Some("statusBar.write"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/statusBar/removeItem", + service: "statusBar", + permission: Some("statusBar.write"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/clipboard/readText", + service: "clipboard", + permission: Some("clipboard.read"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/clipboard/writeText", + service: "clipboard", + permission: Some("clipboard.write"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/workspace/reveal", + service: "workspace", + permission: Some("workspace.reveal"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/network/request", + service: "network", + permission: Some("network.request"), + params: HostParams::Workflow, + }, HostMethod { method: RUN_START, service: HOST_SERVICE_RUN, @@ -409,13 +525,13 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ method: "lithe/host/preview/openHTML", service: "preview", permission: Some("preview.open"), - params: HostParams::Object, + params: HostParams::Workflow, }, HostMethod { method: "lithe/host/browser/openExternal", service: "browser", permission: Some("browser.open"), - params: HostParams::Object, + params: HostParams::Workflow, }, HostMethod { method: "lithe/host/window/showInformation", @@ -534,7 +650,11 @@ pub fn host_request( details: None, }); } - check_host_params(entry.params, params)?; + if entry.params == HostParams::Workflow { + workflow::check_params(method, params.unwrap_or(&Value::Null))?; + } else { + check_host_params(entry.params, params)?; + } if entry.method == GET_CAPABILITIES { return Ok(HostRoute::Answer(capabilities_answer(version, granted))); } diff --git a/rust/crates/plugin-rpc/src/lib.rs b/rust/crates/plugin-rpc/src/lib.rs index 9b41d1cd..239abcb3 100644 --- a/rust/crates/plugin-rpc/src/lib.rs +++ b/rust/crates/plugin-rpc/src/lib.rs @@ -21,6 +21,7 @@ //! dispatchers. pub mod host_api; +pub mod workflow; use lithe_plugin_language_servers::is_protocol_name; use lithe_plugin_model::capabilities::{ @@ -138,6 +139,15 @@ pub fn methods_for_permission(permission: &str) -> Vec<&'static str> { /// Permissions for the additive host services. pub const HOST_PERMISSIONS: &[&str] = &[ + "window.input", + "views.refresh", + "output.write", + "window.progress", + "statusBar.write", + "clipboard.read", + "clipboard.write", + "workspace.reveal", + "network.request", "workspace.files.read", "workspace.files.watch", "build.options.read", diff --git a/rust/crates/plugin-rpc/src/workflow.rs b/rust/crates/plugin-rpc/src/workflow.rs new file mode 100644 index 00000000..9ddd105b --- /dev/null +++ b/rust/crates/plugin-rpc/src/workflow.rs @@ -0,0 +1,618 @@ +//! Strict host workflow contracts and bounded projections. Native hosts own UI, +//! sockets and resource lifetimes; this module owns grants, shapes and budgets. + +use crate::{ + codes, host_rpc_code, is_command_id, is_context_reference, is_credential_key, + HostRequestRefusal, +}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde_json::{json, Map, Value}; +use std::collections::BTreeSet; + +/// Maximum UTF-8 bytes in an inline document, HTTP body or clipboard transfer. +pub const TEXT_BYTES: usize = 128 * 1024; +/// Maximum response header bytes accepted by the desktop HTTP transport. +pub const HTTP_HEADER_BYTES: usize = 16 * 1024; +/// Maximum retained output lines per channel. +pub const OUTPUT_LINES: usize = 4000; +/// Maximum retained output bytes per channel. +pub const OUTPUT_BYTES: usize = 512 * 1024; +/// Maximum bytes of an unfinished output line. +pub const OUTPUT_LINE_BYTES: usize = 16 * 1024; +/// Maximum channels, progress handles and status items per backend session (shared with other limited host registrations). +pub const RESOURCE_LIMIT: usize = 16; + +fn invalid() -> HostRequestRefusal { + HostRequestRefusal { + rpc_code: -32602, + code: codes::HOST_INVALID_PARAMS, + message: "Invalid workflow parameters.", + details: None, + } +} + +fn object<'a>( + value: &'a Value, + fields: &[&str], +) -> Result<&'a Map, HostRequestRefusal> { + let map = value.as_object().ok_or_else(invalid)?; + if let Some(key) = map.keys().find(|key| !fields.contains(&key.as_str())) { + return Err(HostRequestRefusal { + rpc_code: host_rpc_code(codes::HOST_UNSUPPORTED_OPTION), + code: codes::HOST_UNSUPPORTED_OPTION, + message: "Unsupported workflow option.", + details: Some(json!({"option":key})), + }); + } + Ok(map) +} + +fn text(map: &Map, key: &str, max: usize, required: bool, line: bool) -> bool { + match map.get(key) { + None => !required, + Some(value) => value.as_str().is_some_and(|text| { + text.len() <= max + && (!required || !text.is_empty()) + && (!line || !text.chars().any(char::is_control)) + }), + } +} +fn flag(map: &Map, key: &str) -> bool { + map.get(key).is_none_or(Value::is_boolean) +} +fn key(map: &Map, name: &str) -> bool { + map.get(name) + .and_then(Value::as_str) + .is_some_and(is_credential_key) +} +fn resource(value: &Value) -> bool { + value.as_object().is_some_and(|map| { + map.len() == 2 + && key(map, "rootID") + && map.get("path").and_then(Value::as_str).is_some_and(|path| { + path.len() <= 4096 + && !path.contains(['\\', '\0', ':']) + && !path.starts_with('/') + && (path.is_empty() + || path + .split('/') + .all(|p| !p.is_empty() && p != "." && p != "..")) + }) + }) +} + +/// Checks one backend request before the session forwards it to native code. +/// Unknown fields retain the protocol's distinct unsupported-option error. +pub fn check_params(method: &str, params: &Value) -> Result<(), HostRequestRefusal> { + let name = method.strip_prefix("lithe/host/").unwrap_or(method); + let fields: &[&str] = match name { + "window/showQuickPick" => &["context", "title", "placeholder", "items", "canPickMany"], + "window/showInputBox" => &[ + "context", + "title", + "prompt", + "placeholder", + "value", + "password", + ], + "preview/openMarkdown" | "preview/openHTML" => &[ + "context", + "resource", + "text", + "title", + "id", + "presentation", + "range", + ], + "editor/showDiff" => &[ + "context", + "title", + "original", + "modified", + "originalTitle", + "modifiedTitle", + ], + "views/refresh" => &["context", "instance"], + "output/create" => &["context", "name"], + "output/append" => &["context", "channelID", "text"], + "output/clear" | "output/show" | "output/dispose" => &["context", "channelID"], + "progress/create" => &["context", "title", "cancellable"], + "progress/report" => &["context", "progressID", "message", "percentage"], + "progress/end" => &["context", "progressID"], + "statusBar/setItem" => &["context", "id", "text", "tooltip", "commandID", "priority"], + "statusBar/removeItem" => &["context", "id"], + "clipboard/readText" => &["context"], + "clipboard/writeText" => &["context", "text"], + "workspace/reveal" => &["context", "resource"], + "browser/openExternal" => &["context", "url", "resource", "unsaved"], + "network/request" => &[ + "context", + "url", + "method", + "headers", + "body", + "timeoutMilliseconds", + "maximumResponseBytes", + ], + _ => return Err(invalid()), + }; + let p = object(params, fields)?; + if !p.get("context").is_some_and(is_context_reference) { + return Err(invalid()); + } + let valid = match name { + "window/showQuickPick" => { + let mut ids = BTreeSet::new(); + text(p, "title", 512, false, true) + && text(p, "placeholder", 512, false, true) + && flag(p, "canPickMany") + && p.get("items") + .and_then(Value::as_array) + .is_some_and(|items| { + items.len() <= 1000 + && items.iter().all(|item| { + let Ok(item) = object( + item, + &["id", "label", "description", "detail", "picked"], + ) else { + return false; + }; + key(item, "id") + && ids.insert(item["id"].as_str().unwrap_or_default()) + && text(item, "label", 512, true, true) + && text(item, "description", 512, false, true) + && text(item, "detail", 1024, false, true) + && flag(item, "picked") + }) + }) + } + "window/showInputBox" => { + text(p, "title", 512, false, true) + && text(p, "prompt", 2048, false, true) + && text(p, "placeholder", 512, false, true) + && text(p, "value", 16 * 1024, false, true) + && flag(p, "password") + && !(p.get("password") == Some(&Value::Bool(true)) + && p.get("value") + .and_then(Value::as_str) + .is_some_and(|v| !v.is_empty())) + } + "preview/openMarkdown" | "preview/openHTML" => { + let source = match (p.get("resource"), p.get("text")) { + (Some(value), None) => resource(value), + (None, Some(_)) => { + text(p, "text", TEXT_BYTES, false, false) + && key(p, "id") + && text(p, "title", 256, true, true) + } + _ => false, + }; + source + && p.get("presentation") + .is_none_or(|v| matches!(v.as_str(), Some("editorAndPreview" | "previewOnly"))) + && p.get("range").is_none_or(|v| { + let position = |v: &Value| { + v.as_object().is_some_and(|o| { + o.len() == 2 + && ["line", "column"].iter().all(|key| { + o.get(*key) + .and_then(Value::as_u64) + .is_some_and(|n| n > 0 && n <= u32::MAX as u64) + }) + }) + }; + v.as_object().is_some_and(|o| { + o.len() == 2 + && o.get("start").is_some_and(position) + && o.get("end").is_some_and(position) + && (o["start"]["line"].as_u64(), o["start"]["column"].as_u64()) + <= (o["end"]["line"].as_u64(), o["end"]["column"].as_u64()) + }) + }) + } + "editor/showDiff" => { + ["original", "modified"].iter().all(|k| { + p.get(*k) + .and_then(Value::as_str) + .is_some_and(|v| v.len() <= TEXT_BYTES) + }) && ["title", "originalTitle", "modifiedTitle"] + .iter() + .all(|k| text(p, k, 256, false, true)) + } + "views/refresh" => key(p, "instance"), + "output/create" => text(p, "name", 256, true, true), + "output/append" => { + key(p, "channelID") + && text(p, "text", TEXT_BYTES, false, false) + && p.contains_key("text") + } + "output/clear" | "output/show" | "output/dispose" => key(p, "channelID"), + "progress/create" => text(p, "title", 256, true, true) && flag(p, "cancellable"), + "progress/report" => { + key(p, "progressID") + && text(p, "message", 1024, false, true) + && p.get("percentage").is_none_or(|v| { + v.as_f64() + .is_some_and(|n| n.is_finite() && (0.0..=100.0).contains(&n)) + }) + } + "progress/end" => key(p, "progressID"), + "statusBar/setItem" => { + key(p, "id") + && text(p, "text", 256, true, true) + && text(p, "tooltip", 1024, false, true) + && p.get("commandID") + .is_none_or(|v| v.as_str().is_some_and(is_command_id)) + && p.get("priority") + .is_none_or(|v| v.as_i64().is_some_and(|n| (-1000..=1000).contains(&n))) + } + "statusBar/removeItem" => key(p, "id"), + "clipboard/readText" => true, + "clipboard/writeText" => { + p.contains_key("text") && text(p, "text", TEXT_BYTES, false, false) + } + "workspace/reveal" => p.get("resource").is_some_and(resource), + "browser/openExternal" => match (p.get("url"), p.get("resource")) { + (Some(Value::String(url)), None) => !p.contains_key("unsaved") && http_address(url), + (None, Some(value)) => { + resource(value) + && p.get("unsaved").is_none_or(|v| { + matches!(v.as_str(), Some("openSavedFile" | "requireSaved")) + }) + } + _ => false, + }, + "network/request" => network_valid(p), + _ => false, + }; + if valid { + Ok(()) + } else { + Err(invalid()) + } +} + +fn http_address(address: &str) -> bool { + address.len() <= 8192 + && !address.chars().any(char::is_control) + && url::Url::parse(address).is_ok_and(|url| { + matches!(url.scheme(), "http" | "https") + && url.host_str().is_some() + && url.username().is_empty() + && url.password().is_none() + }) +} + +fn network_valid(p: &Map) -> bool { + let address = p + .get("url") + .and_then(Value::as_str) + .filter(|s| http_address(s)) + .and_then(|s| url::Url::parse(s).ok()); + let url_valid = address.is_some_and(|url| { + matches!(url.scheme(), "http" | "https") + && url.host_str().is_some() + && url.username().is_empty() + && url.password().is_none() + && url.fragment().is_none() + }); + let method = p.get("method").is_none_or(|v| { + v.as_str().is_some_and(|s| { + matches!( + s, + "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS" + ) + }) + }); + let headers = p.get("headers").is_none_or(|headers| { + headers.as_object().is_some_and(|headers| { + headers.len() <= 64 + && headers.iter().all(|(name, value)| { + !name.is_empty() + && name.len() <= 128 + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) + && !matches!( + name.to_ascii_lowercase().as_str(), + "host" + | "connection" + | "content-length" + | "transfer-encoding" + | "proxy-authorization" + | "proxy-connection" + | "upgrade" + | "trailer" + | "te" + ) + && value.as_str().is_some_and(|v| { + v.len() <= 8192 + && !v.chars().any(|c| c == '\r' || c == '\n' || c == '\0') + }) + }) + }) + }); + url_valid + && method + && headers + && text(p, "body", TEXT_BYTES, false, false) + && p.get("timeoutMilliseconds") + .is_none_or(|v| v.as_u64().is_some_and(|n| (1..=30_000).contains(&n))) + && p.get("maximumResponseBytes").is_none_or(|v| { + v.as_u64() + .is_some_and(|n| (1..=TEXT_BYTES as u64).contains(&n)) + }) +} + +fn core_invalid() -> CoreError { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid plugin workflow projection.", + ) +} +fn cut_tail(text: &str, limit: usize) -> &str { + let mut start = text.len().saturating_sub(limit); + while !text.is_char_boundary(start) { + start += 1; + } + &text[start..] +} + +/// Plans native requests, filters bounded quick-pick candidates, and splits one +/// output increment. No full output history crosses the application boundary. +pub fn command(payload: Value) -> Result { + let p = payload.as_object().ok_or_else(core_invalid)?; + match p.get("operation").and_then(Value::as_str) { + Some("prepare") => { + object(&payload, &["operation", "method", "params"]).map_err(|_| core_invalid())?; + let method = p + .get("method") + .and_then(Value::as_str) + .ok_or_else(core_invalid)?; + let mut params = p.get("params").cloned().ok_or_else(core_invalid)?; + check_params(method, ¶ms).map_err(|failure| { + CoreError::new(ErrorCode::InvalidRequest, failure.message) + .with_details(failure.code) + })?; + if method.ends_with("network/request") { + let map = params.as_object_mut().ok_or_else(core_invalid)?; + map.entry("method").or_insert(json!("GET")); + map.entry("headers").or_insert(json!({})); + map.entry("timeoutMilliseconds").or_insert(json!(30_000)); + map.entry("maximumResponseBytes") + .or_insert(json!(TEXT_BYTES)); + } + Ok( + json!({"params":params,"limits":{"textBytes":TEXT_BYTES,"httpHeaderBytes":HTTP_HEADER_BYTES,"outputLines":OUTPUT_LINES,"outputBytes":OUTPUT_BYTES,"resources":RESOURCE_LIMIT}}), + ) + } + Some("quickPick") => { + object(&payload, &["operation", "items", "query"]).map_err(|_| core_invalid())?; + let items = p + .get("items") + .and_then(Value::as_array) + .filter(|v| v.len() <= 1000) + .ok_or_else(core_invalid)?; + let query = p + .get("query") + .and_then(Value::as_str) + .filter(|q| q.len() <= 1024) + .ok_or_else(core_invalid)? + .to_lowercase(); + let words: Vec<_> = query.split_whitespace().collect(); + let indices: Vec<_> = items + .iter() + .enumerate() + .filter_map(|(index, item)| { + let search = ["label", "description", "detail"] + .iter() + .filter_map(|k| item.get(*k).and_then(Value::as_str)) + .collect::>() + .join(" ") + .to_lowercase(); + words + .iter() + .all(|word| search.contains(word)) + .then_some(index) + }) + .collect(); + Ok(json!({"indices":indices})) + } + Some("status") => { + object(&payload, &["operation", "items"]).map_err(|_| core_invalid())?; + let items = p + .get("items") + .and_then(Value::as_array) + .filter(|items| items.len() <= RESOURCE_LIMIT * 16) + .ok_or_else(core_invalid)?; + let mut order = Vec::new(); + for (index, item) in items.iter().enumerate() { + let item = object(item, &["id", "priority"]).map_err(|_| core_invalid())?; + let id = item + .get("id") + .and_then(Value::as_str) + .filter(|id| id.len() <= 512) + .ok_or_else(core_invalid)?; + let priority = item + .get("priority") + .and_then(Value::as_i64) + .filter(|n| (-1000..=1000).contains(n)) + .ok_or_else(core_invalid)?; + order.push((index, priority, id)); + } + order.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.2.cmp(b.2))); + Ok(json!({"ids":order.into_iter().map(|(_,_,id)|id).collect::>()})) + } + Some("input") => { + object(&payload, &["operation", "pick", "value"]).map_err(|_| core_invalid())?; + let pick = p + .get("pick") + .and_then(Value::as_bool) + .ok_or_else(core_invalid)?; + let value = p + .get("value") + .and_then(Value::as_str) + .ok_or_else(core_invalid)?; + let valid = value.len() <= if pick { 1024 } else { 16 * 1024 } + && !value.chars().any(char::is_control); + Ok(json!({"valid":valid})) + } + Some("treePage") => { + object( + &payload, + &[ + "operation", + "cursor", + "lastCursor", + "count", + "lastCount", + "rows", + "lastVisible", + ], + ) + .map_err(|_| core_invalid())?; + let cursor = p + .get("cursor") + .and_then(Value::as_str) + .filter(|s| s.len() <= 256) + .ok_or_else(core_invalid)?; + let last = p + .get("lastCursor") + .and_then(Value::as_str) + .filter(|s| s.len() <= 256) + .ok_or_else(core_invalid)?; + let number = |key| { + p.get(key) + .and_then(Value::as_u64) + .filter(|n| *n <= 2000) + .ok_or_else(core_invalid) + }; + let count = number("count")?; + let previous = number("lastCount")?; + let visible = number("lastVisible")?; + let rows = number("rows")?; + // A page advances the cursor and grows the retained range. A plugin + // replaces its full loaded range or patches it; the host never merges pages. + Ok( + json!({"load":!cursor.is_empty() && cursor!=last && (last.is_empty() || count>previous) && rows>0 && visible>=rows.saturating_sub(8)}), + ) + } + Some("output") => { + object(&payload, &["operation", "open", "text"]).map_err(|_| core_invalid())?; + let open = p + .get("open") + .and_then(Value::as_str) + .filter(|s| s.len() <= OUTPUT_LINE_BYTES) + .ok_or_else(core_invalid)?; + let text = p + .get("text") + .and_then(Value::as_str) + .filter(|s| s.len() <= TEXT_BYTES) + .ok_or_else(core_invalid)?; + let joined = format!("{open}{text}"); + let mut lines: Vec<&str> = joined.split('\n').collect(); + let last = lines.pop().unwrap_or_default(); + let lines: Vec<_> = lines + .into_iter() + .map(|line| cut_tail(line.trim_end_matches('\r'), OUTPUT_LINE_BYTES)) + .collect(); + Ok( + json!({"lines":lines,"open":cut_tail(last,OUTPUT_LINE_BYTES),"maxLines":OUTPUT_LINES,"maxBytes":OUTPUT_BYTES}), + ) + } + _ => Err(core_invalid()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{host_request, HostRoute}; + + #[test] + fn grants_are_individual_and_workflow_params_are_strict() { + let method = "lithe/host/window/showInputBox"; + let context = json!({"contextID":"context-1","generation":1}); + let params = json!({"context":context,"password":true}); + assert_eq!( + host_request( + method, + Some(¶ms), + Some(0), + &["window".to_string()].into_iter().collect() + ) + .unwrap_err() + .code, + codes::HOST_PERMISSION_DENIED + ); + let grants = [method.to_string()].into_iter().collect(); + assert_eq!( + host_request(method, Some(¶ms), Some(0), &grants).unwrap(), + HostRoute::Forward("window") + ); + let mut unknown = params.clone(); + unknown["secret"] = json!("hidden"); + assert_eq!( + check_params(method, &unknown).unwrap_err().code, + codes::HOST_UNSUPPORTED_OPTION + ); + let mut seeded = params; + seeded["value"] = json!("do not reveal stored secrets"); + assert!(check_params(method, &seeded).is_err()); + } + + #[test] + fn managed_http_rejects_unsafe_headers_urls_and_budgets() { + let base = json!({"context":{"contextID":"c","generation":1},"url":"https://example.test/query","method":"POST","headers":{"Authorization":"credential","Content-Type":"application/json"},"body":"{}"}); + assert!(check_params("network/request", &base).is_ok()); + for patch in [ + json!({"url":"file:///etc/hosts"}), + json!({"url":"https://user:secret@example.test"}), + json!({"headers":{"Host":"other.test"}}), + json!({"headers":{"X-Test":"bad\r\nheader"}}), + json!({"maximumResponseBytes":TEXT_BYTES+1}), + json!({"timeoutMilliseconds":30001}), + ] { + let mut value = base.clone(); + value + .as_object_mut() + .unwrap() + .extend(patch.as_object().unwrap().clone()); + assert!(check_params("network/request", &value).is_err()); + } + let planned = + command(json!({"operation":"prepare","method":"network/request","params":base})) + .unwrap(); + assert_eq!(planned["params"]["maximumResponseBytes"], TEXT_BYTES); + } + + #[test] + fn projections_keep_search_order_and_bound_unfinished_output() { + let filtered = command(json!({"operation":"quickPick","items":[{"label":"Alpha","detail":"Rust"},{"label":"Beta","description":"Rust"},{"label":"Gamma"}],"query":"rust beta"})).unwrap(); + assert_eq!(filtered["indices"], json!([1])); + assert_eq!(command(json!({"operation":"status","items":[{"id":"b","priority":2},{"id":"a","priority":2},{"id":"c","priority":3}]})).unwrap()["ids"],json!(["c","a","b"])); + assert_eq!(command(json!({"operation":"treePage","cursor":"next","lastCursor":"previous","count":20,"lastCount":20,"rows":20,"lastVisible":19})).unwrap()["load"],false); + assert_eq!( + command(json!({"operation":"input","pick":false,"value":"a\nb"})).unwrap()["valid"], + false + ); + let result = command(json!({"operation":"output","open":"first","text":format!(" second\n{}", "字".repeat(20_000))})).unwrap(); + assert_eq!(result["lines"], json!(["first second"])); + assert!(result["open"].as_str().unwrap().len() <= OUTPUT_LINE_BYTES); + } + + #[test] + fn workflow_fixture_covers_projection_and_paging_boundaries() { + let fixture: Value = + serde_json::from_str(include_str!("../../../fixtures/plugins/workflow-v1.json")) + .unwrap(); + for case in fixture["cases"].as_array().unwrap() { + assert_eq!( + command(case["request"].clone()).unwrap(), + case["result"], + "{}", + case["name"] + ); + } + } +} diff --git a/rust/crates/plugin-ui/src/tree.rs b/rust/crates/plugin-ui/src/tree.rs index 2ba0a5c0..3583bb25 100644 --- a/rust/crates/plugin-ui/src/tree.rs +++ b/rust/crates/plugin-ui/src/tree.rs @@ -367,12 +367,13 @@ impl<'c> Walk<'c> { if self.context.surface != Surface::ToolWindow { return Err(fail(path, "Trees appear in tool windows.")); } - let map = object(value, path, &["type", "id", "label", "items"])?; + let map = object(value, path, &["type", "id", "label", "items", "cursor"])?; self.id(map, path, true)?; line(map, path, "label", MAX_LABEL_CHARS, false)?; let items = map .get("items") .ok_or_else(|| fail(at(path, "items"), "Required."))?; + line(map, path, "cursor", 256, false)?; let mut ids = BTreeSet::new(); let mut count = 0; tree_items(items, &at(path, "items"), 1, &mut ids, &mut count) @@ -466,7 +467,15 @@ fn tree_items( let map = object( item, &item_path, - &["id", "label", "icon", "detail", "expanded", "children"], + &[ + "id", + "label", + "icon", + "detail", + "expanded", + "children", + "hasChildren", + ], )?; let id = identifier(map, &item_path, "id", true)?.unwrap_or_default(); if !ids.insert(id.to_owned()) { @@ -478,6 +487,7 @@ fn tree_items( line(map, &item_path, "label", MAX_LABEL_CHARS * 2, true)?; line(map, &item_path, "detail", MAX_LABEL_CHARS * 2, false)?; boolean(map, &item_path, "expanded")?; + boolean(map, &item_path, "hasChildren")?; if let Some(icon) = string(map, &item_path, "icon", false)? { let host: Option = serde_json::from_value(json!({"host": icon})).ok(); if !host.is_some_and(|icon| icon.is_valid_host_icon()) { diff --git a/rust/crates/project/src/html_preview.rs b/rust/crates/project/src/html_preview.rs index d8d9f34c..dfc48dd5 100644 --- a/rust/crates/project/src/html_preview.rs +++ b/rust/crates/project/src/html_preview.rs @@ -135,6 +135,13 @@ pub enum HtmlPreviewResource { /// The site of a document, or `None` for a document that is not an absolute file path. pub fn html_preview_site(request: HtmlPreviewSiteRequest) -> Option { + if request.document_path.starts_with("lithe-plugin-preview:") { + return Some(HtmlPreviewSite { + root: String::new(), + address: "index.html".into(), + mime: "text/html; charset=utf-8".into(), + }); + } let document = Path::new(&request.document_path); let (_, root) = document_scope(document, request.workspace_root.as_deref())?; let relative = names(document.strip_prefix(root).ok()?)?; @@ -159,6 +166,13 @@ pub fn html_preview_site(request: HtmlPreviewSiteRequest) -> Option