Skip to content

Commit ea50225

Browse files
committed
feat(cli): add launch policy and opt-in shell registration rules
1 parent 1539567 commit ea50225

11 files changed

Lines changed: 474 additions & 1 deletion

File tree

‎rust/Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎rust/contracts/rust-core-api.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7632,3 +7632,36 @@ order. A nearer directory masks the project root even when the workspace is a fi
76327632
root. Optional project discovery omits paths outside the supported native bounds, so a
76337633
usable pin still resolves. Both project and external installations can omit `pathPrepend`
76347634
directories explicitly observed as missing.
7635+
7636+
## CLI launch and standalone documents
7637+
7638+
`application.cli.planLaunch` accepts `{args: string[]}` (at most four arguments,
7639+
32768 bytes each). It returns `{action: "welcome"|"open"|"help"|"version", path,
7640+
detach}`. A single path is accepted; `--` protects dash-prefixed paths. `-h` /
7641+
`--help` and `-v` / `--version` are supported. The managed launcher prepends
7642+
`--cli`, requesting a detached GUI child. Invalid or ambiguous arguments fail
7643+
with `invalid_request`, before a window or plugin service is created.
7644+
7645+
`application.cli.openTarget` accepts the native observation `{kind: "file"|
7646+
"directory"}` and returns `{mode: "file"|"project", plugins: boolean, commands: string[]}`.
7647+
The file policy lists permitted command IDs; a project returns an empty list (unrestricted). A regular
7648+
file opens an isolated document session: no plugin registry, backend, language
7649+
server, project scan or Git observation. No terminal is created at startup;
7650+
the user may explicitly open the host's integrated terminal in the selected
7651+
file's directory. Bundled syntax highlighting, editing, guarded saving and
7652+
document observation remain available. Directories
7653+
retain the project workflow and workspace trust. Other native file types fail.
7654+
7655+
`application.cli.editRegistration` accepts `{shell: "zsh"|"bash"|"sh"|"fish"|
7656+
"windows", source, launcherSource?: string, directory, executable, action: "inspect"|"install"|"remove"}`.
7657+
It returns `{installed, source, launcher, owned}`; installed describes the input source.
7658+
Owned recognizes a complete managed launcher, permitting repair after an application move.
7659+
Sources are bounded to 1 MiB. Unix shell configuration uses one marked owned
7660+
block; unrelated bytes and line endings are preserved. Invalid markers fail
7661+
closed. Windows edits only matching user PATH entries, comparing case-insensitively
7662+
and ignoring trailing separators. The native host owns default-shell discovery,
7663+
source selection, optimistic conflict checks, atomic publication, executable
7664+
permissions and environment-change notification. Inspect is read-only; only an
7665+
explicit install/remove click publishes. Launcher resources live in user data,
7666+
never the read-only installation. Removing registration deletes the owned launcher after removing its PATH entry. See
7667+
[fixtures](../fixtures/application/cli-v1.json).

‎rust/crates/core-rules/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ description = "Pure synchronous rules linked into Lithe Core"
99
serde = { version = "1.0", features = ["derive"] }
1010
serde_json = "1.0"
1111
unicode-normalization = "0.1"
12+
lithe-platform = { path = "../platform" }

‎rust/crates/core-rules/src/cli.rs‎

