diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 98d273ba..940ef8fc 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -607,6 +607,13 @@ or removing a command fails until the table changes in the same commit. | `workspace.configureIndexing` | Install a process-local, canonical-root indexing policy before workspace consumers run; returns a monotonic revision, effective directory reasons and Git failure state; see `rust/fixtures/workspace/indexing-policy-v1.json` | | `workspace.refreshIndexing` | Refresh external Git decisions for a live `root`, `ownerId`, `revision` lease without changing preferences or release tokens; returns lazy `IndexingStatus` | | `workspace.filterChanges` | Filter an array of workspace-relative paths, or `{ paths, hiddenFilePatterns }` whose `!` entries turn default exclusions off, against Core's default hidden folders and patterns, including the folders enabled plugins declare; preserve order, spelling, and the empty root path. Native event loss bypasses filtering. Hosts relativize to the most specific explicit watch root and retain explicitly watched files | +| `workspace.findFiles` | Bounded plugin disk file-name search with a query-bound cursor (API-08) | +| `workspace.findText` | Bounded plugin disk text search, without dirty buffers (API-08) | +| `workspace.watchPlan` | Validate a local watch target before native registration (API-07) | +| `workspace.watchEvents` | Filter and bound one native root-relative event batch (API-07) | +| `workspace.readDirectory` | Return one bounded no-follow disk directory page for API-06; see Workspace disk reads below | +| `workspace.stat` | Stat a workspace leaf without following it or any ancestor link (API-06) | +| `workspace.readFile` | Read at most 128 KiB of regular-file disk bytes without following links (API-06) | | `workspace.listDirectories` | Return one visible level of children for each requested workspace-relative directory (`""` is the root); missing, hidden, external/cyclic symlink, or nested-worktree paths are omitted; workspace-internal aliases are browsable and each listing reports `linked: true` when reached through an alias, and each listing reports the nested worktrees it left out. Child directories have `children: []` only when a shallow probe proves them visibly empty; otherwise children remain omitted (unloaded), with no recursive tree allocation. Children list directories first, then names in IDEA's natural file-name order (digit runs compare by value, case-insensitive, `-` next to `_`; fixture `rust/fixtures/workspace/file-name-order-v1.json`) | | `workspace.orderEntries` | Order natively enumerated directory siblings | | `workspace.projectTree.rows` | Say which loaded project tree nodes show as rows, keep the selection on a row that shows, and find the row the top of the view was on, without reading the disk (from `lithe-project-tree`) | @@ -7492,6 +7499,93 @@ to exist, creates the copy without replacing anything (`FileManager.copyItem`, w appeared meanwhile, adds the name to `existing` and plans again. After 512 rounds the host reports the stable `destination_exists` error. Cases are in `rust/fixtures/workspace/file-copy-names-v1.json`. +### Plugin workspace search and watches + +`workspace.findFiles` takes `{root,query,fileMask?,cursor?,limit?,hiddenDirectoryNames?,hiddenFilePatterns?}`. +`workspace.findText` takes `{root,pattern,fileMask?,caseSensitive?,wholeWords?,regularExpression?,cursor?,limit?,hiddenDirectoryNames?,hiddenFilePatterns?}`. +Queries/patterns are nonempty and at most 4096 UTF-8 bytes; masks have the same +byte cap. Limits default to 100 and accept 1–200. Matching reuses the workspace +literal/regular-expression matcher and comma-separated basename globs. Files +sort by UTF-8 relative path bytes, text hits by path then one-based line, one +hit per line with `range:null` and a trimmed preview of at most 500 characters. +The returned envelope is `{matches,nextCursor,isTruncated,source:"disk"}`; +file matches are `{path}`, text matches are `{path,line,preview,range:null}`. + +Search walks no-follow handles, applies shared hidden rules and the installed +indexing exclusion policy (including its Git-ignore decisions), skips links and +special entries, and consults no dirty buffer. File contents use the existing +search text decoder, with binary and undecodable files omitted. At most 2 MiB +are read per text file, with one sentinel byte; traversal depth caps at 128. +Oversized files, deeper directories and an overall 200-hit cap set +`isTruncated:true`. At most a page plus one candidate is retained; serialized +pages reserve host envelopes under 900 KiB. A live cursor binds canonical root, +query/options, effective visibility and indexing generation, keeps no server +snapshot, and resumes after the last result; page size may change. A changed +query/policy or malformed cursor uses `invalid_request`; invalid regex uses +`parse_failed`. Cancellation and a 30-second deadline are checked per entry, +chunk and line; native syscalls can still block. I/O failures are returned, +except concurrently vanished entries. Remote workspaces are unsupported. + +`workspace.watchPlan` takes `{root,path,recursive?}` (false by default) and +returns `{root,path,isDirectory,recursive}` with a canonical root. Targets +must exist and be a regular file or directory, with no plugin-supplied link +component. The native adapter watches root changes, checks the root/target +identity again after registration, and owns the native stream and its cleanup. +`workspace.watchEvents` takes this plan plus `paths`, optional +`requiresRescan`, `hiddenDirectoryNames`, `hiddenFilePatterns`. It returns +`{changedPaths,requiresRescan}` with sorted, deduplicated, root-relative visible +names. File watches select the exact file; directory watches select immediate +children or descendants when recursive. Ancestor changes request a rescan. +Deleted names remain valid, existing ancestor links/reparse points are rejected, +and leaf links are omitted. Native loss, malformed names, more than 1000 input +paths or the 900 KiB event budget set `requiresRescan:true`. This command is +untraced because it runs on each native watch batch. Native registration and +plugin/context/session ownership remain in the desktop adapter, without polling, +filesystem writes or retained file content. + +Fixture: `rust/fixtures/workspace/find-watch-v1.json`. + +### Workspace disk reads + +`workspace.readDirectory` takes `{root,path,cursor?,limit?,hiddenDirectoryNames?,hiddenFilePatterns?}`. +`workspace.stat` takes `{root,path}` and `workspace.readFile` takes +`{root,path,maximumBytes?}`. `root` is an absolute authorized local directory; +`path` is a strictly `/`-separated path below it, at most 4096 UTF-8 bytes with +no backslash, NUL, absolute prefix, empty, `.` or `..` component. Empty path names +the root for listing/stat only. Windows components obey native storable-name rules. +Unknown payload fields and invalid bounds fail with `invalid_request`. + +Listing defaults to 200, accepts 1–1000, and retains at most `limit + 1` ordered +candidates while streaming a directory. It applies shared effective hidden rules, +omits links/reparse points and unrepresentable paths, and returns +`{entries:[{name,path,kind}],nextCursor}`. Entries sort by UTF-8 name bytes. +A serialized page has a 900 KiB budget, reserving space for host resource envelopes, +so a page may be shorter than its limit. Cursors bind canonical root, directory and +filters and resume after the last name, without keeping a server-side snapshot. +`stat` returns `{path,kind,size,modifiedMilliseconds}`; `kind` is `file`, +`directory`, `symlink` or `other`, and unavailable/pre-epoch timestamps are null. +The leaf's own metadata is returned; ancestor links are refused. + +Reading accepts `maximumBytes` in 1–131072, default 131072, and returns +`{path,source:"disk",byteCount,isTruncated,identity,text?,encoding?,base64?}`. +It reads at most the limit plus one byte, discards the sentinel and hashes only +the returned prefix. `identity` is `{sha256,byteCount,isTruncated}` and describes +those exact bytes, not an atomic whole-file snapshot. Strict UTF-8 without control +characters except tab/CR/LF returns text with `encoding:"utf-8"` (BOM preserved); +all other prefixes, including incomplete UTF-8, use standard base64. Exactly one +of text/base64 is present. No editor buffer is consulted. + +Unix walks held directory descriptors with `openat/O_NOFOLLOW`; Windows rejects +reparse points and retains directory handles without write/delete sharing. +Non-regular files cannot be read. These commands reject `remoteWorkspace` before +local I/O. Missing roots use `workspace_not_found`, missing entries use +`entry_not_found`, link traversal and access failures use `permission_denied`, +and other I/O failures use `unknown`. Enumeration and chunk reads check cancellation +and a 30-second deadline; native filesystem calls may still block in the kernel. +The host checks context/root ownership and wraps returned paths as resources; +it maps the Core errors to the public API-06 errors. +Fixture: `rust/fixtures/workspace/read-v1.json`. + `workspace.createEntry`, `workspace.renameEntry`, `workspace.copyEntry` and `workspace.resolveEntry` change and name entries below a local workspace root on a plugin's behalf (plan API-11). Each takes `root`, the absolute path of the root as the host spells it, and `path`, the entry below it. diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 26c6688a..38ebc2be 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -536,6 +536,20 @@ pub enum WorkspaceCommand { RefreshIndexing, /// Releases an indexing generation when its project closes. ReleaseIndexing, + /// Reads a bounded no-follow directory page (`workspace.readDirectory`). + ReadDirectory, + /// Stats a workspace entry without following its leaf (`workspace.stat`). + Stat, + /// Reads bounded disk bytes without following links (`workspace.readFile`). + ReadFile, + /// Searches plugin-visible disk file names (`workspace.findFiles`). + FindFiles, + /// Searches plugin-visible disk text (`workspace.findText`). + FindText, + /// Validates a native workspace watch target (`workspace.watchPlan`). + WatchPlan, + /// Projects a native watch batch (`workspace.watchEvents`). + WatchEvents, /// Lists the visible children of project directories (`workspace.listDirectories`). ListDirectories, /// Says which loaded project tree nodes show as rows and keeps the selection on one @@ -1367,6 +1381,13 @@ impl CoreCommand { } "workspace.refreshIndexing" => Some(Self::Workspace(WorkspaceCommand::RefreshIndexing)), "workspace.filterChanges" => Some(Self::Workspace(WorkspaceCommand::FilterChanges)), + "workspace.findFiles" => Some(Self::Workspace(WorkspaceCommand::FindFiles)), + "workspace.findText" => Some(Self::Workspace(WorkspaceCommand::FindText)), + "workspace.watchPlan" => Some(Self::Workspace(WorkspaceCommand::WatchPlan)), + "workspace.watchEvents" => Some(Self::Workspace(WorkspaceCommand::WatchEvents)), + "workspace.readDirectory" => Some(Self::Workspace(WorkspaceCommand::ReadDirectory)), + "workspace.stat" => Some(Self::Workspace(WorkspaceCommand::Stat)), + "workspace.readFile" => Some(Self::Workspace(WorkspaceCommand::ReadFile)), "workspace.listDirectories" => Some(Self::Workspace(WorkspaceCommand::ListDirectories)), "workspace.projectTree.rows" => { Some(Self::Workspace(WorkspaceCommand::ProjectTreeRows)) diff --git a/rust/crates/core/src/runtime/dispatcher/workspace.rs b/rust/crates/core/src/runtime/dispatcher/workspace.rs index 7904985a..43bd8950 100644 --- a/rust/crates/core/src/runtime/dispatcher/workspace.rs +++ b/rust/crates/core/src/runtime/dispatcher/workspace.rs @@ -17,6 +17,27 @@ pub(super) fn dispatch( payload: Value, ) -> CoreResponse { match command { + WorkspaceCommand::FindFiles => { + plugin_response(id, payload, project::workspace_find::find_files_command) + } + WorkspaceCommand::FindText => { + plugin_response(id, payload, project::workspace_find::find_text_command) + } + WorkspaceCommand::WatchPlan => { + plugin_response(id, payload, project::workspace_watch::plan_command) + } + WorkspaceCommand::WatchEvents => { + plugin_response(id, payload, project::workspace_watch::events_command) + } + WorkspaceCommand::ReadDirectory => { + plugin_response(id, payload, project::workspace_read::read_directory_command) + } + WorkspaceCommand::Stat => { + plugin_response(id, payload, project::workspace_read::stat_command) + } + WorkspaceCommand::ReadFile => { + plugin_response(id, payload, project::workspace_read::read_file_command) + } WorkspaceCommand::SearchPresentation => match serde_json::from_value::< project::SearchPresentationRequest, >(payload) diff --git a/rust/crates/core/src/runtime/request_trace.rs b/rust/crates/core/src/runtime/request_trace.rs index d99e5e88..06719610 100644 --- a/rust/crates/core/src/runtime/request_trace.rs +++ b/rust/crates/core/src/runtime/request_trace.rs @@ -195,7 +195,7 @@ pub(crate) fn is_hot(method: &str) -> bool { // File watchers forward one batch per debounce window. || matches!( method, - "workspace.filterChanges" | "lsp.workspaceFilesChanged" | "git.classifyMetadataChanges" + "workspace.watchEvents" | "workspace.filterChanges" | "lsp.workspaceFilesChanged" | "git.classifyMetadataChanges" ) // The status bar sums the instance's memory every few seconds while it is shown, // and active runs probe their process tree's listening ports periodically. diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index 908099fc..7cbdc7f3 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -81,3 +81,6 @@ mod toolchain_queries; mod toolchain_resolution; mod toolchain_vectors; mod vcs; + +mod workspace_find_watch; +mod workspace_read; diff --git a/rust/crates/core/src/tests/workspace_find_watch.rs b/rust/crates/core/src/tests/workspace_find_watch.rs new file mode 100644 index 00000000..47e4f790 --- /dev/null +++ b/rust/crates/core/src/tests/workspace_find_watch.rs @@ -0,0 +1,161 @@ +//! API-07/08 commands against real files and the shared host-boundary fixture. + +use super::support::{temporary_root, Cleanup}; +use crate::execute_json; +use serde_json::{json, Value}; +use std::fs; +use std::path::PathBuf; + +fn fixture() -> Value { + serde_json::from_str(include_str!( + "../../../../fixtures/workspace/find-watch-v1.json" + )) + .unwrap() +} + +fn workspace(label: &str) -> (PathBuf, Cleanup) { + let root = temporary_root(label); + fs::create_dir_all(&root).unwrap(); + for file in fixture()["files"].as_array().unwrap() { + let path = root.join(file["path"].as_str().unwrap()); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, file["text"].as_str().unwrap()).unwrap(); + } + (root.clone(), Cleanup(root)) +} + +fn execute(command: &str, payload: Value) -> Value { + serde_json::from_str(&execute_json( + &json!({"command":command,"payload":payload}).to_string(), + )) + .unwrap() +} + +#[test] +fn workspace_find_pages_match_the_fixture_and_bind_query_options() { + let (root, _cleanup) = workspace("workspace-find"); + let fixture = fixture(); + for (method, key, expected) in [ + ("workspace.findFiles", "fileRequest", "filePaths"), + ("workspace.findText", "textRequest", "textMatches"), + ] { + let mut request = fixture[key].clone(); + request["root"] = json!(root); + let mut actual = Vec::new(); + for _ in 0..5 { + let response = execute(method, request.clone()); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(response["data"]["source"], "disk"); + for item in response["data"]["matches"].as_array().unwrap() { + actual.push(if expected == "filePaths" { + item["path"].clone() + } else { + item.clone() + }); + } + let cursor = &response["data"]["nextCursor"]; + if cursor.is_null() { + break; + } + request["cursor"] = cursor.clone(); + let mut changed = request.clone(); + changed["fileMask"] = json!("*.different"); + assert_eq!(execute(method, changed)["error"]["code"], "invalid_request"); + } + assert_eq!(json!(actual), fixture[expected]); + } + let bad = execute( + "workspace.findText", + json!({"root":root,"pattern":"[","regularExpression":true}), + ); + assert_eq!(bad["error"]["code"], "parse_failed"); +} + +#[test] +fn workspace_find_reports_caps_and_does_not_read_binary_or_oversized_files() { + let (root, _cleanup) = workspace("workspace-find-caps"); + let lines = "alpha\n".repeat(202); + fs::write(root.join("a.txt"), lines).unwrap(); + fs::write(root.join("binary.txt"), b"alpha\0").unwrap(); + fs::write(root.join("large.txt"), vec![b'a'; 2 * 1024 * 1024 + 1]).unwrap(); + let response = execute( + "workspace.findText", + json!({"root":root,"pattern":"alpha","limit":200}), + ); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(response["data"]["matches"].as_array().unwrap().len(), 200); + assert_eq!(response["data"]["isTruncated"], true); + assert!(response["data"]["nextCursor"].is_null()); + let response = execute( + "workspace.findText", + json!({"root":root,"pattern":"BETA","caseSensitive":true,"wholeWords":true}), + ); + assert!(response["data"]["matches"].as_array().unwrap().is_empty()); + assert_eq!(response["data"]["isTruncated"], true); +} + +#[test] +fn workspace_watch_plans_and_events_are_scoped_filtered_and_bounded() { + let (root, _cleanup) = workspace("workspace-watch-events"); + let plan = execute( + "workspace.watchPlan", + json!({"root":root,"path":"src","recursive":true}), + ); + assert_eq!(plan["ok"], true, "{plan}"); + assert_eq!(plan["data"]["isDirectory"], true); + let request = json!({"root":root,"path":"","isDirectory":true,"recursive":true,"paths":fixture()["watch"]["paths"]}); + let response = execute("workspace.watchEvents", request.clone()); + assert_eq!(response["data"], fixture()["watch"]["expected"]); + let response = execute( + "workspace.watchEvents", + json!({"root":root,"path":"src","isDirectory":true,"recursive":false,"paths":["src/b.txt","src/deleted","src/deep/file","a.txt"]}), + ); + assert_eq!( + response["data"]["changedPaths"], + json!(["src/b.txt", "src/deleted"]) + ); + let response = execute( + "workspace.watchEvents", + json!({"root":root,"path":"a.txt","isDirectory":false,"paths":["a.txt","z.md"],"requiresRescan":true}), + ); + assert_eq!(response["data"]["changedPaths"], json!(["a.txt"])); + assert_eq!(response["data"]["requiresRescan"], true); + let mut overflow = request; + overflow["paths"] = json!(vec!["a.txt"; 1001]); + assert_eq!( + execute("workspace.watchEvents", overflow)["data"]["requiresRescan"], + true + ); + assert_eq!( + execute( + "workspace.watchPlan", + json!({"root":root,"path":"../escape"}) + )["error"]["code"], + "invalid_request" + ); +} + +#[cfg(unix)] +#[test] +fn workspace_find_and_watch_never_traverse_a_link() { + let (root, _cleanup) = workspace("workspace-find-links"); + std::os::unix::fs::symlink(root.join("src"), root.join("alias")).unwrap(); + std::os::unix::fs::symlink(root.join("a.txt"), root.join("link.txt")).unwrap(); + assert_eq!( + execute("workspace.watchPlan", json!({"root":root,"path":"alias"}))["error"]["code"], + "permission_denied" + ); + let response = execute( + "workspace.findFiles", + json!({"root":root,"query":".txt","limit":200}), + ); + assert_eq!( + response["data"]["matches"], + json!([{"path":"a.txt"},{"path":"src/b.txt"}]) + ); + let response = execute( + "workspace.watchEvents", + json!({"root":root,"path":"","isDirectory":true,"recursive":true,"paths":["alias/b.txt","link.txt"]}), + ); + assert_eq!(response["data"]["changedPaths"], json!([])); +} diff --git a/rust/crates/core/src/tests/workspace_read.rs b/rust/crates/core/src/tests/workspace_read.rs new file mode 100644 index 00000000..ca5abcb0 --- /dev/null +++ b/rust/crates/core/src/tests/workspace_read.rs @@ -0,0 +1,171 @@ +//! API-06 disk reads through the JSON C ABI, using real isolated files. + +use super::support::{temporary_root, Cleanup}; +use crate::execute_json; +use serde_json::{json, Value}; +use std::fs; +use std::path::PathBuf; + +fn workspace(label: &str) -> (PathBuf, Cleanup) { + let root = temporary_root(label); + fs::create_dir_all(&root).unwrap(); + (root.clone(), Cleanup(root)) +} + +fn execute(command: &str, payload: Value) -> Value { + serde_json::from_str(&execute_json( + &json!({"command":command,"payload":payload}).to_string(), + )) + .unwrap() +} + +fn fixture() -> Value { + serde_json::from_str(include_str!("../../../../fixtures/workspace/read-v1.json")).unwrap() +} + +#[test] +fn workspace_read_directory_pages_are_sorted_filtered_and_scoped() { + let (root, _cleanup) = workspace("workspace-read-pages"); + for name in ["c.txt", "a.txt", "b.txt", "ignored.tmp"] { + fs::write(root.join(name), name).unwrap(); + } + fs::create_dir(root.join(".git")).unwrap(); + let mut request = json!({"root":root,"path":"","limit":2,"hiddenFilePatterns":["*.tmp"]}); + let first = execute("workspace.readDirectory", request.clone()); + assert_eq!(first["ok"], true, "{first}"); + assert_eq!(first["data"]["entries"], fixture()["directoryFirst"]); + let cursor = first["data"]["nextCursor"].as_str().expect("another page"); + request["cursor"] = json!(cursor); + let second = execute("workspace.readDirectory", request.clone()); + assert_eq!(second["data"]["entries"], fixture()["directoryLast"]); + assert_eq!(second["data"]["nextCursor"], Value::Null); + request["hiddenFilePatterns"] = json!([]); + assert_eq!( + execute("workspace.readDirectory", request)["error"]["code"], + "invalid_request" + ); + let explicit = execute( + "workspace.readFile", + json!({"root":root,"path":"ignored.tmp"}), + ); + assert_eq!(explicit["data"]["text"], "ignored.tmp"); + let stat = execute("workspace.stat", json!({"root":root,"path":"a.txt"})); + assert_eq!(stat["data"]["kind"], "file"); + assert_eq!(stat["data"]["size"], 5); + assert!(stat["data"]["modifiedMilliseconds"].is_u64()); + assert_eq!( + execute("workspace.stat", json!({"root":root,"path":""}))["data"]["kind"], + "directory" + ); +} + +#[test] +fn workspace_read_file_preserves_bytes_and_marks_prefix_identity() { + let (root, _cleanup) = workspace("workspace-read-bytes"); + for case in fixture()["files"].as_array().unwrap() { + let bytes = case["bytes"] + .as_array() + .unwrap() + .iter() + .map(|n| n.as_u64().unwrap() as u8) + .collect::>(); + fs::write(root.join("input"), bytes).unwrap(); + let mut request = json!({"root":root,"path":"input"}); + if let Some(maximum) = case.get("maximumBytes") { + request["maximumBytes"] = maximum.clone(); + } + let response = execute("workspace.readFile", request); + assert_eq!(response["ok"], true, "{}: {response}", case["id"]); + for (key, expected) in case["expected"].as_object().unwrap() { + assert_eq!(response["data"][key], *expected, "{}: {key}", case["id"]); + } + assert_eq!( + response["data"]["identity"]["byteCount"], + response["data"]["byteCount"] + ); + assert_eq!( + response["data"]["identity"]["isTruncated"], + response["data"]["isTruncated"] + ); + assert_eq!( + response["data"]["identity"]["sha256"] + .as_str() + .unwrap() + .len(), + 64 + ); + assert_ne!( + response["data"]["text"].is_string(), + response["data"]["base64"].is_string() + ); + } + fs::write(root.join("large"), vec![b'x'; 128 * 1024 + 1]).unwrap(); + let response = execute("workspace.readFile", json!({"root":root,"path":"large"})); + assert_eq!(response["data"]["byteCount"], 128 * 1024); + assert_eq!(response["data"]["isTruncated"], true); +} + +#[test] +fn workspace_read_rejects_invalid_requests_before_reading() { + let (root, _cleanup) = workspace("workspace-read-invalid"); + for case in fixture()["invalid"].as_array().unwrap() { + let mut request = case["request"].clone(); + request["root"] = json!(root); + let response = execute(case["command"].as_str().unwrap(), request); + assert_eq!( + response["error"]["code"], "invalid_request", + "{case}: {response}" + ); + } + assert_eq!( + execute("workspace.stat", json!({"root":root,"path":"missing"}))["error"]["code"], + "entry_not_found" + ); + for command in [ + "workspace.readDirectory", + "workspace.stat", + "workspace.readFile", + ] { + let response: Value = serde_json::from_str(&execute_json(&json!({ + "command":command,"payload":{"root":root,"path":"input"}, + "remoteWorkspace":{"sessionId":"not-connected","localRoot":root,"remoteRoot":"/remote"} + }).to_string())).unwrap(); + assert_eq!(response["error"]["code"], "not_supported", "{response}"); + } +} + +#[cfg(unix)] +#[test] +fn workspace_read_never_follows_leaf_or_ancestor_links() { + use std::os::unix::fs::symlink; + let (root, _cleanup) = workspace("workspace-read-links"); + let (outside, _outside_cleanup) = workspace("workspace-read-outside"); + fs::write(outside.join("secret"), "outside").unwrap(); + symlink(&outside, root.join("alias")).unwrap(); + symlink(outside.join("secret"), root.join("leaf")).unwrap(); + for path in ["leaf", "alias/secret"] { + assert_eq!( + execute("workspace.readFile", json!({"root":root,"path":path}))["error"]["code"], + "permission_denied" + ); + } + assert_eq!( + execute( + "workspace.readDirectory", + json!({"root":root,"path":"alias"}) + )["error"]["code"], + "permission_denied" + ); + assert_eq!( + execute("workspace.stat", json!({"root":root,"path":"alias/secret"}))["error"]["code"], + "permission_denied" + ); + assert_eq!( + execute("workspace.stat", json!({"root":root,"path":"leaf"}))["data"]["kind"], + "symlink" + ); + assert_eq!( + execute("workspace.readDirectory", json!({"root":root,"path":""}))["data"]["entries"], + json!([]) + ); +} diff --git a/rust/crates/platform-tests/tests/platform/main.rs b/rust/crates/platform-tests/tests/platform/main.rs index 9463ff27..c89e78b4 100644 --- a/rust/crates/platform-tests/tests/platform/main.rs +++ b/rust/crates/platform-tests/tests/platform/main.rs @@ -9,5 +9,6 @@ mod git_executable; mod lsp_process; mod permissions; mod process_tree; +mod scoped_read; mod socket; mod support; diff --git a/rust/crates/platform-tests/tests/platform/scoped_read.rs b/rust/crates/platform-tests/tests/platform/scoped_read.rs new file mode 100644 index 00000000..a1612d04 --- /dev/null +++ b/rust/crates/platform-tests/tests/platform/scoped_read.rs @@ -0,0 +1,72 @@ +//! No-follow reads against real OS directory and file handles. + +use crate::support::TempDir; +use lithe_platform::scoped_read::{Directory, Kind}; +use std::ffi::OsStr; +use std::fs; +use std::io::{ErrorKind, Read}; + +#[test] +fn scoped_read_handles_keep_the_opened_directory_when_its_name_changes() { + let root = TempDir::new("lithe scoped read"); + fs::create_dir(root.path().join("child")).unwrap(); + fs::write(root.path().join("child/data"), "original").unwrap(); + let handle = Directory::open_root(root.path()).unwrap(); + let child = handle.directory(OsStr::new("child")).unwrap(); + let renamed = fs::rename(root.path().join("child"), root.path().join("old")); + // Windows denies renames while the ancestor handle excludes delete sharing. + // Unix permits them, and descendant lookups stay relative to the held fd. + if let Err(error) = &renamed { + assert!( + cfg!(windows) && matches!(error.raw_os_error(), Some(5 | 32)), + "unexpected directory rename failure: {error}" + ); + } + if renamed.is_ok() { + fs::create_dir(root.path().join("child")).unwrap(); + fs::write(root.path().join("child/data"), "replacement").unwrap(); + } + let mut text = String::new(); + child + .file(OsStr::new("data")) + .unwrap() + .read_to_string(&mut text) + .unwrap(); + assert_eq!(text, "original"); + assert_eq!( + child.child_metadata(OsStr::new("data")).unwrap().kind, + Kind::File + ); +} + +#[test] +fn scoped_read_refuses_links_and_reports_the_leaf_itself() { + let root = TempDir::new("lithe scoped links"); + fs::create_dir(root.path().join("target")).unwrap(); + fs::write(root.path().join("target/data"), "target").unwrap(); + if let Err(error) = lithe_platform::entries::create_symlink( + std::path::Path::new("target"), + &root.path().join("alias"), + ) { + if cfg!(windows) && error.raw_os_error() == Some(1314) { + return; + } + panic!("create symlink: {error}"); + } + let handle = Directory::open_root(root.path()).unwrap(); + assert_eq!( + handle.child_metadata(OsStr::new("alias")).unwrap().kind, + Kind::Symlink + ); + assert_eq!( + handle.directory(OsStr::new("alias")).err().unwrap().kind(), + ErrorKind::PermissionDenied + ); + assert_eq!( + handle.file(OsStr::new("alias")).err().unwrap().kind(), + ErrorKind::PermissionDenied + ); + for name in ["..", "a/b", "/absolute"] { + assert!(handle.directory(OsStr::new(name)).is_err()); + } +} diff --git a/rust/crates/platform/src/lib.rs b/rust/crates/platform/src/lib.rs index 26f0b256..5500ec1f 100644 --- a/rust/crates/platform/src/lib.rs +++ b/rust/crates/platform/src/lib.rs @@ -17,6 +17,7 @@ pub mod fs; pub mod names; pub mod paths; pub mod process; +pub mod scoped_read; #[cfg(unix)] pub mod socket; diff --git a/rust/crates/platform/src/scoped_read.rs b/rust/crates/platform/src/scoped_read.rs new file mode 100644 index 00000000..93a9aa98 --- /dev/null +++ b/rust/crates/platform/src/scoped_read.rs @@ -0,0 +1,405 @@ +//! Handle-relative reads that never traverse a symbolic link or Windows reparse point. +//! +//! The caller validates relative components. Unix resolves them with openat and +//! O_NOFOLLOW; Windows holds each ancestor without delete sharing while opening +//! the next component. Handles belong to a single request and close on drop. + +use std::ffi::OsStr; +use std::fs::{File, Metadata}; +use std::io::{self, Read}; +use std::path::Path; +use std::time::UNIX_EPOCH; + +/// The entry itself, without following a link. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// A regular file. + File, + /// A directory. + Directory, + /// A symbolic link or other Windows reparse point. + Symlink, + /// A device, socket, pipe or another non-regular entry. + Other, +} + +/// Portable metadata obtained without following the leaf. +#[derive(Clone, Copy, Debug)] +pub struct EntryMetadata { + /// The entry's own type. + pub kind: Kind, + /// The native byte length. + pub size: u64, + /// Milliseconds since the Unix epoch, absent when unavailable or earlier. + pub modified_milliseconds: Option, +} + +fn metadata(value: Metadata) -> EntryMetadata { + let kind = if is_link(&value) { + Kind::Symlink + } else if value.is_dir() { + Kind::Directory + } else if value.is_file() { + Kind::File + } else { + Kind::Other + }; + EntryMetadata { + kind, + size: value.len(), + modified_milliseconds: value + .modified() + .ok() + .and_then(|time| time.duration_since(UNIX_EPOCH).ok()) + .and_then(|time| u64::try_from(time.as_millis()).ok()), + } +} + +fn is_link(value: &Metadata) -> bool { + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + value.file_attributes() + & windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT + != 0 + } + #[cfg(not(windows))] + { + value.file_type().is_symlink() + } +} + +fn link_refused() -> io::Error { + io::Error::new( + io::ErrorKind::PermissionDenied, + "Reading through a symbolic link or reparse point is forbidden", + ) +} + +/// An opened directory anchoring all descendant lookups. +pub struct Directory { + handle: File, + #[cfg(windows)] + path: std::path::PathBuf, + #[cfg(windows)] + ancestors: Vec, +} + +/// An opened regular file, with Windows ancestor replacement prevented until drop. +pub struct ScopedFile { + handle: File, + #[cfg(windows)] + _ancestors: Vec, +} + +impl Read for ScopedFile { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + self.handle.read(bytes) + } +} + +impl Directory { + /// Opens an authorized absolute root. The root alias may be canonicalized; + /// no component supplied by the plugin is canonicalized or followed. + pub fn open_root(root: &Path) -> io::Result { + let root = root.canonicalize()?; + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + let handle = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(root)?; + Ok(Self { handle }) + } + #[cfg(windows)] + { + let mut path = std::path::PathBuf::new(); + let mut ancestors = Vec::new(); + for component in root.components() { + path.push(component); + if matches!(component, std::path::Component::Prefix(_)) { + continue; + } + let handle = windows_open(&path, false)?; + let info = metadata(handle.metadata()?); + if info.kind == Kind::Symlink { + return Err(link_refused()); + } + if info.kind != Kind::Directory { + return Err(io::ErrorKind::NotADirectory.into()); + } + ancestors.push(handle); + } + let handle = ancestors.pop().ok_or(io::ErrorKind::InvalidInput)?; + Ok(Self { + handle, + path, + ancestors, + }) + } + } + + /// Opens a single directory component without following it. + pub fn directory(&self, name: &OsStr) -> io::Result { + validate_component(name)?; + #[cfg(unix)] + { + Ok(Self { + handle: unix_open(&self.handle, name, libc::O_DIRECTORY)?, + }) + } + #[cfg(windows)] + { + let path = self.path.join(name); + let handle = windows_open(&path, false)?; + let info = metadata(handle.metadata()?); + if info.kind == Kind::Symlink { + return Err(link_refused()); + } + if info.kind != Kind::Directory { + return Err(io::ErrorKind::NotADirectory.into()); + } + Ok(Self { + handle, + path, + ancestors: self.retained_handles()?, + }) + } + } + + /// Opens a single regular file without following it or waiting on a FIFO. + pub fn file(&self, name: &OsStr) -> io::Result { + validate_component(name)?; + #[cfg(unix)] + let handle = unix_open(&self.handle, name, libc::O_NONBLOCK)?; + #[cfg(windows)] + let handle = windows_open(&self.path.join(name), true)?; + let info = metadata(handle.metadata()?); + if info.kind == Kind::Symlink { + return Err(link_refused()); + } + if info.kind != Kind::File { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "The entry is not a regular file", + )); + } + Ok(ScopedFile { + handle, + #[cfg(windows)] + _ancestors: self.retained_handles()?, + }) + } + + /// Metadata for this directory's held handle. + pub fn metadata(&self) -> io::Result { + self.handle.metadata().map(metadata) + } + + /// Metadata for one child, including the link itself when it is a link. + pub fn child_metadata(&self, name: &OsStr) -> io::Result { + validate_component(name)?; + #[cfg(unix)] + { + unix_metadata(&self.handle, name) + } + #[cfg(windows)] + { + windows_open(&self.path.join(name), false)? + .metadata() + .map(metadata) + } + } + + /// Visits children using constant enumeration memory. The callback can stop + /// with an error, including the request's cancellation or deadline. + pub fn visit( + &self, + mut visitor: impl FnMut(&OsStr, EntryMetadata) -> io::Result<()>, + ) -> io::Result<()> { + #[cfg(unix)] + { + use std::ffi::CStr; + use std::os::fd::IntoRawFd; + use std::os::unix::ffi::OsStrExt; + let handle = unix_open(&self.handle, OsStr::new("."), libc::O_DIRECTORY)?; + let fd = handle.into_raw_fd(); + // SAFETY: fd is newly owned; fdopendir takes ownership only on success. + let stream = unsafe { libc::fdopendir(fd) }; + if stream.is_null() { + let error = io::Error::last_os_error(); + // SAFETY: fdopendir failed, so fd is still ours. + unsafe { + libc::close(fd); + } + return Err(error); + } + struct Stream(*mut libc::DIR); + impl Drop for Stream { + fn drop(&mut self) { + // SAFETY: the stream is owned by this guard and closed once. + unsafe { + libc::closedir(self.0); + } + } + } + let stream = Stream(stream); + loop { + // SAFETY: errno is thread-local and stream remains live throughout this loop. + unsafe { + *errno() = 0; + } + // SAFETY: readdir's pointer stays valid until the next call on this stream. + let entry = unsafe { libc::readdir(stream.0) }; + if entry.is_null() { + let error = io::Error::last_os_error(); + return if error.raw_os_error() == Some(0) { + Ok(()) + } else { + Err(error) + }; + } + // SAFETY: a successful readdir supplies a NUL-terminated d_name. + let name = OsStr::from_bytes( + unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) }.to_bytes(), + ); + if name == "." || name == ".." { + continue; + } + match unix_metadata(&self.handle, name) { + Ok(info) => visitor(name, info)?, + // A concurrently removed entry contributes no result. + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + } + } + #[cfg(windows)] + { + for entry in std::fs::read_dir(&self.path)? { + let entry = entry?; + visitor(&entry.file_name(), metadata(entry.metadata()?))?; + } + Ok(()) + } + } + + #[cfg(windows)] + fn retained_handles(&self) -> io::Result> { + self.ancestors + .iter() + .chain(std::iter::once(&self.handle)) + .map(File::try_clone) + .collect() + } +} + +fn validate_component(name: &OsStr) -> io::Result<()> { + let mut components = Path::new(name).components(); + if !matches!(components.next(), Some(std::path::Component::Normal(_))) + || components.next().is_some() + { + return Err(io::ErrorKind::InvalidInput.into()); + } + Ok(()) +} + +#[cfg(unix)] +fn unix_open(parent: &File, name: &OsStr, flags: i32) -> io::Result { + use std::os::fd::{AsRawFd, FromRawFd}; + use std::os::unix::ffi::OsStrExt; + let name = std::ffi::CString::new(name.as_bytes()).map_err(|_| io::ErrorKind::InvalidInput)?; + // SAFETY: parent is live, name is NUL-terminated, and no creation flag needs a mode. + let fd = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC | flags, + ) + }; + if fd < 0 { + let error = io::Error::last_os_error(); + // Some hosts report ENOTDIR for O_DIRECTORY|O_NOFOLLOW on a link. + if error.raw_os_error() == Some(libc::ELOOP) + || (error.kind() == io::ErrorKind::NotADirectory + && unix_metadata(parent, OsStr::from_bytes(name.as_bytes()))?.kind == Kind::Symlink) + { + return Err(link_refused()); + } + return Err(error); + } + // SAFETY: openat returned a fresh descriptor transferred exactly once. + Ok(unsafe { File::from_raw_fd(fd) }) +} + +#[cfg(unix)] +fn unix_metadata(parent: &File, name: &OsStr) -> io::Result { + use std::os::fd::AsRawFd; + use std::os::unix::ffi::OsStrExt; + let name = std::ffi::CString::new(name.as_bytes()).map_err(|_| io::ErrorKind::InvalidInput)?; + let mut info = std::mem::MaybeUninit::::uninit(); + // SAFETY: fstatat writes info on success; the parent and C string remain live. + if unsafe { + libc::fstatat( + parent.as_raw_fd(), + name.as_ptr(), + info.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + } != 0 + { + return Err(io::Error::last_os_error()); + } + // SAFETY: fstatat succeeded and initialized every field. + let info = unsafe { info.assume_init() }; + let kind = match info.st_mode & libc::S_IFMT { + libc::S_IFREG => Kind::File, + libc::S_IFDIR => Kind::Directory, + libc::S_IFLNK => Kind::Symlink, + _ => Kind::Other, + }; + Ok(EntryMetadata { + kind, + size: u64::try_from(info.st_size).unwrap_or(0), + modified_milliseconds: u64::try_from(info.st_mtime) + .ok() + .and_then(|seconds| seconds.checked_mul(1000)) + .and_then(|ms| ms.checked_add((info.st_mtime_nsec / 1_000_000) as u64)), + }) +} + +#[cfg(target_os = "macos")] +unsafe fn errno() -> *mut i32 { + // SAFETY: the OS returns the current thread's errno storage. + unsafe { libc::__error() } +} + +#[cfg(all(unix, not(target_os = "macos")))] +unsafe fn errno() -> *mut i32 { + // SAFETY: the OS returns the current thread's errno storage. + unsafe { libc::__errno_location() } +} + +#[cfg(windows)] +fn windows_open(path: &Path, read: bool) -> io::Result { + use std::os::windows::fs::OpenOptionsExt; + use windows_sys::Win32::Storage::FileSystem::{ + FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, + FILE_SHARE_READ, FILE_SHARE_WRITE, + }; + let mut options = std::fs::OpenOptions::new(); + if read { + options.read(true); + } else { + options.access_mode(FILE_READ_ATTRIBUTES); + } + options + .share_mode(if read { + FILE_SHARE_READ | FILE_SHARE_WRITE + } else { + FILE_SHARE_READ + }) + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT) + .open(path) +} diff --git a/rust/crates/plugin-rpc/src/host_params.rs b/rust/crates/plugin-rpc/src/host_params.rs index 680cfd34..36b2803e 100644 --- a/rust/crates/plugin-rpc/src/host_params.rs +++ b/rust/crates/plugin-rpc/src/host_params.rs @@ -72,7 +72,24 @@ pub(crate) fn check_host_params( HostParams::DocumentClose => &["context", "documentID"], HostParams::WorkspaceCreate => &["context", "resource", "kind", "text", "linkTarget"], HostParams::WorkspaceMove => &["context", "resource", "target"], - HostParams::WorkspaceTrash => &["context", "resource"], + HostParams::WorkspaceTrash | HostParams::WorkspaceStat => &["context", "resource"], + HostParams::WorkspaceReadDirectory => &["context", "resource", "cursor", "limit"], + HostParams::WorkspaceReadFile => &["context", "resource", "maximumBytes"], + HostParams::WorkspaceWatch => &["context", "resource", "recursive"], + HostParams::WorkspaceFindFiles => &[ + "context", "resource", "query", "fileMask", "cursor", "limit", + ], + HostParams::WorkspaceFindText => &[ + "context", + "resource", + "pattern", + "fileMask", + "caseSensitive", + "wholeWords", + "regularExpression", + "cursor", + "limit", + ], HostParams::Object => { return match params.get("context") { Some(context) if !is_context_reference(context) => { @@ -261,6 +278,12 @@ pub(crate) fn check_host_params( | HostParams::WorkspaceCreate | HostParams::WorkspaceMove | HostParams::WorkspaceTrash => check_file_change_params(rule, params, &invalid)?, + HostParams::WorkspaceReadDirectory + | HostParams::WorkspaceStat + | HostParams::WorkspaceReadFile + | HostParams::WorkspaceWatch + | HostParams::WorkspaceFindFiles + | HostParams::WorkspaceFindText => check_workspace_read_params(rule, params, &invalid)?, HostParams::Empty | HostParams::Object => {} } Ok(()) @@ -617,3 +640,110 @@ pub fn attach_caller(invoke_params: &mut Value, caller: Option<&str>) { params.insert("caller".to_string(), json!({ "pluginID": caller })); } } + +/// Checks the read surface before forwarding it to a context-owning host. +fn check_workspace_read_params( + rule: HostParams, + params: &serde_json::Map, + invalid: &dyn Fn(&'static str) -> HostRequestRefusal, +) -> Result<(), HostRequestRefusal> { + if !params.get("context").is_some_and(is_context_reference) { + return Err(invalid(CONTEXT_REFERENCE_MESSAGE)); + } + let resource = params + .get("resource") + .and_then(Value::as_object) + .ok_or_else(|| invalid(RESOURCE_MESSAGE))?; + if let Some(option) = resource + .keys() + .find(|key| !["rootID", "path"].contains(&key.as_str())) + { + return Err(HostRequestRefusal { + rpc_code: host_rpc_code(codes::HOST_UNSUPPORTED_OPTION), + code: codes::HOST_UNSUPPORTED_OPTION, + message: "Resource names an option this host does not support.", + details: Some(json!({"option": format!("resource.{option}")})), + }); + } + let valid = resource + .get("rootID") + .and_then(Value::as_str) + .is_some_and(is_credential_key) + && resource + .get("path") + .and_then(Value::as_str) + .is_some_and(|path| { + path.len() <= MAX_FILE_CHANGE_PATH_BYTES + && !path.contains('\\') + && (path.is_empty() && rule != HostParams::WorkspaceReadFile + || !lithe_platform::paths::invalid_entry_path( + path, + lithe_platform::Platform::HOST, + )) + }); + if !valid { + return Err(invalid(RESOURCE_MESSAGE)); + } + if params.get("cursor").is_some_and(|value| { + !value + .as_str() + .is_some_and(|text| !text.is_empty() && text.len() <= 8192) + }) { + return Err(invalid( + "cursor must be a nonempty string of at most 8192 bytes.", + )); + } + let search = matches!( + rule, + HostParams::WorkspaceFindFiles | HostParams::WorkspaceFindText + ); + if search { + if resource.get("path").and_then(Value::as_str) != Some("") { + return Err(invalid("A search resource must name the workspace root.")); + } + let key = if rule == HostParams::WorkspaceFindFiles { + "query" + } else { + "pattern" + }; + if !params + .get(key) + .and_then(Value::as_str) + .is_some_and(|value| !value.is_empty() && value.len() <= 4096) + { + return Err(invalid("The search query must contain 1-4096 UTF-8 bytes.")); + } + if params + .get("fileMask") + .is_some_and(|value| !value.as_str().is_some_and(|value| value.len() <= 4096)) + { + return Err(invalid( + "fileMask must be a string of at most 4096 UTF-8 bytes.", + )); + } + } + for key in [ + "recursive", + "caseSensitive", + "wholeWords", + "regularExpression", + ] { + if params.get(key).is_some_and(|value| !value.is_boolean()) { + return Err(invalid("Search and watch flags must be booleans.")); + } + } + for (key, maximum) in [ + ("limit", if search { 200 } else { 1000 }), + ("maximumBytes", 128 * 1024), + ] { + if params + .get(key) + .is_some_and(|value| !value.as_u64().is_some_and(|n| (1..=maximum).contains(&n))) + { + return Err(invalid( + "limit is outside the supported page size or maximumBytes is outside 1-131072.", + )); + } + } + Ok(()) +} diff --git a/rust/crates/plugin-rpc/src/host_requests.rs b/rust/crates/plugin-rpc/src/host_requests.rs index bc35c34a..ea9b77ac 100644 --- a/rust/crates/plugin-rpc/src/host_requests.rs +++ b/rust/crates/plugin-rpc/src/host_requests.rs @@ -77,6 +77,18 @@ pub(crate) enum HostParams { WorkspaceMove, /// `{ context, resource }`: a move to the system trash (plan API-11). WorkspaceTrash, + /// `{ context, resource, cursor?, limit? }` (plan API-06). + WorkspaceReadDirectory, + /// `{ context, resource }`, including the root (plan API-06). + WorkspaceStat, + /// `{ context, resource, maximumBytes? }` (plan API-06). + WorkspaceReadFile, + /// `{ context, resource, recursive? }` (plan API-07). + WorkspaceWatch, + /// `{ context, resource, query, fileMask?, cursor?, limit? }` (plan API-08). + WorkspaceFindFiles, + /// A bounded text search at the workspace root (plan API-08). + WorkspaceFindText, /// 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, @@ -248,37 +260,37 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ method: "lithe/host/workspace/readDirectory", service: "workspace", permission: Some("workspace.files.read"), - params: HostParams::Object, + params: HostParams::WorkspaceReadDirectory, }, HostMethod { method: "lithe/host/workspace/stat", service: "workspace", permission: Some("workspace.files.read"), - params: HostParams::Object, + params: HostParams::WorkspaceStat, }, HostMethod { method: "lithe/host/workspace/readFile", service: "workspace", permission: Some("workspace.files.read"), - params: HostParams::Object, + params: HostParams::WorkspaceReadFile, }, HostMethod { method: "lithe/host/workspace/watch", service: "workspace", permission: Some("workspace.files.watch"), - params: HostParams::Object, + params: HostParams::WorkspaceWatch, }, HostMethod { method: "lithe/host/workspace/findFiles", service: "workspace", permission: Some("workspace.search"), - params: HostParams::Object, + params: HostParams::WorkspaceFindFiles, }, HostMethod { method: "lithe/host/workspace/findText", service: "workspace", permission: Some("workspace.search"), - params: HostParams::Object, + params: HostParams::WorkspaceFindText, }, // Plan API-11: file changes the host makes on the backend's behalf. The // host never overwrites a file, saves an open document before it moves @@ -641,3 +653,127 @@ mod build_configuration_tests { ); } } + +#[cfg(test)] +mod workspace_read_tests { + use super::*; + + #[test] + fn workspace_read_methods_check_options_context_resources_and_bounds() { + let context = json!({"contextID":"context-1","generation":1}); + for (method, extra) in [ + ( + "lithe/host/workspace/readDirectory", + json!({"cursor":"opaque","limit":1000}), + ), + ("lithe/host/workspace/stat", json!({})), + ("lithe/host/workspace/watch", json!({"recursive":true})), + ( + "lithe/host/workspace/findFiles", + json!({"query":"alpha","limit":200}), + ), + ( + "lithe/host/workspace/findText", + json!({"pattern":"alpha","wholeWords":true}), + ), + ( + "lithe/host/workspace/readFile", + json!({"maximumBytes":131072}), + ), + ] { + let granted = [method.to_owned()].into_iter().collect(); + let mut params = + json!({"context":context,"resource":{"rootID":"root-1","path":"src/a"}}); + if method.ends_with("findFiles") || method.ends_with("findText") { + params["resource"]["path"] = json!(""); + } + for (key, value) in extra.as_object().unwrap() { + params[key] = value.clone(); + } + assert_eq!( + host_request(method, Some(¶ms), Some(0), &granted).unwrap(), + HostRoute::Forward("workspace") + ); + let mut unknown = params.clone(); + unknown["unknown"] = json!(true); + assert_eq!( + host_request(method, Some(&unknown), Some(0), &granted) + .unwrap_err() + .code, + codes::HOST_UNSUPPORTED_OPTION + ); + let mut unknown = params.clone(); + unknown["resource"]["unknown"] = json!(true); + assert_eq!( + host_request(method, Some(&unknown), Some(0), &granted) + .unwrap_err() + .code, + codes::HOST_UNSUPPORTED_OPTION + ); + for resource in [ + json!({"rootID":"other","path":"../escape"}), + json!({"rootID":"","path":"a"}), + json!({"rootID":"root-1","path":"a\\b"}), + ] { + let mut invalid = params.clone(); + invalid["resource"] = resource; + assert_eq!( + host_request(method, Some(&invalid), Some(0), &granted) + .unwrap_err() + .code, + codes::HOST_INVALID_PARAMS + ); + } + let mut invalid = params.clone(); + invalid["context"] = Value::Null; + assert_eq!( + host_request(method, Some(&invalid), Some(0), &granted) + .unwrap_err() + .code, + codes::HOST_INVALID_PARAMS + ); + } + for (method, key, value) in [ + ("lithe/host/workspace/readDirectory", "limit", json!(0)), + ("lithe/host/workspace/readDirectory", "limit", json!(1001)), + ("lithe/host/workspace/readDirectory", "cursor", json!(null)), + ( + "lithe/host/workspace/readFile", + "maximumBytes", + json!(131073), + ), + ("lithe/host/workspace/watch", "recursive", json!("true")), + ("lithe/host/workspace/findFiles", "limit", json!(201)), + ("lithe/host/workspace/findText", "wholeWords", json!(1)), + ("lithe/host/workspace/findText", "pattern", json!("")), + ( + "lithe/host/workspace/findFiles", + "resource", + json!({"rootID":"r1","path":"sub"}), + ), + ] { + let mut params = json!({"context":context,"resource":{"rootID":"root-1","path":"a"}}); + if method.ends_with("findFiles") || method.ends_with("findText") { + params["resource"]["path"] = json!(""); + params[if method.ends_with("findFiles") { + "query" + } else { + "pattern" + }] = json!("alpha"); + } + params[key] = value; + assert_eq!( + host_request( + method, + Some(¶ms), + Some(0), + &[method.to_owned()].into_iter().collect() + ) + .unwrap_err() + .code, + codes::HOST_INVALID_PARAMS, + "{method}: {params}" + ); + } + } +} diff --git a/rust/crates/project/src/lib.rs b/rust/crates/project/src/lib.rs index 256fad0f..a100d6c4 100644 --- a/rust/crates/project/src/lib.rs +++ b/rust/crates/project/src/lib.rs @@ -29,6 +29,9 @@ mod search_languages; mod search_paging; mod search_preferences; mod search_presentation; +pub mod workspace_find; +pub mod workspace_read; +pub mod workspace_watch; pub use document_lifecycle::*; pub use files::*; diff --git a/rust/crates/project/src/workspace_find.rs b/rust/crates/project/src/workspace_find.rs new file mode 100644 index 00000000..0c5c8ae3 --- /dev/null +++ b/rust/crates/project/src/workspace_find.rs @@ -0,0 +1,329 @@ +//! Bounded plugin disk searches, reusing workspace matching without retaining an index. +//! +//! Only the best page plus a sentinel is retained. Traversal and text reads use +//! held no-follow handles; a continuation binds the query and visibility generation. + +use crate::files::{ + file_mask_allows, parse_file_mask, searchable_bytes_text, Matcher, VisibilityRules, +}; +use crate::workspace_read::{check, decode, failure, invalid, root, validate_path}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use lithe_platform::scoped_read::{Directory, Kind}; +use lithe_protocol::CoreError; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::ffi::OsStr; +use std::io::Read; +use std::path::Path; +use std::time::{Duration, Instant}; + +const MAX_RESULTS: usize = 200; +const MAX_TEXT_BYTES: usize = 2 * 1024 * 1024; +const MAX_DEPTH: usize = 128; + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FindRequest { + root: String, + #[serde(default)] + query: Option, + #[serde(default)] + pattern: Option, + #[serde(default)] + file_mask: String, + #[serde(default)] + case_sensitive: bool, + #[serde(default)] + whole_words: bool, + #[serde(default)] + regular_expression: bool, + cursor: Option, + limit: Option, + #[serde(default)] + hidden_directory_names: Vec, + #[serde(default)] + hidden_file_patterns: Vec, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Cursor { + scope: String, + after: (String, usize), + returned: usize, +} + +/// Executes API-08 file-name searches with a root/query-bound continuation. +pub fn find_files_command(payload: Value) -> Result { + find(decode(payload)?, false) +} + +/// Executes API-08 line searches against disk, never an unsaved editor buffer. +pub fn find_text_command(payload: Value) -> Result { + find(decode(payload)?, true) +} + +struct Search { + matcher: Matcher, + masks: Vec, + rules: VisibilityRules, + policy: Option>, + after: (String, usize), + cap: usize, + candidates: BTreeMap<(String, usize), Value>, + text: bool, + incomplete: bool, + deadline: Instant, +} + +impl Search { + fn push(&mut self, path: &str, line: usize, value: Value) { + let key = (path.to_string(), line); + if key <= self.after { + return; + } + self.candidates.insert(key, value); + if self.candidates.len() > self.cap + 1 { + self.candidates.pop_last(); + } + } + + fn walk(&mut self, directory: Directory, prefix: &str, depth: usize) -> Result<(), CoreError> { + check(self.deadline)?; + if depth > MAX_DEPTH { + self.incomplete = true; + return Ok(()); + } + let mut refused = None; + let result = directory.visit(|name, info| { + match self.entry(&directory, name, info.kind, info.size, prefix, depth) { + Ok(()) => Ok(()), + Err(error) => { + refused = Some(error); + Err(std::io::Error::other("Workspace search stopped")) + } + } + }); + if let Some(error) = refused { + Err(error) + } else { + result.map_err(failure) + } + } + + fn entry( + &mut self, + directory: &Directory, + name: &OsStr, + kind: Kind, + size: u64, + prefix: &str, + depth: usize, + ) -> Result<(), CoreError> { + check(self.deadline)?; + let Some(name_text) = name.to_str() else { + return Ok(()); + }; + let path = if prefix.is_empty() { + name_text.to_string() + } else { + format!("{prefix}/{name_text}") + }; + if !matches!(kind, Kind::Directory | Kind::File) + || validate_path(&path).is_err() + || self.rules.is_hidden(&path, kind == Kind::Directory) + { + return Ok(()); + } + if let Some(policy) = &self.policy { + if policy + .search_reason(&path, kind == Kind::Directory, false)? + .is_some() + { + return Ok(()); + } + } + if kind == Kind::Directory { + return match directory.directory(name) { + Ok(child) => self.walk(child, &path, depth + 1), + // A concurrently removed entry contributes no result. + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(failure(error)), + }; + } + if !file_mask_allows(&self.masks, &path) { + return Ok(()); + } + if !self.text { + if self.matcher.matches(&path) { + self.push(&path, 0, json!({"path":path})); + } + return Ok(()); + } + if size > MAX_TEXT_BYTES as u64 { + self.incomplete = true; + return Ok(()); + } + let mut file = match directory.file(name) { + Ok(file) => file.take((MAX_TEXT_BYTES + 1) as u64), + // A concurrently removed entry contributes no result. + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(failure(error)), + }; + let mut bytes = Vec::new(); + let mut chunk = [0u8; 8192]; + loop { + check(self.deadline)?; + let count = file.read(&mut chunk).map_err(failure)?; + if count == 0 { + break; + } + bytes.extend_from_slice(&chunk[..count]); + } + if bytes.len() > MAX_TEXT_BYTES { + self.incomplete = true; + return Ok(()); + } + let Some(text) = searchable_bytes_text(bytes) else { + return Ok(()); + }; + for (index, line) in text.split('\n').enumerate() { + check(self.deadline)?; + let line = line.strip_suffix('\r').unwrap_or(line); + if self.matcher.matches(line) { + let preview: String = line.trim().chars().take(500).collect(); + self.push( + &path, + index + 1, + json!({"path":path,"line":index+1,"preview":preview,"range":null}), + ); + } + } + Ok(()) + } +} + +fn find(mut request: FindRequest, text: bool) -> Result { + let query = if text { + request.pattern.as_deref() + } else { + request.query.as_deref() + } + .ok_or_else(|| invalid("The search query is required"))?; + if query.is_empty() + || query.len() > 4096 + || request.file_mask.len() > 4096 + || (text && request.query.is_some()) + || (!text + && (request.pattern.is_some() + || request.case_sensitive + || request.whole_words + || request.regular_expression)) + { + return Err(invalid("Invalid search query or options")); + } + let limit = request.limit.unwrap_or(100); + if !(1..=MAX_RESULTS).contains(&limit) { + return Err(invalid("Search limit must be 1-200")); + } + let directory = root(&request.root)?; + let canonical = Path::new(&request.root).canonicalize().map_err(failure)?; + let policy = crate::indexing::context(&canonical); + let rules = VisibilityRules::new( + request.hidden_directory_names.clone(), + request.hidden_file_patterns.clone(), + ); + let cursor = request.cursor.take(); + // Page size may change between requests, but query, root and effective policy may not. + request.limit = None; + let scope = crate::encoding::bytes_identity( + &serde_json::to_vec(&json!([ + text, + request, + canonical, + rules.hidden_directories, + rules.hidden_file_patterns, + policy.as_ref().map(|policy| policy.revision) + ])) + .expect("search scope encodes"), + ); + let cursor: Option = cursor + .map(|value| { + if value.len() > 8192 { + return Err(invalid("Invalid search cursor")); + } + URL_SAFE_NO_PAD + .decode(value) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .ok_or_else(|| invalid("Invalid search cursor")) + }) + .transpose()?; + if cursor.as_ref().is_some_and(|cursor| { + cursor.scope != scope + || cursor.returned == 0 + || cursor.returned >= MAX_RESULTS + || cursor.after.0.is_empty() + || validate_path(&cursor.after.0).is_err() + }) { + return Err(invalid("Search cursor does not belong to this request")); + } + let returned = cursor.as_ref().map_or(0, |cursor| cursor.returned); + let mut search = Search { + matcher: Matcher::new( + query, + request.case_sensitive, + request.whole_words, + request.regular_expression, + )?, + masks: parse_file_mask(&request.file_mask), + rules, + policy, + after: cursor.map_or((String::new(), 0), |cursor| cursor.after), + cap: limit.min(MAX_RESULTS - returned), + candidates: BTreeMap::new(), + text, + incomplete: false, + deadline: Instant::now() + Duration::from_secs(30), + }; + search.walk(directory, "", 0)?; + if let Some(policy) = &search.policy { + policy.check()? + } + let mut more = search.candidates.len() > search.cap; + let mut matches = Vec::new(); + let mut last = None; + let mut page_bytes = 0; + for (key, value) in search.candidates.into_iter().take(search.cap) { + let bytes = serde_json::to_vec(&value) + .expect("search result encodes") + .len() + + 256; + if page_bytes + bytes > 900 * 1024 { + more = true; + break; + } + page_bytes += bytes; + last = Some(key); + matches.push(value); + } + let total = returned + matches.len(); + let next = if more && total < MAX_RESULTS { + Some( + URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&Cursor { + scope, + after: last.expect("a search page has a result"), + returned: total, + }) + .expect("search cursor encodes"), + ), + ) + } else { + None + }; + Ok( + json!({"matches":matches,"nextCursor":next,"isTruncated":search.incomplete || (more && total >= MAX_RESULTS),"source":"disk"}), + ) +} diff --git a/rust/crates/project/src/workspace_read.rs b/rust/crates/project/src/workspace_read.rs new file mode 100644 index 00000000..e58315ae --- /dev/null +++ b/rust/crates/project/src/workspace_read.rs @@ -0,0 +1,326 @@ +//! Bounded disk reads for the plugin workspace file surface (plan API-06). +//! +//! Paths and limits are shared policy; only the no-follow handle operations +//! belong to lithe-platform. Explicit reads ignore visibility filters, and no +//! command consults an editor buffer. Directory cursors retain no server state. + +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use lithe_platform::scoped_read::{Directory, EntryMetadata, Kind}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::ffi::OsStr; +use std::io::{self, Read}; +use std::path::Path; +use std::time::{Duration, Instant}; + +const MAX_FILE_BYTES: usize = 128 * 1024; +const MAX_PATH_BYTES: usize = 4096; +const PAGE_BYTES: usize = 900 * 1024; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ResourceRequest { + root: String, + path: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DirectoryRequest { + root: String, + path: String, + cursor: Option, + limit: Option, + #[serde(default)] + hidden_directory_names: Vec, + #[serde(default)] + hidden_file_patterns: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FileRequest { + root: String, + path: String, + maximum_bytes: Option, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Cursor { + scope: String, + after: String, +} + +/// Builds the shared invalid-request refusal for workspace disk methods. +pub(crate) fn invalid(message: &str) -> CoreError { + CoreError::new(ErrorCode::InvalidRequest, message) +} + +/// Decodes strict command payloads without admitting unknown options. +pub(crate) fn decode Deserialize<'de>>(payload: Value) -> Result { + serde_json::from_value(payload) + .map_err(|error| invalid("Invalid workspace read request").with_details(error.to_string())) +} + +/// Maps native I/O categories to stable Core workspace failures. +pub(crate) fn failure(error: io::Error) -> CoreError { + let code = match error.kind() { + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory => ErrorCode::EntryNotFound, + io::ErrorKind::PermissionDenied => ErrorCode::PermissionDenied, + io::ErrorKind::InvalidInput => ErrorCode::InvalidRequest, + io::ErrorKind::TimedOut => ErrorCode::TimedOut, + io::ErrorKind::Interrupted => ErrorCode::Cancelled, + _ => ErrorCode::Unknown, + }; + CoreError::new(code, "Could not read the workspace entry").with_details(error.to_string()) +} + +/// Checks cooperative cancellation and the bounded disk-operation deadline. +pub(crate) fn check(deadline: Instant) -> Result<(), CoreError> { + lithe_protocol::cancellation::check()?; + if Instant::now() >= deadline { + return Err(CoreError::new( + ErrorCode::TimedOut, + "Workspace read deadline expired", + )); + } + Ok(()) +} + +/// Requires one portable, normalized resource path under the authorized root. +pub(crate) fn validate_path(path: &str) -> Result<(), CoreError> { + if path.len() > MAX_PATH_BYTES + || path.contains('\\') + || (!path.is_empty() + && lithe_platform::paths::invalid_entry_path(path, lithe_platform::Platform::HOST)) + { + return Err(invalid( + "Path must use '/' and name an entry below its root", + )); + } + Ok(()) +} + +/// Opens an absolute authorized root that anchors no-follow descendant reads. +pub(crate) fn root(value: &str) -> Result { + if !Path::new(value).is_absolute() { + return Err(invalid("Workspace root must be absolute")); + } + Directory::open_root(Path::new(value)).map_err(|error| { + if error.kind() == io::ErrorKind::NotFound { + CoreError::new(ErrorCode::WorkspaceNotFound, "Workspace does not exist") + } else { + failure(error) + } + }) +} + +/// Walks validated directory components through held no-follow handles. +pub(crate) fn directory(mut root: Directory, path: &str) -> Result { + for component in path.split('/').filter(|part| !part.is_empty()) { + lithe_protocol::cancellation::check()?; + root = root.directory(OsStr::new(component)).map_err(failure)?; + } + Ok(root) +} + +/// Opens the parent of a validated resource without following plugin links. +pub(crate) fn parent(root: Directory, path: &str) -> Result<(Directory, &str), CoreError> { + let (parents, name) = path.rsplit_once('/').unwrap_or(("", path)); + Ok((directory(root, parents)?, name)) +} + +fn kind(value: Kind) -> &'static str { + match value { + Kind::File => "file", + Kind::Directory => "directory", + Kind::Symlink => "symlink", + Kind::Other => "other", + } +} + +/// Reads a live directory page, ordered by UTF-8 name bytes, omitting links and +/// hidden entries. A cursor binds the root, directory and effective filters. +pub fn read_directory_command(payload: Value) -> Result { + let request: DirectoryRequest = decode(payload)?; + validate_path(&request.path)?; + let limit = request.limit.unwrap_or(200); + if !(1..=1000).contains(&limit) { + return Err(invalid("Directory limit must be 1-1000")); + } + let deadline = Instant::now() + Duration::from_secs(30); + check(deadline)?; + let root_handle = root(&request.root)?; + let root_path = Path::new(&request.root).canonicalize().map_err(failure)?; + let rules = crate::files::VisibilityRules::new( + request.hidden_directory_names, + request.hidden_file_patterns, + ); + let scope = crate::encoding::bytes_identity( + &serde_json::to_vec(&json!([ + root_path, + request.path, + rules.hidden_directories, + rules.hidden_file_patterns + ])) + .expect("cursor scope encodes"), + ); + let after = match request.cursor { + None => String::new(), + Some(cursor) => { + if cursor.len() > 8192 { + return Err(invalid("Invalid directory cursor")); + } + let cursor: Cursor = URL_SAFE_NO_PAD + .decode(cursor) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .ok_or_else(|| invalid("Invalid directory cursor"))?; + if cursor.scope != scope + || cursor.after.is_empty() + || cursor.after.contains('/') + || cursor.after.contains('\\') + { + return Err(invalid("Directory cursor does not belong to this request")); + } + cursor.after + } + }; + let directory = directory(root_handle, &request.path)?; + let mut candidates = BTreeMap::new(); + directory + .visit(|name, info| { + check(deadline).map_err(|error| { + io::Error::new( + match error.code { + ErrorCode::Cancelled => io::ErrorKind::Interrupted, + _ => io::ErrorKind::TimedOut, + }, + error.message, + ) + })?; + let Some(name) = name.to_str() else { + return Ok(()); + }; + let path = if request.path.is_empty() { + name.to_string() + } else { + format!("{}/{name}", request.path) + }; + if name <= after.as_str() + || info.kind == Kind::Symlink + || validate_path(&path).is_err() + || rules.is_hidden(&path, info.kind == Kind::Directory) + { + return Ok(()); + } + candidates.insert( + name.to_string(), + json!({"name":name,"path":path,"kind":kind(info.kind)}), + ); + if candidates.len() > limit + 1 { + candidates.pop_last(); + } + Ok(()) + }) + .map_err(failure)?; + let mut entries = Vec::with_capacity(limit); + let mut bytes = 0; + let mut last = None; + let mut has_more = false; + for (name, entry) in candidates { + // Reserve each resource's root ID and JSON envelope added by the host. + let size = serde_json::to_vec(&entry).expect("entry encodes").len() + 256; + if entries.len() == limit || bytes + size > PAGE_BYTES { + has_more = true; + break; + } + bytes += size; + last = Some(name); + entries.push(entry); + } + let cursor = if has_more { + Some( + URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&Cursor { + scope, + after: last.expect("one legal entry fits in the page budget"), + }) + .expect("cursor encodes"), + ), + ) + } else { + None + }; + check(deadline)?; + Ok(json!({"entries":entries,"nextCursor":cursor})) +} + +/// Stats the leaf itself, allowing a link only as the final component. +pub fn stat_command(payload: Value) -> Result { + let request: ResourceRequest = decode(payload)?; + validate_path(&request.path)?; + lithe_protocol::cancellation::check()?; + let root = root(&request.root)?; + let info: EntryMetadata = if request.path.is_empty() { + root.metadata().map_err(failure)? + } else { + let (parent, name) = parent(root, &request.path)?; + parent.child_metadata(OsStr::new(name)).map_err(failure)? + }; + Ok( + json!({"path":request.path,"kind":kind(info.kind),"size":info.size,"modifiedMilliseconds":info.modified_milliseconds}), + ) +} + +/// Returns at most 128 KiB of disk bytes. Strict UTF-8 without binary controls +/// is text; every other prefix is base64, including an incomplete UTF-8 tail. +pub fn read_file_command(payload: Value) -> Result { + let request: FileRequest = decode(payload)?; + validate_path(&request.path)?; + if request.path.is_empty() { + return Err(invalid("A file path cannot name the root")); + } + let maximum = request.maximum_bytes.unwrap_or(MAX_FILE_BYTES); + if !(1..=MAX_FILE_BYTES).contains(&maximum) { + return Err(invalid("maximumBytes must be 1-131072")); + } + let deadline = Instant::now() + Duration::from_secs(30); + check(deadline)?; + let (parent, name) = parent(root(&request.root)?, &request.path)?; + let mut file = parent + .file(OsStr::new(name)) + .map_err(failure)? + .take((maximum + 1) as u64); + let mut bytes = Vec::with_capacity(maximum + 1); + let mut buffer = [0u8; 8192]; + loop { + check(deadline)?; + let count = file.read(&mut buffer).map_err(failure)?; + if count == 0 { + break; + } + bytes.extend_from_slice(&buffer[..count]); + } + let truncated = bytes.len() > maximum; + bytes.truncate(maximum); + let mut result = json!({"path":request.path,"source":"disk","byteCount":bytes.len(),"isTruncated":truncated, + "identity":{"sha256":crate::encoding::bytes_identity(&bytes),"byteCount":bytes.len(),"isTruncated":truncated}}); + match std::str::from_utf8(&bytes).ok().filter(|text| { + !text + .chars() + .any(|ch| ch.is_control() && !matches!(ch, '\t' | '\r' | '\n')) + }) { + Some(text) => { + result["text"] = json!(text); + result["encoding"] = json!("utf-8"); + } + None => { + result["base64"] = json!(base64::engine::general_purpose::STANDARD.encode(&bytes)); + } + } + Ok(result) +} diff --git a/rust/crates/project/src/workspace_watch.rs b/rust/crates/project/src/workspace_watch.rs new file mode 100644 index 00000000..ca93eb63 --- /dev/null +++ b/rust/crates/project/src/workspace_watch.rs @@ -0,0 +1,157 @@ +//! Plugin workspace watch plans and bounded event projection (API-07). +//! +//! The desktop owns native registrations. Core owns path containment, visibility, +//! scope and loss semantics; no watcher state or filesystem contents are retained. + +use crate::files::VisibilityRules; +use crate::workspace_read::{check, decode, failure, parent, root, validate_path}; +use lithe_platform::scoped_read::Kind; +use lithe_protocol::CoreError; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::BTreeSet; +use std::ffi::OsStr; +use std::path::Path; +use std::time::{Duration, Instant}; + +const EVENT_LIMIT: usize = 1000; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PlanRequest { + root: String, + path: String, + #[serde(default)] + recursive: bool, +} + +/// Validates a watch target through no-follow handles before native registration. +/// The native stream covers the root so ancestor moves also invalidate a target. +pub fn plan_command(payload: Value) -> Result { + let request: PlanRequest = decode(payload)?; + validate_path(&request.path)?; + lithe_protocol::cancellation::check()?; + let handle = root(&request.root)?; + let info = if request.path.is_empty() { + handle.metadata().map_err(failure)? + } else { + let (parent, name) = parent(handle, &request.path)?; + parent.child_metadata(OsStr::new(name)).map_err(failure)? + }; + if !matches!(info.kind, Kind::File | Kind::Directory) { + return Err(failure(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "A watch target must not be a link or special entry", + ))); + } + Ok( + json!({"root":Path::new(&request.root).canonicalize().map_err(failure)?, + "path":request.path,"isDirectory":info.kind==Kind::Directory,"recursive":request.recursive}), + ) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct EventsRequest { + root: String, + path: String, + is_directory: bool, + #[serde(default)] + recursive: bool, + paths: Vec, + #[serde(default)] + requires_rescan: bool, + #[serde(default)] + hidden_directory_names: Vec, + #[serde(default)] + hidden_file_patterns: Vec, +} + +/// Projects root-relative native names into one subscription, without following +/// ancestor links. Missing entries remain visible so deletions are not lost. +pub fn events_command(payload: Value) -> Result { + let request: EventsRequest = decode(payload)?; + validate_path(&request.path)?; + let rules = VisibilityRules::new(request.hidden_directory_names, request.hidden_file_patterns); + let mut paths = BTreeSet::new(); + let mut rescan = request.requires_rescan || request.paths.len() > EVENT_LIMIT; + let handle = root(&request.root)?; + let deadline = Instant::now() + Duration::from_secs(30); + for path in request.paths.into_iter().take(EVENT_LIMIT) { + check(deadline)?; + if path.is_empty() { + rescan = true; + continue; + } + if validate_path(&path).is_err() { + rescan = true; + continue; + } + let ancestor = !request.path.is_empty() && request.path.starts_with(&format!("{path}/")); + if ancestor { + rescan = true; + continue; + } + let descendant = path.strip_prefix(&request.path).and_then(|suffix| { + if request.path.is_empty() { + Some(suffix) + } else { + suffix.strip_prefix('/') + } + }); + let in_scope = path == request.path + || request.is_directory + && descendant.is_some_and(|suffix| request.recursive || !suffix.contains('/')); + if !in_scope || rules.is_hidden(&path, true) || rules.is_hidden(&path, false) { + continue; + } + let metadata = child_metadata(&handle, &path, deadline); + match metadata { + Ok(info) if info.kind == Kind::Symlink => continue, + Ok(_) => { + paths.insert(path); + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + paths.insert(path); + } + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + // A replaced ancestor may now be a link or an unreadable directory. + rescan = true; + } + Err(error) => return Err(failure(error)), + } + } + // Keep the validated root handle alive through the batch. + drop(handle); + let mut changed = Vec::new(); + let mut bytes = 0; + for path in paths { + bytes += serde_json::to_vec(&path).expect("event path encodes").len(); + if bytes > 900 * 1024 { + rescan = true; + break; + } + changed.push(path); + } + Ok(json!({"changedPaths":changed,"requiresRescan":rescan})) +} + +fn child_metadata( + root: &lithe_platform::scoped_read::Directory, + path: &str, + deadline: Instant, +) -> std::io::Result { + let (parents, name) = path.rsplit_once('/').unwrap_or(("", path)); + let mut current = None; + for component in parents.split('/').filter(|part| !part.is_empty()) { + if Instant::now() >= deadline { + return Err(std::io::ErrorKind::TimedOut.into()); + } + let parent = current.as_ref().unwrap_or(root); + current = Some(parent.directory(OsStr::new(component))?); + } + current + .as_ref() + .unwrap_or(root) + .child_metadata(OsStr::new(name)) +} diff --git a/rust/fixtures/workspace/find-watch-v1.json b/rust/fixtures/workspace/find-watch-v1.json new file mode 100644 index 00000000..14b37321 --- /dev/null +++ b/rust/fixtures/workspace/find-watch-v1.json @@ -0,0 +1,69 @@ +{ + "version": 1, + "files": [ + { + "path": "a.txt", + "text": "alpha\nBETA alpha\n" + }, + { + "path": "src/b.txt", + "text": "alpha\n" + }, + { + "path": "z.md", + "text": "alpha\n" + }, + { + "path": ".git/hidden.txt", + "text": "alpha\n" + } + ], + "fileRequest": { + "query": ".txt", + "limit": 1 + }, + "filePaths": [ + "a.txt", + "src/b.txt" + ], + "textRequest": { + "pattern": "alpha", + "fileMask": "*.txt", + "limit": 2 + }, + "textMatches": [ + { + "path": "a.txt", + "line": 1, + "preview": "alpha", + "range": null + }, + { + "path": "a.txt", + "line": 2, + "preview": "BETA alpha", + "range": null + }, + { + "path": "src/b.txt", + "line": 1, + "preview": "alpha", + "range": null + } + ], + "watch": { + "paths": [ + "src/b.txt", + "a.txt", + "src/b.txt", + ".git/hidden.txt" + ], + "expected": { + "changedPaths": [ + "a.txt", + "src/b.txt" + ], + "requiresRescan": false + } + } +} diff --git a/rust/fixtures/workspace/read-v1.json b/rust/fixtures/workspace/read-v1.json new file mode 100644 index 00000000..744a6154 --- /dev/null +++ b/rust/fixtures/workspace/read-v1.json @@ -0,0 +1,198 @@ +{ + "directoryFirst": [ + { + "name": "a.txt", + "path": "a.txt", + "kind": "file" + }, + { + "name": "b.txt", + "path": "b.txt", + "kind": "file" + } + ], + "directoryLast": [ + { + "name": "c.txt", + "path": "c.txt", + "kind": "file" + } + ], + "files": [ + { + "id": "utf8", + "bytes": [ + 104, + 101, + 108, + 108, + 111, + 10 + ], + "expected": { + "text": "hello\n", + "encoding": "utf-8", + "source": "disk", + "byteCount": 6, + "isTruncated": false, + "identity": { + "sha256": "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03", + "byteCount": 6, + "isTruncated": false + } + } + }, + { + "id": "empty", + "bytes": [], + "expected": { + "text": "", + "encoding": "utf-8", + "byteCount": 0, + "isTruncated": false, + "identity": { + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "byteCount": 0, + "isTruncated": false + } + } + }, + { + "id": "binary", + "bytes": [ + 0, + 255, + 65 + ], + "expected": { + "base64": "AP9B", + "byteCount": 3, + "isTruncated": false, + "identity": { + "sha256": "a90a10503fbfc95789ff38a1bb5039cb71869ab9c0eb1cb51c4a9099f2933c6b", + "byteCount": 3, + "isTruncated": false + } + } + }, + { + "id": "utf8-boundary", + "bytes": [ + 65, + 228, + 184, + 173 + ], + "maximumBytes": 3, + "expected": { + "base64": "QeS4", + "byteCount": 3, + "isTruncated": true, + "identity": { + "sha256": "33c840794ad07fdbba9882a959c865994d36b551bc2c72ca92e533de1cd914e6", + "byteCount": 3, + "isTruncated": true + } + } + }, + { + "id": "exact-limit", + "bytes": [ + 65, + 66, + 67 + ], + "maximumBytes": 3, + "expected": { + "text": "ABC", + "byteCount": 3, + "isTruncated": false, + "identity": { + "sha256": "b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78", + "byteCount": 3, + "isTruncated": false + } + } + } + ], + "invalid": [ + { + "command": "workspace.stat", + "request": { + "path": "../outside" + } + }, + { + "command": "workspace.stat", + "request": { + "path": "/outside" + } + }, + { + "command": "workspace.stat", + "request": { + "path": "a//b" + } + }, + { + "command": "workspace.stat", + "request": { + "path": "./a" + } + }, + { + "command": "workspace.stat", + "request": { + "path": "a\\b" + } + }, + { + "command": "workspace.readDirectory", + "request": { + "path": "", + "limit": 0 + } + }, + { + "command": "workspace.readDirectory", + "request": { + "path": "", + "limit": 1001 + } + }, + { + "command": "workspace.readDirectory", + "request": { + "path": "", + "cursor": "garbage" + } + }, + { + "command": "workspace.readFile", + "request": { + "path": "" + } + }, + { + "command": "workspace.readFile", + "request": { + "path": "input", + "maximumBytes": 0 + } + }, + { + "command": "workspace.readFile", + "request": { + "path": "input", + "maximumBytes": 131073 + } + }, + { + "command": "workspace.readFile", + "request": { + "path": "input", + "unknown": true + } + } + ] +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 959757c6..d790e48a 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4314,6 +4314,84 @@ listing/search/watch, not authorization for explicit reads. Open/browser paths retain the existing canonical containment checks and their documented check-to-open race; native backends are not OS-sandboxed. +Workspace disk reads (API-06) require exactly `{rootID,path}`. `path` is at +most 4096 UTF-8 bytes, uses `/`, and has no empty, `.` or `..` component, +backslash, absolute prefix or NUL. On Windows, reserved device names, alternate +data streams, trailing dots/spaces and other non-storable names are refused. +`path:""` names the root for `readDirectory` and `stat`, but not `readFile`. +Unknown top-level or resource fields return `unsupportedOption`; malformed +paths, cursors and bounds return `invalidParams`. Missing roots/entries return +`notFound`, filesystem access failures and attempted link traversal return +`permissionDenied`, and other I/O failures return `failed`. Remote contexts +return `authorityUnsupported` before any local I/O. + +`readDirectory.limit` is an integer in 1–1000 (default 200). Entries are ordered +by their UTF-8 name bytes, omit symbolic links/reparse points, names that cannot +be represented as a resource, and the workspace's effective hidden rules. +A page may be shorter than `limit` to respect the serialized response budget. +`nextCursor` is an opaque string, or null when exhausted. It is bound to the +root, directory and filters, and resumes strictly after the last returned name; +changing a directory between pages can omit newly inserted earlier names. It +is a live listing, not a retained snapshot. `stat` reports the leaf itself +(`file`, `directory`, `symlink` or `other`), with byte `size` and epoch +`modifiedMilliseconds` (null when unavailable); no ancestor link is followed. + +`readFile.maximumBytes` is an integer in 1–131072 (default 131072). +`byteCount` counts the returned raw prefix bytes. `isTruncated` is true when +at least one additional byte was observed. `identity` is +`{sha256,byteCount,isTruncated}`, where `sha256` is lowercase SHA-256 of exactly +the returned bytes, never a claim about an unread suffix or an atomic whole-file +snapshot. Valid UTF-8 containing no control characters other than tab, CR and +LF returns `text` and `encoding:"utf-8"`, preserving any UTF-8 BOM. Every other +prefix returns standard `base64` instead, including UTF-8 cut mid-character. +Exactly one of `text` and `base64` is present. Only regular files can be read; +there is no buffer fallback, encoding guessing or lossy substitution. Unix +opens every plugin-supplied component relative to a held directory descriptor +with `O_NOFOLLOW`; Windows rejects reparse points and holds directory ancestors +without write/delete sharing until the operation finishes. + +Workspace search and watches (API-07/08) use the same strict resource paths, +local authority and no-follow policy as disk reads. Unknown fields are +`unsupportedOption`; malformed flags/bounds/queries/cursors and invalid regex +are `invalidParams`. A missing target is `notFound`, access/link traversal is +`permissionDenied`, and other I/O failures are `failed`. + +- `findFiles` and `findText` require a root resource (`path:""`). `query` or + `pattern` must contain 1–4096 UTF-8 bytes; `fileMask` has a 4096-byte maximum + and is a comma-separated list of basename globs such as `*.md,*.txt`. + File-name search is case insensitive. Text search defaults all flags to false + and uses the existing workspace matcher's literal/regex semantics; regex mode + uses the expression's own word boundaries. Pages default to 100 and accept + 1–200, with at most 200 results across continuations. Results sort by UTF-8 + path bytes then one-based line. Text results contain one hit per line, + `range:null`, and a trimmed preview capped at 500 characters. Search reads + disk only, applies effective hidden/indexing/Git-ignore rules, never follows + links, omits binary/undecodable files, and uses the existing search text + decoder. A text file is limited to 2 MiB and directory depth to 128. These + omissions or the overall hit cap set `isTruncated:true`; no exact count is + claimed. A page may be smaller than requested to fit the response budget. + `nextCursor` is null on exhaustion; it binds root, query/options and effective + policy and resumes after the last result without a retained snapshot. + Page size may change, but changing the query or policy invalidates the cursor. +- `watch` accepts an existing regular file or directory and defaults `recursive` + to false. File watches observe replacement/removal of that file; directory + watches observe immediate entries or the subtree when recursive. Events carry + root-relative, sorted and deduplicated `changedPaths` with the calling + plugin's `rootID`. Hidden entries and linked descendants are omitted. + Native streams may coalesce changes, report directories instead of every + descendant, or lose names; `requiresRescan:true` means reread the watched + scope. Registration emits an initial rescan event to close the setup gap. + A batch has at most 1000 paths and 900 KiB; overflow also requests rescan. + At most 16 limited native subscriptions may be held by a backend session; + excess registration returns `limitExceeded`. Disposal is idempotent and + checked against the caller's plugin/session. Context closure, backend exit + or plugin stop releases the stream; notifications stop before disposal + returns. If the workspace root is deleted or replaced, the host emits a final + rescan and releases the old stream; register again after rereading the scope. + Sequence starts at 1, increments per emitted notification, and never + transfers to a replacement session/context. Registration and notifications + use native filesystem events, with no idle polling or filesystem writes. + Machine host requests have a 30-second host deadline. User-choice messages wait until the user answers, the request is cancelled, or the context/session closes. Messages retain the per-plugin/window rate and queue limits (5/10 seconds, diff --git a/shared/plugins/contract/v1/fixtures/backend/function-protocol.json b/shared/plugins/contract/v1/fixtures/backend/function-protocol.json index c34ed926..13a45277 100644 --- a/shared/plugins/contract/v1/fixtures/backend/function-protocol.json +++ b/shared/plugins/contract/v1/fixtures/backend/function-protocol.json @@ -268,6 +268,13 @@ } ], "hostRequests": [ + {"name": "workspace metadata never authorizes a native watch", "version": 0, "hostServices": ["workspace"], "method": "lithe/host/workspace/watch", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r1", "path": ""}, "recursive": true}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "workspace watch recursion is a boolean", "version": 0, "hostServices": ["lithe/host/workspace/watch"], "method": "lithe/host/workspace/watch", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r1", "path": ""}, "recursive": "true"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "file search requires a root resource", "version": 0, "hostServices": ["lithe/host/workspace/findFiles"], "method": "lithe/host/workspace/findFiles", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r1", "path": "sub"}, "query": "needle"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "text search pages have a shared bound", "version": 0, "hostServices": ["lithe/host/workspace/findText"], "method": "lithe/host/workspace/findText", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r1", "path": ""}, "pattern": "needle", "limit": 201}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "only the explicit search method is forwarded", "version": 0, "hostServices": ["lithe/host/workspace/findFiles"], "method": "lithe/host/workspace/findFiles", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r1", "path": ""}, "query": "needle"}, "expected": {"forward": "workspace"}}, + {"name": "directory read requires bounded page size", "version": 0, "hostServices": ["lithe/host/workspace/readDirectory"], "method": "lithe/host/workspace/readDirectory", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r1", "path": ""}, "limit": 1001}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "file read rejects unknown nested resource options", "version": 0, "hostServices": ["lithe/host/workspace/readFile"], "method": "lithe/host/workspace/readFile", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r1", "path": "hello.txt", "followLinks": true}}, "expected": {"rpcCode": -32018, "code": "plugin.host.unsupportedOption", "details": {"option": "resource.followLinks"}}}, {"name": "workspace metadata never authorizes file reads", "version": 0, "hostServices": ["workspace"], "method": "lithe/host/workspace/readFile", "params": {"context": {"contextID": "w1", "generation": 1}}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, {"name": "editor read method grant never authorizes edits", "version": 0, "hostServices": ["lithe/host/editor/getSelections"], "method": "lithe/host/editor/applyEdits", "params": {}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, {"name": "only the explicit file method is forwarded", "version": 0, "hostServices": ["lithe/host/workspace/readFile"], "method": "lithe/host/workspace/readFile", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r1", "path": "hello.txt"}}, "expected": {"forward": "workspace"}}, diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 4487a3ac..66fabe2d 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -8,7 +8,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I 读这张表前先知道三件事: -- **本页描述契约,不描述某个宿主。** 所有 `lithe/host/*` 方法由 Rust Core 校验、宿主执行。当前的宿主是 Lithe 桌面端:它声明了哪些能力、哪些部分尚未呈现,见[版本对照页](capabilities-and-versions.md#能力版本requires)。Lithe 桌面端目前没有注册 `workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText` 和 `preview/openHTML`,申请对应权限的插件会被宿主拒绝。 +- **本页描述契约,不描述某个宿主。** 所有 `lithe/host/*` 方法由 Rust Core 校验、宿主执行。当前的宿主是 Lithe 桌面端:它声明了哪些能力、哪些部分尚未呈现,见[版本对照页](capabilities-and-versions.md#能力版本requires)。包含 API-06–08 Core 与桌面改动的构建在窗口附着后提供本地工作区的 `workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText`;旧构建不会因此获得能力。`preview/openHTML` 尚未注册,申请对应权限的插件会被宿主拒绝。 - **运行时以 `getCapabilities` 为准。** 某个方法出现在本表,不代表当前宿主一定提供;后端调用前先查 `lithe/host/getCapabilities` 返回的 `services`。 - **计划中的条目没有可用方法名。** 第二张表只描述要做的能力,不列候选方法名;在契约正式写入之前,不要按猜测的名字调用。 @@ -31,9 +31,9 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-03 | 菜单、快捷键、上下文键、状态栏 | 部分完成 | 已有的命令放置位置(`ui.commands`) | 通用菜单、快捷键贡献、上下文键、状态栏 | [界面](domains/ui.md) | | API-04 | 工作区与文档事件 | 部分完成 | `workspace/didChangeContexts`、`workspace/watch` 的文件事件 | 文档、选区、活动编辑器的变化事件 | [插件后端](domains/backend.md) | | API-05 | 工作区上下文 | 已公开 | [`workspace/listContexts`、`getContext`、`getFolders`](../contract/v1/README.md#workspace-contexts-and-capability-discovery),带 `contextID`/`generation` 与 `rootID` | — | [插件后端](domains/backend.md) | -| API-06 | 文件读取 | 已公开 | [`workspace/readDirectory`、`stat`、`readFile`](../contract/v1/README.md#public-document-file-and-window-methods);每次最多读 128 KiB | Lithe 桌面端尚未注册这三个方法 | [插件后端](domains/backend.md) | -| API-07 | 文件监听 | 已公开 | `workspace/watch` 加 `subscriptions/notify`、`dispose`;上下文或会话结束时回收,溢出时要求重扫 | Lithe 桌面端尚未注册 `workspace/watch` | [插件后端](domains/backend.md) | -| API-08 | 搜索 | 部分完成 | `workspace/findFiles`、`findText`,分页、可取消 | 只搜磁盘内容,不含未保存的修改;匹配的精确范围目前是 `null`;Lithe 桌面端尚未注册这两个方法 | [插件后端](domains/backend.md) | +| API-06 | 文件读取 | 已公开 | [`workspace/readDirectory`、`stat`、`readFile`](../contract/v1/README.md#public-document-file-and-window-methods);每次最多读 128 KiB;Core 执行有界分页和逐段拒绝链接的磁盘读取 | 远程工作区不支持;桌面端需包含 API-06 Core 与桌面改动的构建,Windows 原生行为待验收 | [插件后端](domains/backend.md) | +| API-07 | 文件监听 | 已公开 | `workspace/watch` 加 `subscriptions/notify`、`dispose`;上下文或会话结束时回收,溢出时要求重扫 | 远程工作区不支持;需包含 API-07 Core 与桌面改动的构建,macOS 原生事件已验证,Windows 原生验证未执行 | [插件后端](domains/backend.md) | +| API-08 | 搜索 | 部分完成 | `workspace/findFiles`、`findText`,分页、可取消 | 只搜磁盘内容,不含未保存的修改;匹配的精确范围目前是 `null`;需包含 API-08 Core 与桌面改动的构建,仅支持本地工作区 | [插件后端](domains/backend.md) | | API-09 | 文档与选区读取 | 已公开 | `documents/list`、`documents/getSnapshot`、`editor/getActive`、`editor/getSelections`,包含未保存状态、版本、编码、换行符 | — | [编辑器](domains/editor.md) | | API-10 | 版本化编辑 | 已公开 | `editor/applyEdits`、`replaceSelections`、`insertText`;校验版本,拒绝输入法组字中和只读文档,一批编辑是一次撤销 | — | [编辑器](domains/editor.md) | | API-11 | 保存与文件变更 | 已公开 | [`documents/save`、`saveAs`、`close`](../contract/v1/README.md#saving-documents-and-changing-files)(权限 `documents.save`)和 `workspace/create`、`rename`、`copy`、`trash`(权限 `workspace.files.write`);经文档所有者保存,关闭前先保存,从不覆盖、不丢弃修改、不永久删除,删除只移到系统废纸篓;需要用户选择时直接拒绝,不弹询问 | 一次保存全部文档、永久删除;保存前事件见 API-43 | [编辑器](domains/editor.md)、[插件后端](domains/backend.md) | @@ -93,12 +93,12 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-05 | `workspace/listContexts` | 列出当前的工作区上下文,带变化序号 `revision` | `workspace.metadata` | 0 | | API-05 | `workspace/getContext` | 读取一个工作区上下文 | `workspace.metadata` | 0 | | API-05 | `workspace/getFolders` | 列出上下文的根目录,每个根目录带 `rootID` | `workspace.metadata` | 0 | -| API-06 | `workspace/readDirectory` | 分页列出目录项 | `workspace.files.read` | 0 | -| API-06 | `workspace/stat` | 读取文件或目录的类型、大小和修改时间 | `workspace.files.read` | 0 | -| API-06 | `workspace/readFile` | 读取磁盘上的文件,返回文本或 base64,超过上限时截断 | `workspace.files.read` | 0 | -| API-07 | `workspace/watch` | 监听文件或目录的变化,事件经 `subscriptions/notify` 送达 | `workspace.files.watch` | 0 | -| API-08 | `workspace/findFiles` | 在一个根目录下按名称查找文件,分页 | `workspace.search` | 0 | -| API-08 | `workspace/findText` | 在磁盘内容中搜索文本,按行返回匹配,分页 | `workspace.search` | 0 | +| API-06 | `workspace/readDirectory` | 分页列出目录项;执行/校验补充见 [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | +| API-06 | `workspace/stat` | 读取文件或目录的类型、大小和修改时间;执行/校验补充见 [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | +| API-06 | `workspace/readFile` | 读取磁盘上的文件,返回文本或 base64,超过上限时截断;执行/校验补充见 [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | +| API-07 | `workspace/watch` | 监听文件或目录的变化,事件经 `subscriptions/notify` 送达;执行/校验补充见 [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.watch` | 0 | +| API-08 | `workspace/findFiles` | 在一个根目录下按名称查找文件,分页;执行/校验补充见 [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.search` | 0 | +| API-08 | `workspace/findText` | 在磁盘内容中搜索文本,按行返回匹配,分页;执行/校验补充见 [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.search` | 0 | | API-09 | `documents/list` | 列出已打开文档的摘要 | `documents.read` | 0 | | API-09 | `documents/getSnapshot` | 读取文档当前缓冲区的全文,包含未保存的修改 | `documents.read` | 0 | | API-09 | `editor/getActive` | 读取前台文本标签的文档摘要,没有时为 `null` | `documents.read` | 0 | @@ -191,7 +191,7 @@ Lithe numbers its public plugin APIs API-01 to API-44 in the [API implementation Three things to know before reading the tables: -- **This page describes the contract, not one host.** Rust Core checks every `lithe/host/*` method and the host executes it. The current host is the Lithe desktop client: which capabilities it declares and which parts it does not present yet are in the [version page](capabilities-and-versions.md#capability-versions-requires). The Lithe desktop client does not register `workspace/readDirectory`, `stat`, `readFile`, `watch`, `findFiles`, `findText`, or `preview/openHTML` today, and the host refuses a plugin that asks for the matching permission. +- **This page describes the contract, not one host.** Rust Core checks every `lithe/host/*` method and the host executes it. The current host is the Lithe desktop client: which capabilities it declares and which parts it does not present yet are in the [version page](capabilities-and-versions.md#capability-versions-requires). Builds containing both the API-06–08 Core and desktop changes provide `workspace/readDirectory`, `stat`, `readFile`, `watch`, `findFiles`, and `findText` for local workspaces once a window attaches; older builds do not gain these methods. `preview/openHTML` is not registered, and the host refuses a plugin that asks for the matching permission. - **At runtime, `getCapabilities` decides.** A method listed here is not necessarily offered by the current host; check `services` from `lithe/host/getCapabilities` before calling it. - **Planned entries have no usable method names.** The second table only describes the capability to come and lists no candidate method names; until the contract defines them, do not call guessed names. @@ -214,9 +214,9 @@ Status meanings: | API-03 | Menus, keybindings, context keys, status bar | Partial | Existing command placements (`ui.commands`) | General menus, keybinding contributions, context keys, status bar | [UI](domains/ui.md) | | API-04 | Workspace and document events | Partial | `workspace/didChangeContexts`, file events from `workspace/watch` | Document, selection, and active editor change events | [Plugin backend](domains/backend.md) | | API-05 | Workspace contexts | Public | [`workspace/listContexts`, `getContext`, `getFolders`](../contract/v1/README.md#workspace-contexts-and-capability-discovery) with `contextID`/`generation` and `rootID` | — | [Plugin backend](domains/backend.md) | -| API-06 | File reads | Public | [`workspace/readDirectory`, `stat`, `readFile`](../contract/v1/README.md#public-document-file-and-window-methods); at most 128 KiB per read | The Lithe desktop client does not register these three methods | [Plugin backend](domains/backend.md) | -| API-07 | File watching | Public | `workspace/watch` with `subscriptions/notify` and `dispose`; reclaimed when the context or session ends, with a rescan request on overflow | The Lithe desktop client does not register `workspace/watch` | [Plugin backend](domains/backend.md) | -| API-08 | Search | Partial | `workspace/findFiles` and `findText`, paged and cancellable | Searches disk content only, not unsaved changes; the exact match range is `null` for now; the Lithe desktop client does not register these two methods | [Plugin backend](domains/backend.md) | +| API-06 | File reads | Public | [`workspace/readDirectory`, `stat`, `readFile`](../contract/v1/README.md#public-document-file-and-window-methods); at most 128 KiB per read; Core executes bounded paging and disk reads that refuse link traversal | Remote workspaces are unsupported; the desktop needs both API-06 Core and desktop changes, and native Windows verification is pending | [Plugin backend](domains/backend.md) | +| API-07 | File watching | Public | `workspace/watch` with `subscriptions/notify` and `dispose`; reclaimed when the context or session ends, with a rescan request on overflow | Remote workspaces are unsupported; requires both API-07 Core and desktop changes. Native macOS events are verified; native Windows verification was not run | [Plugin backend](domains/backend.md) | +| API-08 | Search | Partial | `workspace/findFiles` and `findText`, paged and cancellable | Searches disk content only, not unsaved changes; the exact match range is `null` for now; requires both API-08 Core and desktop changes, for local workspaces only | [Plugin backend](domains/backend.md) | | API-09 | Documents and selections | Public | `documents/list`, `documents/getSnapshot`, `editor/getActive`, `editor/getSelections`, with dirty state, version, encoding, and line ending | — | [Editor](domains/editor.md) | | API-10 | Versioned edits | Public | `editor/applyEdits`, `replaceSelections`, `insertText`; version checks, refusal during IME composition and in read-only documents, one undo step per batch | — | [Editor](domains/editor.md) | | API-11 | Save and file operations | Public | [`documents/save`, `saveAs`, `close`](../contract/v1/README.md#saving-documents-and-changing-files) (permission `documents.save`) and `workspace/create`, `rename`, `copy`, `trash` (permission `workspace.files.write`); saves go through the document's owner, a close saves first, nothing is overwritten, discarded or deleted permanently, and a delete only moves to the system trash; a change that needs the user's choice is refused without asking | Saving all documents at once, permanent deletes; pre-save events are API-43 | [Editor](domains/editor.md), [Plugin backend](domains/backend.md) | @@ -276,12 +276,12 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | API-05 | `workspace/listContexts` | Lists the current workspace contexts with the change counter `revision` | `workspace.metadata` | 0 | | API-05 | `workspace/getContext` | Reads one workspace context | `workspace.metadata` | 0 | | API-05 | `workspace/getFolders` | Lists the context's root folders, each with a `rootID` | `workspace.metadata` | 0 | -| API-06 | `workspace/readDirectory` | Lists directory entries page by page | `workspace.files.read` | 0 | -| API-06 | `workspace/stat` | Reads the kind, size, and modification time of a file or directory | `workspace.files.read` | 0 | -| API-06 | `workspace/readFile` | Reads a file from disk as text or base64, truncated past the limit | `workspace.files.read` | 0 | -| API-07 | `workspace/watch` | Watches a file or directory for changes; events arrive through `subscriptions/notify` | `workspace.files.watch` | 0 | -| API-08 | `workspace/findFiles` | Finds files by name under one root, page by page | `workspace.search` | 0 | -| API-08 | `workspace/findText` | Searches disk content for text and returns matching lines, page by page | `workspace.search` | 0 | +| API-06 | `workspace/readDirectory` | Lists directory entries page by page; execution/validation details in [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | +| API-06 | `workspace/stat` | Reads the kind, size, and modification time of a file or directory; execution/validation details in [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | +| API-06 | `workspace/readFile` | Reads a file from disk as text or base64, truncated past the limit; execution/validation details in [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | +| API-07 | `workspace/watch` | Watches a file or directory for changes; events arrive through `subscriptions/notify`; execution/validation details in [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.watch` | 0 | +| API-08 | `workspace/findFiles` | Finds files by name under one root, page by page; execution/validation details in [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.search` | 0 | +| API-08 | `workspace/findText` | Searches disk content for text and returns matching lines, page by page; execution/validation details in [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.search` | 0 | | API-09 | `documents/list` | Lists summaries of the open documents | `documents.read` | 0 | | API-09 | `documents/getSnapshot` | Reads the full text of a document's current buffer, unsaved changes included | `documents.read` | 0 | | API-09 | `editor/getActive` | Reads the document summary of the foreground text tab, or `null` | `documents.read` | 0 | diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index e3ddda14..30cbbeec 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -81,7 +81,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https - 插件声明的运行配置类型只能运行,不能调试。 - 不属于任何工具窗口的 `ui` 命令。 - VCS 提供者的逐行追溯(annotation)、文件历史、文件操作、元数据监听、认证、历史提交差异、项目树与编辑器行号栏状态,以及 `lithe/vcs/execution` 控制台输出。 -- 后端宿主服务:工作区文件与搜索(`workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText`)和 `preview/openHTML` 尚未注册,请求这些权限的插件被拒绝。`workspace/getHostPaths` 也尚未注册,`supports` 返回 false;它和 `listContexts` 共用 `workspace.metadata`,所以声明该权限的插件不会因此被拒绝,见[远程工作区](../guides/plugin-backend-remote-workspaces.md)。运行期以 `lithe/host/getCapabilities` 的返回为准,见 [API 总表](api-catalog.md)。 +- 后端宿主服务:包含 API-06–08 Core 与桌面改动的构建在窗口附着后提供本地磁盘 `workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText`;远程工作区明确拒绝,旧构建不提供。`preview/openHTML` 尚未注册,请求这些权限的插件被拒绝。`workspace/getHostPaths` 也尚未注册,`supports` 返回 false;它和 `listContexts` 共用 `workspace.metadata`,所以声明该权限的插件不会因此被拒绝,见[远程工作区](../guides/plugin-backend-remote-workspaces.md)。运行期以 `lithe/host/getCapabilities` 的返回为准,见 [API 总表](api-catalog.md)。 ### 进程协议版本 @@ -200,7 +200,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani - Run configuration types a plugin declares run but cannot be debugged. - `ui` commands that belong to no tool window. - For VCS providers: annotation, file history, file operations, metadata watching, authentication, history entry diffs, status in the project tree and the editor gutter, and `lithe/vcs/execution` console output. -- Backend host services: the workspace file and search methods (`workspace/readDirectory`, `stat`, `readFile`, `watch`, `findFiles`, `findText`) and `preview/openHTML` are not registered, so a plugin that asks for one of those permissions is refused. `workspace/getHostPaths` is not registered either, so `supports` is false for it; it shares `workspace.metadata` with `listContexts`, so a plugin that declares that permission is not refused for it, see [remote workspaces](../guides/plugin-backend-remote-workspaces.md). At runtime, the reply of `lithe/host/getCapabilities` is authoritative; see the [API catalog](api-catalog.md). +- Backend host services: builds containing both API-06–08 Core and desktop changes provide local disk `workspace/readDirectory`, `stat`, `readFile`, `watch`, `findFiles`, and `findText` once a window attaches. Remote workspaces are refused and older builds do not provide these methods. `preview/openHTML` is not registered, so a plugin that asks for one of those permissions is refused. `workspace/getHostPaths` is not registered either, so `supports` is false for it; it shares `workspace.metadata` with `listContexts`, so a plugin that declares that permission is not refused for it, see [remote workspaces](../guides/plugin-backend-remote-workspaces.md). At runtime, the reply of `lithe/host/getCapabilities` is authoritative; see the [API catalog](api-catalog.md). ### Process protocol versions diff --git a/shared/plugins/reference/domains/backend.md b/shared/plugins/reference/domains/backend.md index 6099f64b..0b63f297 100644 --- a/shared/plugins/reference/domains/backend.md +++ b/shared/plugins/reference/domains/backend.md @@ -8,7 +8,7 @@ > **宿主支持。** Lithe 桌面端声明 `backend` 和 `pluginFunctions`(版本都是 `0`)。一次会话能调用哪些宿主方法,以运行时 `lithe/host/getCapabilities` 返回的 `services` 为准,不要按本页假定。 > 桌面端的 `Declared()` 注释列出了已注册的后端宿主服务:工作区上下文(`workspace/listContexts`、`getContext`、`getFolders` 和 `workspace/didChangeContexts`)、`subscriptions/dispose`、`languageServer/*`、跨插件调用中转、`credentials/*`、`documents/list` 与 `getSnapshot`、`editor/getActive`、`getSelections`、`open`、`reveal`、`insertText`、`replaceSelections`、`applyEdits`、`window/*`、`browser/openExternal`(只接受 HTTP(S) 地址)、`terminal/*` 和 `documents/registerContentProvider`;与窗口绑定的方法在窗口附着后才注册。 -> 工作区文件与搜索(`workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText`)、`preview/openHTML`、`editor/registerActions` 和 `editor/registerProviders` 没有注册,申请对应权限的插件会被拒绝。Run 与调试会话方法(`run/start`、`run/stop`、`debug/start`)是否可用,同样以 `getCapabilities` 为准。 +> 包含 API-06–08 Core 与桌面改动的构建在窗口附着后提供本地 `workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText`;Core 负责有界分页、磁盘读取、搜索和监听事件过滤,Viva 提供原生事件流。关闭工作区会取消请求并释放监听,远程工作区返回 `authorityUnsupported`。旧构建不提供这些方法。`preview/openHTML` 没有注册,申请对应权限的插件会被拒绝。编辑器注册方法以运行时能力发现为准。Run 与调试会话方法(`run/start`、`run/stop`、`debug/start`)是否可用,同样以 `getCapabilities` 为准。 > 说明见 [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go) 中 `Declared()` 上方的注释;各能力的对照见[能力与协议版本对照](../capabilities-and-versions.md)。 > 对契约有疑问,请到 [Lithe-core-rust 的 Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues) 反馈。 @@ -230,7 +230,7 @@ A plugin backend is the plugin's own long-lived process. It runs what a web page > **Host support.** The Lithe desktop declares `backend` and `pluginFunctions` (both version `0`). Which host methods a session may call is decided by `services` in the run-time `lithe/host/getCapabilities` answer; do not assume it from this page. > The comment above `Declared()` in the desktop lists the backend host services it registers: workspace contexts (`workspace/listContexts`, `getContext`, `getFolders`, and `workspace/didChangeContexts`), `subscriptions/dispose`, `languageServer/*`, the cross-plugin call relay, `credentials/*`, `documents/list` and `getSnapshot`, `editor/getActive`, `getSelections`, `open`, `reveal`, `insertText`, `replaceSelections`, `applyEdits`, `window/*`, `browser/openExternal` (HTTP(S) addresses only), `terminal/*`, and `documents/registerContentProvider`; methods bound to a window are registered once the window attaches. -> Workspace files and search (`workspace/readDirectory`, `stat`, `readFile`, `watch`, `findFiles`, `findText`), `preview/openHTML`, `editor/registerActions`, and `editor/registerProviders` are not registered, and a plugin that asks for those permissions is refused. Whether the Run and debug session methods (`run/start`, `run/stop`, `debug/start`) are available is likewise decided by `getCapabilities`. +> Builds containing both API-06–08 Core and desktop changes provide local `workspace/readDirectory`, `stat`, `readFile`, `watch`, `findFiles`, and `findText` once a window attaches. Core owns bounded paging, disk reads, search, and watch event projection; Viva supplies native events. Closing the workspace cancels requests and releases watches, and remote workspaces return `authorityUnsupported`. Older builds do not provide these methods. `preview/openHTML` is not registered. Use runtime discovery for editor registration methods. Whether the Run and debug session methods (`run/start`, `run/stop`, `debug/start`) are available is likewise decided by `getCapabilities`. > See the comment above `Declared()` in [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go); for a per-capability comparison see the [capability and protocol versions](../capabilities-and-versions.md). > Questions about the contract go to [Lithe-core-rust Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues). diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 0ff9a73f..01cb9a1a 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,10 @@ ## 待合入 +- [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190),[@xiaoyumuxi](https://github.com/xiaoyumuxi)(API-07/08,`pluginAPIVersion` 0 内补充):Core 新增 `workspace.watchPlan`、`workspace.watchEvents`、`workspace.findFiles`、`workspace.findText`,宿主方法保持原名和权限。路由前严格校验监听与搜索参数,复用文件匹配、编码和隐藏/索引规则,以 no-follow 句柄处理实时磁盘;搜索分页有查询绑定游标、200 条总上限、取消和 30 秒预算,监听投影有排序去重、隐藏过滤和溢出重扫。桌面使用 Viva 原生事件,订阅受插件/会话/上下文约束,注册后先发重扫,释放前停止通知;无空闲轮询。macOS 原生事件与资源释放已验证,Windows 原生验证本轮未执行。没有新增协议版本、宿主方法或通知;合入日期在合并时补齐。 + +- [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190),[@xiaoyumuxi](https://github.com/xiaoyumuxi)(API-06,`pluginAPIVersion` 0 内补充):Core 新增 `workspace.readDirectory`、`workspace.stat`、`workspace.readFile` 三个执行命令;宿主方法保持原名和权限。路由前严格校验上下文、资源、未知字段与分页/读取上限。补齐 no-follow、Windows reparse point、稳定有界分页、磁盘 UTF-8/base64 和截断前缀 identity 的公开行为及共享 fixture;Node SDK 同步明确前缀 identity 类型与可空修改时间;其他 SDK 保留通用 JSON 返回值。没有新增协议版本、方法或通知。合入日期在合并时补齐。 + - [#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 版本。 @@ -101,7 +105,7 @@ ### 宿主方法(按 API 编号) -向后兼容地新增宿主方法、通知或可选字段时不升版本(见契约 [Extending the host services](../contract/v1/README.md#extending-the-host-services)),上面的版本表看不出某个方法是什么时候加的,所以宿主方法和通知在这里逐个登记。一个 API 编号下可以有多个方法,每个方法一行,记首次加入的日期和 PR。方法名省略前缀 `lithe/host/`;用途和权限见 [API 总表](api-catalog.md#已公开的宿主方法)。`keymapImport/*` 属于 `litheKeymapImport` 协议,不在 API-01–44 内。`functions/providers`、`functions/invoke` 是 `litheFunctions` 里的跨插件调用,只对声明了至少一个 `calls` 的后端开放。 +向后兼容地新增宿主方法、通知或可选字段时不升版本(见契约 [Extending the host services](../contract/v1/README.md#extending-the-host-services)),上面的版本表看不出某个方法是什么时候加的,所以宿主方法和通知在这里逐个登记。一个 API 编号下可以有多个方法,每个方法一行,记首次加入的日期和 PR;后续的执行或行为补充另加一行,保留首次记录。方法名省略前缀 `lithe/host/`;用途和权限见 [API 总表](api-catalog.md#已公开的宿主方法)。`keymapImport/*` 属于 `litheKeymapImport` 协议,不在 API-01–44 内。`functions/providers`、`functions/invoke` 是 `litheFunctions` 里的跨插件调用,只对声明了至少一个 `calls` 的后端开放。 | API | 方法 | 协议 | 日期 | PR | | --- | --- | --- | --- | --- | @@ -113,14 +117,20 @@ | API-05 | `workspace/getContext` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-05 | `workspace/getFolders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-06 | `workspace/readDirectory` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| API-06 | `workspace/readDirectory` | 0(执行/校验补充) | 待合入 | [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | | API-06 | `workspace/stat` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| API-06 | `workspace/stat` | 0(执行/校验补充) | 待合入 | [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | | API-06 | `workspace/readFile` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| API-06 | `workspace/readFile` | 0(执行/校验补充) | 待合入 | [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | | API-07 | `workspace/watch` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| API-07 | `workspace/watch` | 0(执行/校验补充) | 待合入 | [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | | API-07、API-24 | `subscriptions/notify`(通知) | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-29 | `build/getOptions` | 0 | 2026-11-21 | [#155](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/155) | | API-29 | `build/watchConfiguration` | 0 | 2026-11-21 | [#155](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/155) | | API-08 | `workspace/findFiles` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| API-08 | `workspace/findFiles` | 0(执行/校验补充) | 待合入 | [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | | API-08 | `workspace/findText` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| API-08 | `workspace/findText` | 0(执行/校验补充) | 待合入 | [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | | API-09 | `documents/list` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-09 | `documents/getSnapshot` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-09 | `editor/getActive` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 5310d02e..1cb085c8 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -300,13 +300,14 @@ export interface Host { entries: { name: string; resource: WorkspaceResource; kind: string }[]; nextCursor: string | null; }>; - stat: Scoped<{ resource: WorkspaceResource }, { resource: WorkspaceResource; kind: string; size: number; modifiedMilliseconds: number }>; + stat: Scoped<{ resource: WorkspaceResource }, { resource: WorkspaceResource; kind: string; size: number; modifiedMilliseconds: number | null }>; readFile: Scoped<{ resource: WorkspaceResource; maximumBytes?: number }, { resource: WorkspaceResource; source: 'disk'; byteCount: number; isTruncated: boolean; - identity: JsonValue; + /** Identity of the returned byte prefix, including whether an unread suffix exists. */ + identity: { sha256: string; byteCount: number; isTruncated: boolean }; text?: string; encoding?: string; base64?: string; diff --git a/shared/plugins/sdk/node/test/types/host.mts b/shared/plugins/sdk/node/test/types/host.mts index 41f12394..d7b579d7 100644 --- a/shared/plugins/sdk/node/test/types/host.mts +++ b/shared/plugins/sdk/node/test/types/host.mts @@ -25,6 +25,12 @@ backend.function('query.run', async (_params, context) => { if (!root) return null; const file = await context.host.workspace.readFile(workspace, { resource: { rootID: root.rootID, path: 'README.md' }, maximumBytes: 4096 }); const truncated: boolean = file.isTruncated; + const identity: { sha256: string; byteCount: number; isTruncated: boolean } = file.identity; + const entry = await context.host.workspace.stat(workspace, { resource: file.resource }); + const modified: number | null = entry.modifiedMilliseconds; + // @ts-expect-error Modification time can be unavailable or before the epoch. + const knownModified: number = entry.modifiedMilliseconds; + void identity; void modified; void knownModified; const { selectedIndex } = await context.host.window.showInformation(workspace, { text: 'Done', actions: ['Open'] }); const choice: number | null = selectedIndex; return { truncated, choice };