From ea502256b6537ff6aec7dff35892452cc5e8e7af Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Fri, 20 Nov 2026 14:44:58 +0800 Subject: [PATCH] feat(cli): add launch policy and opt-in shell registration rules --- rust/Cargo.lock | 1 + rust/contracts/rust-core-api.md | 33 +++ rust/crates/core-rules/Cargo.toml | 1 + rust/crates/core-rules/src/cli.rs | 300 +++++++++++++++++++++ rust/crates/core-rules/src/dispatch.rs | 8 +- rust/crates/core-rules/src/lib.rs | 1 + rust/crates/core/src/protocol/command.rs | 5 + rust/crates/core/src/runtime/dispatcher.rs | 1 + rust/crates/platform/src/cli.rs | 90 +++++++ rust/crates/platform/src/lib.rs | 1 + rust/fixtures/application/cli-v1.json | 34 +++ 11 files changed, 474 insertions(+), 1 deletion(-) create mode 100644 rust/crates/core-rules/src/cli.rs create mode 100644 rust/crates/platform/src/cli.rs create mode 100644 rust/fixtures/application/cli-v1.json diff --git a/rust/Cargo.lock b/rust/Cargo.lock index cd1940ea..408e367e 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -956,6 +956,7 @@ dependencies = [ name = "lithe-core-rules" version = "0.1.0" dependencies = [ + "lithe-platform", "serde", "serde_json", "unicode-normalization", diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index e7c91fa8..5b48a1db 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -7632,3 +7632,36 @@ order. A nearer directory masks the project root even when the workspace is a fi root. Optional project discovery omits paths outside the supported native bounds, so a usable pin still resolves. Both project and external installations can omit `pathPrepend` directories explicitly observed as missing. + +## CLI launch and standalone documents + +`application.cli.planLaunch` accepts `{args: string[]}` (at most four arguments, +32768 bytes each). It returns `{action: "welcome"|"open"|"help"|"version", path, +detach}`. A single path is accepted; `--` protects dash-prefixed paths. `-h` / +`--help` and `-v` / `--version` are supported. The managed launcher prepends +`--cli`, requesting a detached GUI child. Invalid or ambiguous arguments fail +with `invalid_request`, before a window or plugin service is created. + +`application.cli.openTarget` accepts the native observation `{kind: "file"| +"directory"}` and returns `{mode: "file"|"project", plugins: boolean, commands: string[]}`. +The file policy lists permitted command IDs; a project returns an empty list (unrestricted). A regular +file opens an isolated document session: no plugin registry, backend, language +server, project scan or Git observation. No terminal is created at startup; +the user may explicitly open the host's integrated terminal in the selected +file's directory. Bundled syntax highlighting, editing, guarded saving and +document observation remain available. Directories +retain the project workflow and workspace trust. Other native file types fail. + +`application.cli.editRegistration` accepts `{shell: "zsh"|"bash"|"sh"|"fish"| +"windows", source, launcherSource?: string, directory, executable, action: "inspect"|"install"|"remove"}`. +It returns `{installed, source, launcher, owned}`; installed describes the input source. +Owned recognizes a complete managed launcher, permitting repair after an application move. +Sources are bounded to 1 MiB. Unix shell configuration uses one marked owned +block; unrelated bytes and line endings are preserved. Invalid markers fail +closed. Windows edits only matching user PATH entries, comparing case-insensitively +and ignoring trailing separators. The native host owns default-shell discovery, +source selection, optimistic conflict checks, atomic publication, executable +permissions and environment-change notification. Inspect is read-only; only an +explicit install/remove click publishes. Launcher resources live in user data, +never the read-only installation. Removing registration deletes the owned launcher after removing its PATH entry. See +[fixtures](../fixtures/application/cli-v1.json). diff --git a/rust/crates/core-rules/Cargo.toml b/rust/crates/core-rules/Cargo.toml index 27fbb34f..ba58b0b1 100644 --- a/rust/crates/core-rules/Cargo.toml +++ b/rust/crates/core-rules/Cargo.toml @@ -9,3 +9,4 @@ description = "Pure synchronous rules linked into Lithe Core" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" unicode-normalization = "0.1" +lithe-platform = { path = "../platform" } diff --git a/rust/crates/core-rules/src/cli.rs b/rust/crates/core-rules/src/cli.rs new file mode 100644 index 00000000..7715a246 --- /dev/null +++ b/rust/crates/core-rules/src/cli.rs @@ -0,0 +1,300 @@ +//! CLI invocation and owned shell registration rules; native adapters perform all I/O. + +use crate::{RuleError, RuleErrorCode}; +use serde::Deserialize; +use serde_json::{json, Value}; + +/// Parses bounded launch arguments without probing native paths. +pub const PLAN_LAUNCH: &str = "application.cli.planLaunch"; +/// Classifies a native path observation into an isolated editor or a project. +pub const OPEN_TARGET: &str = "application.cli.openTarget"; +/// Produces an idempotent edit of only Lithe's owned registration. +pub const EDIT_REGISTRATION: &str = "application.cli.editRegistration"; +const BEGIN: &str = "# >>> Lithe CLI >>>"; +const END: &str = "# <<< Lithe CLI <<<"; +const MAX_SOURCE: usize = 1024 * 1024; + +fn invalid(reason: &str) -> RuleError { + RuleError::new(RuleErrorCode::InvalidRequest, reason) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LaunchRequest { + args: Vec, +} + +/// Resolves help, version, a single path and the launcher's internal detach marker. +pub fn plan_launch_json(payload: Value) -> Result { + let request: LaunchRequest = + serde_json::from_value(payload).map_err(|_| invalid("Invalid CLI arguments"))?; + if request.args.len() > 4 + || request + .args + .iter() + .any(|s| s.len() > 32768 || s.contains('\0')) + { + return Err(invalid("CLI arguments exceed their bounds")); + } + let mut args = request.args.as_slice(); + let detach = args.first().is_some_and(|s| s == "--cli"); + if detach { + args = &args[1..]; + } + let literal = args.first().is_some_and(|s| s == "--"); + if literal { + args = &args[1..]; + } + let (action, path) = match args { + [] => ("welcome", ""), + [arg] if !literal && (arg == "--help" || arg == "-h") => ("help", ""), + [arg] if !literal && (arg == "--version" || arg == "-v") => ("version", ""), + [arg] if !arg.is_empty() && (literal || !arg.starts_with('-')) => ("open", arg.as_str()), + _ => return Err(invalid("Expected one file or folder path")), + }; + Ok(json!({"action": action, "path": path, "detach": detach})) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TargetRequest { + /// Native observation; never inferred from the filename or extension. + kind: String, +} + +/// No project services are permitted for a standalone regular file. +pub fn open_target_json(payload: Value) -> Result { + let request: TargetRequest = serde_json::from_value(payload) + .map_err(|_| invalid("Invalid native target observation"))?; + let (mode, plugins) = match request.kind.as_str() { + "directory" => ("project", true), + "file" => ("file", false), + _ => return Err(invalid("Target must be a regular file or directory")), + }; + // Commands outside this list cannot enter project services from an editor-only session. + let commands = if plugins { + Vec::new() + } else { + [ + "settings.open", + "logs.open", + "theme.system", + "theme.light", + "theme.dark", + "window.fullscreen", + "language.en", + "language.zh", + "editor.vimMode", + "project.open", + "document.open", + "documents.saveAll", + "tab.close", + "terminal.new", + "tool.terminal", + "editor.find", + "editor.replace", + "editor.fold", + "editor.unfold", + "editor.foldAll", + "editor.unfoldAll", + "editor.addNextOccurrence", + "editor.unselectOccurrence", + "editor.selectAllOccurrences", + "editor.cloneCaretAbove", + "editor.cloneCaretBelow", + ] + .into_iter() + .collect::>() + }; + Ok(json!({"mode": mode, "plugins": plugins, "commands": commands})) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RegistrationRequest { + /// zsh, bash, sh, fish or windows; shell discovery belongs to the native adapter. + shell: String, + source: String, + #[serde(default)] + launcher_source: String, + directory: String, + executable: String, + /// inspect never changes the returned source; install/remove require an explicit click. + action: String, +} + +fn quote(value: &str) -> String { + format!("'{}'", value.replace('\'', "'\"'\"'")) +} + +fn fish_quote(value: &str) -> String { + format!("'{}'", value.replace('\\', "\\\\").replace('\'', "\\'")) +} + +/// Keeps unrelated configuration byte-for-byte, rejecting malformed owned blocks. +pub fn edit_registration_json(payload: Value) -> Result { + let request: RegistrationRequest = + serde_json::from_value(payload).map_err(|_| invalid("Invalid CLI registration request"))?; + let r = &request; + if r.source.len() > MAX_SOURCE + || r.launcher_source.len() > MAX_SOURCE + || r.directory.is_empty() + || r.executable.is_empty() + || [&r.directory, &r.executable] + .iter() + .any(|s| s.len() > 32768 || s.contains(['\0', '\r', '\n'])) + || !matches!(r.action.as_str(), "inspect" | "install" | "remove") + { + return Err(invalid("Invalid CLI registration values")); + } + let windows = r.shell == "windows"; + if !windows && !matches!(r.shell.as_str(), "zsh" | "bash" | "sh" | "fish") { + return Err(invalid("Unsupported login shell")); + } + let platform = if windows { + lithe_platform::Platform::Windows + } else { + lithe_platform::Platform::Unix + }; + let launcher = lithe_platform::cli::launcher(&r.executable, platform) + .ok_or_else(|| invalid("Invalid launcher path"))?; + let owned = lithe_platform::cli::is_managed_launcher(&r.launcher_source, platform); + if windows { + if r.directory.contains([';', '"']) { + return Err(invalid("Invalid Windows PATH entry")); + } + let same = |s: &str| lithe_platform::cli::same_path_entry(s, &r.directory, platform); + let installed = r.source.split(';').any(same); + let source = match r.action.as_str() { + "install" if !installed => format!( + "{}{}{}", + r.source, + if r.source.is_empty() || r.source.ends_with(';') { + "" + } else { + ";" + }, + r.directory + ), + "remove" => r + .source + .split(';') + .filter(|s| !same(s)) + .collect::>() + .join(";"), + _ => r.source.clone(), + }; + return Ok( + json!({"installed": installed, "source": source, "launcher": launcher, "owned": owned}), + ); + } + let newline = if r.source.contains("\r\n") { + "\r\n" + } else { + "\n" + }; + let command = if r.shell == "fish" { + format!( + "if not contains -- {} $PATH; set -gx PATH {} $PATH; end", + fish_quote(&r.directory), + fish_quote(&r.directory) + ) + } else { + format!("export PATH={}:\"$PATH\"", quote(&r.directory)) + }; + let block = format!("{BEGIN}{newline}{command}{newline}{END}{newline}"); + let starts: Vec<_> = r.source.match_indices(BEGIN).collect(); + let ends: Vec<_> = r.source.match_indices(END).collect(); + if starts.len() > 1 || ends.len() > 1 || starts.len() != ends.len() { + return Err(invalid("Conflicting Lithe CLI registration markers")); + } + let range = if let (Some(&(start, _)), Some(&(end, _))) = (starts.first(), ends.first()) { + if end < start || (start > 0 && !r.source[..start].ends_with('\n')) { + return Err(invalid("Malformed Lithe CLI registration block")); + } + let tail = end + END.len(); + let suffix = &r.source[tail..]; + let length = if suffix.starts_with("\r\n") { + 2 + } else if suffix.starts_with('\n') { + 1 + } else if suffix.is_empty() { + 0 + } else { + return Err(invalid("Malformed Lithe CLI registration block")); + }; + Some(start..tail + length) + } else { + None + }; + let installed = range.as_ref().is_some_and(|range| { + r.source[range.clone()].trim_end_matches(['\r', '\n']) + == block.trim_end_matches(['\r', '\n']) + }); + let mut source = r.source.clone(); + match r.action.as_str() { + "install" => { + if let Some(range) = range { + source.replace_range(range, &block); + } else { + if !source.is_empty() && !source.ends_with('\n') { + source.push_str(newline); + } + source.push_str(&block); + } + } + "remove" => { + if let Some(range) = range { + source.replace_range(range, ""); + } + } + _ => {} + } + Ok(json!({"installed": installed, "source": source, "launcher": launcher, "owned": owned})) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn launch_rejects_ambiguous_inputs_and_preserves_literal_paths() { + assert!(plan_launch_json(json!({"args": ["a", "b"]})).is_err()); + assert!(plan_launch_json(json!({"args": ["--unknown"]})).is_err()); + let plan = plan_launch_json(json!({"args": ["--cli", "--", "-file.txt"]})).unwrap(); + assert_eq!(plan["path"], "-file.txt"); + assert_eq!(plan["detach"], true); + let target = open_target_json(json!({"kind": "file"})).unwrap(); + assert_eq!(target["plugins"], false); + let commands = target["commands"].as_array().unwrap(); + assert!(commands.contains(&json!("editor.find"))); + assert!(commands.contains(&json!("terminal.new"))); + assert!(commands.contains(&json!("tool.terminal"))); + assert!(!commands.contains(&json!("search.files"))); + } + + #[test] + fn shell_registration_is_idempotent_and_preserves_unrelated_content() { + for shell in ["zsh", "bash", "sh", "fish", "windows"] { + let original = if shell == "windows" { + "C:\\Tools;%USERPROFILE%\\bin" + } else { + "# personal settings\r\nexport EDITOR=vi\r\n" + }; + let mut request = json!({"shell": shell, "source": original, "directory": "/User Space/bin", "executable": "/Apps/Lithe's.app/lithe", "action": "install"}); + let first = edit_registration_json(request.clone()).unwrap(); + request["source"] = first["source"].clone(); + let second = edit_registration_json(request.clone()).unwrap(); + assert_eq!(first["source"], second["source"]); + assert_eq!(second["installed"], true); + request["action"] = json!("remove"); + assert_eq!(edit_registration_json(request).unwrap()["source"], original); + } + } + + #[test] + fn malformed_markers_never_overwrite_shell_configuration() { + let request = json!({"shell": "zsh", "source": BEGIN, "directory": "/bin", "executable": "/app", "action": "install"}); + assert!(edit_registration_json(request).is_err()); + } +} diff --git a/rust/crates/core-rules/src/dispatch.rs b/rust/crates/core-rules/src/dispatch.rs index 4fa7b36e..a830b766 100644 --- a/rust/crates/core-rules/src/dispatch.rs +++ b/rust/crates/core-rules/src/dispatch.rs @@ -1,11 +1,14 @@ //! Command routing for the rules `lithe-core` forwards to this crate. -use crate::{action_search, editor, keymap, visibility, workbench, RuleError, RuleErrorCode}; +use crate::{action_search, cli, editor, keymap, visibility, workbench, RuleError, RuleErrorCode}; use serde_json::Value; /// Every command name this crate owns. `lithe-core` routes exactly these names here. pub const COMMANDS: &[&str] = &[ action_search::SEARCH_ACTIONS, + cli::PLAN_LAUNCH, + cli::OPEN_TARGET, + cli::EDIT_REGISTRATION, keymap::ANALYZE_CONFLICTS, keymap::EVALUATE_CONTEXT, keymap::MODIFIER_GESTURE_STEP, @@ -21,6 +24,9 @@ pub const COMMANDS: &[&str] = &[ /// Runs one rule on an already decoded payload. pub fn execute(command: &str, payload: Value) -> Result { match command { + cli::PLAN_LAUNCH => cli::plan_launch_json(payload), + cli::OPEN_TARGET => cli::open_target_json(payload), + cli::EDIT_REGISTRATION => cli::edit_registration_json(payload), action_search::SEARCH_ACTIONS => action_search::search_actions_json(payload), keymap::ANALYZE_CONFLICTS => keymap::analyze_conflicts_json(payload), keymap::EVALUATE_CONTEXT => keymap::evaluate_context_json(payload), diff --git a/rust/crates/core-rules/src/lib.rs b/rust/crates/core-rules/src/lib.rs index 66feb1ab..5f04cffc 100644 --- a/rust/crates/core-rules/src/lib.rs +++ b/rust/crates/core-rules/src/lib.rs @@ -11,6 +11,7 @@ //! [`RuleError`], which `lithe-core` maps one to one onto its stable error codes. pub mod action_search; +pub mod cli; mod dispatch; pub mod editor; mod error; diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index c1462693..29646957 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -51,6 +51,8 @@ pub struct RequestOrigin { /// Variants are grouped by domain, but their serialized compatibility names /// live only in [`CoreCommand::parse`] so every host uses one mapping. pub enum CoreCommand { + /// Plans CLI launch and native shell registration (`application.cli.*`). + ApplicationCli, /// Controls the native IDE capability broker (`ideHost.control`). IdeHostControl, /// Reports the Core and protocol versions (`core.ping`). @@ -1040,6 +1042,9 @@ impl CoreCommand { /// case variations that could behave differently across hosts. pub fn parse(value: &str) -> Option { match value { + "application.cli.planLaunch" + | "application.cli.openTarget" + | "application.cli.editRegistration" => Some(Self::ApplicationCli), "core.ping" => Some(Self::Ping), "ideHost.control" => Some(Self::IdeHostControl), "ai.commitInputBudget" => Some(Self::Ai(AiCommand::CommitInputBudget)), diff --git a/rust/crates/core/src/runtime/dispatcher.rs b/rust/crates/core/src/runtime/dispatcher.rs index d91df0c0..044b0e8e 100644 --- a/rust/crates/core/src/runtime/dispatcher.rs +++ b/rust/crates/core/src/runtime/dispatcher.rs @@ -171,6 +171,7 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon let preserve_workspace_outcome = matches!(command, CoreCommand::Git(GitCommand::WorkspaceCommitStep)); let response = match command { + CoreCommand::ApplicationCli => rules_response(id, &parsed.command, parsed.payload), CoreCommand::IdeHostControl => { let action = parsed.payload["action"].as_str().unwrap_or(""); match lithe_ide_host::execute(action, parsed.payload["arguments"].clone()) { diff --git a/rust/crates/platform/src/cli.rs b/rust/crates/platform/src/cli.rs new file mode 100644 index 00000000..80e0d1fb --- /dev/null +++ b/rust/crates/platform/src/cli.rs @@ -0,0 +1,90 @@ +//! Launcher text and PATH comparison without host I/O. + +use crate::Platform; + +/// Produces a shell launcher, rejecting characters the native command format cannot carry. +pub fn launcher(executable: &str, platform: Platform) -> Option { + if executable.is_empty() || executable.contains(['\0', '\r', '\n']) { + return None; + } + match platform { + Platform::Windows => { + if executable.contains('"') { + return None; + } + Some(format!("@echo off\r\nrem Lithe CLI managed launcher\r\nsetlocal DisableDelayedExpansion\r\n\"{}\" --cli %*\r\n", executable.replace('%', "%%"))) + } + Platform::Unix => Some(format!( + "#!/bin/sh\n# Lithe CLI managed launcher\nexec '{}' --cli \"$@\"\n", + executable.replace('\'', "'\"'\"'") + )), + } +} + +/// Recognizes the complete owned format so app moves can repair an earlier launcher. +pub fn is_managed_launcher(source: &str, platform: Platform) -> bool { + let executable = match platform { + Platform::Windows => source.strip_prefix("@echo off\r\nrem Lithe CLI managed launcher\r\nsetlocal DisableDelayedExpansion\r\n\"") + .and_then(|s| s.strip_suffix("\" --cli %*\r\n")) + .map(|s| s.replace("%%", "%")), + Platform::Unix => source.strip_prefix("#!/bin/sh\n# Lithe CLI managed launcher\nexec '") + .and_then(|s| s.strip_suffix("' --cli \"$@\"\n")) + .map(|s| s.replace("'\"'\"'", "'")), + }; + executable + .is_some_and(|exe| launcher(&exe, platform).is_some_and(|expected| expected == source)) +} + +/// Compares native PATH entries with Windows separator and case conventions. +pub fn same_path_entry(left: &str, right: &str, platform: Platform) -> bool { + match platform { + Platform::Unix => left == right, + Platform::Windows => { + left.trim() + .trim_matches('"') + .trim_end_matches(['\\', '/']) + .replace('\\', "/") + .to_lowercase() + == right + .trim() + .trim_matches('"') + .trim_end_matches(['\\', '/']) + .replace('\\', "/") + .to_lowercase() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn launcher_quotes_native_paths_and_marks_ownership() { + let windows = launcher(r"C:\User Space\100%\lithe.exe", Platform::Windows).unwrap(); + assert!(windows.contains(r#""C:\User Space\100%%\lithe.exe" --cli %*"#)); + assert!(windows.contains("DisableDelayedExpansion")); + assert!(is_managed_launcher(&windows, Platform::Windows)); + assert!(launcher("bad\"path", Platform::Windows).is_none()); + let unix = launcher("/Apps/Lithe's/lithe", Platform::Unix).unwrap(); + assert!(unix.contains("'\"'\"'")); + assert!(is_managed_launcher(&unix, Platform::Unix)); + assert!(!is_managed_launcher( + "#!/bin/sh\necho unrelated\n", + Platform::Unix + )); + for platform in Platform::ALL { + assert!(launcher("bad\npath", platform).is_none()); + } + } + + #[test] + fn windows_path_registration_matches_case_slashes_and_quotes() { + assert!(same_path_entry( + r#" "C:\Users\Äpfel\bin\" "#, + "c:/users/äpfel/bin", + Platform::Windows + )); + assert!(!same_path_entry("/Bin", "/bin", Platform::Unix)); + } +} diff --git a/rust/crates/platform/src/lib.rs b/rust/crates/platform/src/lib.rs index 9d34fc91..f9aca1b4 100644 --- a/rust/crates/platform/src/lib.rs +++ b/rust/crates/platform/src/lib.rs @@ -11,6 +11,7 @@ //! crate. Tests that need a real Windows or Unix host to observe them live in //! the `lithe-platform-tests` package. +pub mod cli; pub mod fs; pub mod names; pub mod paths; diff --git a/rust/fixtures/application/cli-v1.json b/rust/fixtures/application/cli-v1.json new file mode 100644 index 00000000..5a12ace0 --- /dev/null +++ b/rust/fixtures/application/cli-v1.json @@ -0,0 +1,34 @@ +{ + "version": 1, + "launch": [ + { + "args": [], + "action": "welcome" + }, + { + "args": [ + "--cli", + "src/main.rs" + ], + "action": "open", + "detach": true + } + ], + "targets": [ + { + "kind": "file", + "mode": "file", + "plugins": false, + "commands": [ + "editor.find", + "terminal.new", + "tool.terminal" + ] + }, + { + "kind": "directory", + "mode": "project", + "plugins": true + } + ] +}