Lines changed: 300 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,300 @@
1+
//! CLI invocation and owned shell registration rules; native adapters perform all I/O.
2+
3+
use crate::{RuleError, RuleErrorCode};
4+
use serde::Deserialize;
5+
use serde_json::{json, Value};
6+
7+
/// Parses bounded launch arguments without probing native paths.
8+
pub const PLAN_LAUNCH: &str = "application.cli.planLaunch";
9+
/// Classifies a native path observation into an isolated editor or a project.
10+
pub const OPEN_TARGET: &str = "application.cli.openTarget";
11+
/// Produces an idempotent edit of only Lithe's owned registration.
12+
pub const EDIT_REGISTRATION: &str = "application.cli.editRegistration";
13+
const BEGIN: &str = "# >>> Lithe CLI >>>";
14+
const END: &str = "# <<< Lithe CLI <<<";
15+
const MAX_SOURCE: usize = 1024 * 1024;
16+
17+
fn invalid(reason: &str) -> RuleError {
18+
RuleError::new(RuleErrorCode::InvalidRequest, reason)
19+
}
20+
21+
#[derive(Deserialize)]
22+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
23+
struct LaunchRequest {
24+
args: Vec<String>,
25+
}
26+
27+
/// Resolves help, version, a single path and the launcher's internal detach marker.
28+
pub fn plan_launch_json(payload: Value) -> Result<Value, RuleError> {
29+
let request: LaunchRequest =
30+
serde_json::from_value(payload).map_err(|_| invalid("Invalid CLI arguments"))?;
31+
if request.args.len() > 4
32+
|| request
33+
.args
34+
.iter()
35+
.any(|s| s.len() > 32768 || s.contains('\0'))
36+
{
37+
return Err(invalid("CLI arguments exceed their bounds"));
38+
}
39+
let mut args = request.args.as_slice();
40+
let detach = args.first().is_some_and(|s| s == "--cli");
41+
if detach {
42+
args = &args[1..];
43+
}
44+
let literal = args.first().is_some_and(|s| s == "--");
45+
if literal {
46+
args = &args[1..];
47+
}
48+
let (action, path) = match args {
49+
[] => ("welcome", ""),
50+
[arg] if !literal && (arg == "--help" || arg == "-h") => ("help", ""),
51+
[arg] if !literal && (arg == "--version" || arg == "-v") => ("version", ""),
52+
[arg] if !arg.is_empty() && (literal || !arg.starts_with('-')) => ("open", arg.as_str()),
53+
_ => return Err(invalid("Expected one file or folder path")),
54+
};
55+
Ok(json!({"action": action, "path": path, "detach": detach}))
56+
}
57+
58+
#[derive(Deserialize)]
59+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
60+
struct TargetRequest {
61+
/// Native observation; never inferred from the filename or extension.
62+
kind: String,
63+
}
64+
65+
/// No project services are permitted for a standalone regular file.
66+
pub fn open_target_json(payload: Value) -> Result<Value, RuleError> {
67+
let request: TargetRequest = serde_json::from_value(payload)
68+
.map_err(|_| invalid("Invalid native target observation"))?;
69+
let (mode, plugins) = match request.kind.as_str() {
70+
"directory" => ("project", true),
71+
"file" => ("file", false),
72+
_ => return Err(invalid("Target must be a regular file or directory")),
73+
};
74+
// Commands outside this list cannot enter project services from an editor-only session.
75+
let commands = if plugins {
76+
Vec::new()
77+
} else {
78+
[
79+
"settings.open",
80+
"logs.open",
81+
"theme.system",
82+
"theme.light",
83+
"theme.dark",
84+
"window.fullscreen",
85+
"language.en",
86+
"language.zh",
87+
"editor.vimMode",
88+
"project.open",
89+
"document.open",
90+
"documents.saveAll",
91+
"tab.close",
92+
"terminal.new",
93+
"tool.terminal",
94+
"editor.find",
95+
"editor.replace",
96+
"editor.fold",
97+
"editor.unfold",
98+
"editor.foldAll",
99+
"editor.unfoldAll",
100+
"editor.addNextOccurrence",
101+
"editor.unselectOccurrence",
102+
"editor.selectAllOccurrences",
103+
"editor.cloneCaretAbove",
104+
"editor.cloneCaretBelow",
105+
]
106+
.into_iter()
107+
.collect::<Vec<_>>()
108+
};
109+
Ok(json!({"mode": mode, "plugins": plugins, "commands": commands}))
110+
}
111+
112+
#[derive(Deserialize)]
113+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
114+
struct RegistrationRequest {
115+
/// zsh, bash, sh, fish or windows; shell discovery belongs to the native adapter.
116+
shell: String,
117+
source: String,
118+
#[serde(default)]
119+
launcher_source: String,
120+
directory: String,
121+
executable: String,
122+
/// inspect never changes the returned source; install/remove require an explicit click.
123+
action: String,
124+
}
125+
126+
fn quote(value: &str) -> String {
127+
format!("'{}'", value.replace('\'', "'\"'\"'"))
128+
}
129+
130+
fn fish_quote(value: &str) -> String {
131+
format!("'{}'", value.replace('\\', "\\\\").replace('\'', "\\'"))
132+
}
133+
134+
/// Keeps unrelated configuration byte-for-byte, rejecting malformed owned blocks.
135+
pub fn edit_registration_json(payload: Value) -> Result<Value, RuleError> {
136+
let request: RegistrationRequest =
137+
serde_json::from_value(payload).map_err(|_| invalid("Invalid CLI registration request"))?;
138+
let r = &request;
139+
if r.source.len() > MAX_SOURCE
140+
|| r.launcher_source.len() > MAX_SOURCE
141+
|| r.directory.is_empty()
142+
|| r.executable.is_empty()
143+
|| [&r.directory, &r.executable]
144+
.iter()
145+
.any(|s| s.len() > 32768 || s.contains(['\0', '\r', '\n']))
146+
|| !matches!(r.action.as_str(), "inspect" | "install" | "remove")
147+
{
148+
return Err(invalid("Invalid CLI registration values"));
149+
}
150+
let windows = r.shell == "windows";
151+
if !windows && !matches!(r.shell.as_str(), "zsh" | "bash" | "sh" | "fish") {
152+
return Err(invalid("Unsupported login shell"));
153+
}
154+
let platform = if windows {
155+
lithe_platform::Platform::Windows
156+
} else {
157+
lithe_platform::Platform::Unix
158+
};
159+
let launcher = lithe_platform::cli::launcher(&r.executable, platform)
160+
.ok_or_else(|| invalid("Invalid launcher path"))?;
161+
let owned = lithe_platform::cli::is_managed_launcher(&r.launcher_source, platform);
162+
if windows {
163+
if r.directory.contains([';', '"']) {
164+
return Err(invalid("Invalid Windows PATH entry"));
165+
}
166+
let same = |s: &str| lithe_platform::cli::same_path_entry(s, &r.directory, platform);
167+
let installed = r.source.split(';').any(same);
168+
let source = match r.action.as_str() {
169+
"install" if !installed => format!(
170+
"{}{}{}",
171+
r.source,
172+
if r.source.is_empty() || r.source.ends_with(';') {
173+
""
174+
} else {
175+
";"
176+
},
177+
r.directory
178+
),
179+
"remove" => r
180+
.source
181+
.split(';')
182+
.filter(|s| !same(s))
183+
.collect::<Vec<_>>()
184+
.join(";"),
185+
_ => r.source.clone(),
186+
};
187+
return Ok(
188+
json!({"installed": installed, "source": source, "launcher": launcher, "owned": owned}),
189+
);
190+
}
191+
let newline = if r.source.contains("\r\n") {
192+
"\r\n"
193+
} else {
194+
"\n"
195+
};
196+
let command = if r.shell == "fish" {
197+
format!(
198+
"if not contains -- {} $PATH; set -gx PATH {} $PATH; end",
199+
fish_quote(&r.directory),
200+
fish_quote(&r.directory)
201+
)
202+
} else {
203+
format!("export PATH={}:\"$PATH\"", quote(&r.directory))
204+
};
205+
let block = format!("{BEGIN}{newline}{command}{newline}{END}{newline}");
206+
let starts: Vec<_> = r.source.match_indices(BEGIN).collect();
207+
let ends: Vec<_> = r.source.match_indices(END).collect();
208+
if starts.len() > 1 || ends.len() > 1 || starts.len() != ends.len() {
209+
return Err(invalid("Conflicting Lithe CLI registration markers"));
210+
}
211+
let range = if let (Some(&(start, _)), Some(&(end, _))) = (starts.first(), ends.first()) {
212+
if end < start || (start > 0 && !r.source[..start].ends_with('\n')) {
213+
return Err(invalid("Malformed Lithe CLI registration block"));
214+
}
215+
let tail = end + END.len();
216+
let suffix = &r.source[tail..];
217+
let length = if suffix.starts_with("\r\n") {
218+
2
219+
} else if suffix.starts_with('\n') {
220+
1
221+
} else if suffix.is_empty() {
222+
0
223+
} else {
224+
return Err(invalid("Malformed Lithe CLI registration block"));
225+
};
226+
Some(start..tail + length)
227+
} else {
228+
None
229+
};
230+
let installed = range.as_ref().is_some_and(|range| {
231+
r.source[range.clone()].trim_end_matches(['\r', '\n'])
232+
== block.trim_end_matches(['\r', '\n'])
233+
});
234+
let mut source = r.source.clone();
235+
match r.action.as_str() {
236+
"install" => {
237+
if let Some(range) = range {
238+
source.replace_range(range, &block);
239+
} else {
240+
if !source.is_empty() && !source.ends_with('\n') {
241+
source.push_str(newline);
242+
}
243+
source.push_str(&block);
244+
}
245+
}
246+
"remove" => {
247+
if let Some(range) = range {
248+
source.replace_range(range, "");
249+
}
250+
}
251+
_ => {}
252+
}
253+
Ok(json!({"installed": installed, "source": source, "launcher": launcher, "owned": owned}))
254+
}
255+
256+
#[cfg(test)]
257+
mod tests {
258+
use super::*;
259+
260+
#[test]
261+
fn launch_rejects_ambiguous_inputs_and_preserves_literal_paths() {
262+
assert!(plan_launch_json(json!({"args": ["a", "b"]})).is_err());
263+
assert!(plan_launch_json(json!({"args": ["--unknown"]})).is_err());
264+
let plan = plan_launch_json(json!({"args": ["--cli", "--", "-file.txt"]})).unwrap();
265+
assert_eq!(plan["path"], "-file.txt");
266+
assert_eq!(plan["detach"], true);
267+
let target = open_target_json(json!({"kind": "file"})).unwrap();
268+
assert_eq!(target["plugins"], false);
269+
let commands = target["commands"].as_array().unwrap();
270+
assert!(commands.contains(&json!("editor.find")));
271+
assert!(commands.contains(&json!("terminal.new")));
272+
assert!(commands.contains(&json!("tool.terminal")));
273+
assert!(!commands.contains(&json!("search.files")));
274+
}
275+
276+
#[test]
277+
fn shell_registration_is_idempotent_and_preserves_unrelated_content() {
278+
for shell in ["zsh", "bash", "sh", "fish", "windows"] {
279+
let original = if shell == "windows" {
280+
"C:\\Tools;%USERPROFILE%\\bin"
281+
} else {
282+
"# personal settings\r\nexport EDITOR=vi\r\n"
283+
};
284+
let mut request = json!({"shell": shell, "source": original, "directory": "/User Space/bin", "executable": "/Apps/Lithe's.app/lithe", "action": "install"});
285+
let first = edit_registration_json(request.clone()).unwrap();
286+
request["source"] = first["source"].clone();
287+
let second = edit_registration_json(request.clone()).unwrap();
288+
assert_eq!(first["source"], second["source"]);
289+
assert_eq!(second["installed"], true);
290+
request["action"] = json!("remove");
291+
assert_eq!(edit_registration_json(request).unwrap()["source"], original);
292+
}
293+
}
294+
295+
#[test]
296+
fn malformed_markers_never_overwrite_shell_configuration() {
297+
let request = json!({"shell": "zsh", "source": BEGIN, "directory": "/bin", "executable": "/app", "action": "install"});
298+
assert!(edit_registration_json(request).is_err());
299+
}
300+
}

‎rust/crates/core-rules/src/dispatch.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
//! Command routing for the rules `lithe-core` forwards to this crate.
22
3-
use crate::{action_search, editor, keymap, visibility, workbench, RuleError, RuleErrorCode};
3+
use crate::{action_search, cli, editor, keymap, visibility, workbench, RuleError, RuleErrorCode};
44
use serde_json::Value;
55

66
/// Every command name this crate owns. `lithe-core` routes exactly these names here.
77
pub const COMMANDS: &[&str] = &[
88
action_search::SEARCH_ACTIONS,
9+
cli::PLAN_LAUNCH,
10+
cli::OPEN_TARGET,
11+
cli::EDIT_REGISTRATION,
912
keymap::ANALYZE_CONFLICTS,
1013
keymap::EVALUATE_CONTEXT,
1114
keymap::MODIFIER_GESTURE_STEP,
@@ -21,6 +24,9 @@ pub const COMMANDS: &[&str] = &[
2124
/// Runs one rule on an already decoded payload.
2225
pub fn execute(command: &str, payload: Value) -> Result<Value, RuleError> {
2326
match command {
27+
cli::PLAN_LAUNCH => cli::plan_launch_json(payload),
28+
cli::OPEN_TARGET => cli::open_target_json(payload),
29+
cli::EDIT_REGISTRATION => cli::edit_registration_json(payload),
2430
action_search::SEARCH_ACTIONS => action_search::search_actions_json(payload),
2531
keymap::ANALYZE_CONFLICTS => keymap::analyze_conflicts_json(payload),
2632
keymap::EVALUATE_CONTEXT => keymap::evaluate_context_json(payload),

‎rust/crates/core-rules/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
//! [`RuleError`], which `lithe-core` maps one to one onto its stable error codes.
1212
1313
pub mod action_search;
14+
pub mod cli;
1415
mod dispatch;
1516
pub mod editor;
1617
mod error;

0 commit comments

Comments
 (0)