diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 6c7a52fd..2aca1f14 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -497,17 +497,17 @@ or removing a command fails until the table changes in the same commit. | `toolchains.failureReply` | Build the JSON-RPC error reply for a query that missed its deadline or found no backend, so the host passes it to `toolchains.decodeReply` like a provider's own error; cancellation has none | | `toolchains.resolvePins` | Validate a captured local document and find the nearest ancestor directory pin, retaining dormant and legacy entries without probing or writing | | `toolchains.editPins` | Apply one bounded batch of directory pin edits to a captured local document without writing native files | -| `toolchains.catalogState` | Validate machine-wide SDK registrations without a project | -| `toolchains.editCatalog` | Merge confirmed machine-wide SDK registrations and defaults | +| `toolchains.catalogState` | Validate machine-wide SDK registrations and optional workspace project-code trust without a project | +| `toolchains.editCatalog` | Merge confirmed machine-wide SDK registrations, defaults and explicit workspace project-code trust | | `toolchains.pinStoragePlan` | Declare bounded workspace-native pin and ignore sources | | `toolchains.decodePinDocument` | Validate a complete native source or supply the absent-source default | | `toolchains.editPinSources` | Plan deterministic pin and Git ignore source edits without native I/O | | `toolchains.resolveConsumerPreferences` | Validate an inert consumer preference document and resolve one tool's explicit Run, consumer, directory or workspace choice while keeping workspace/consumer inheritance symbolic; no native files or launch authority | | `toolchains.editConsumerPreferences` | Edit or reset one exact consumer/directory tool preference; return the document and effective input without native writes | -| `toolchains.resolve` | Resolve the fixed/project/global/automatic layers from one generation-bound snapshot, retaining unmet requirements, unavailable providers with their cause, conflicts and terminal fixed-value failures | +| `toolchains.resolve` | Resolve the fixed/project/global/automatic layers from one generation-bound snapshot, retaining nearest project candidates, unmet requirements, unavailable providers with their cause, conflicts and terminal fixed-value failures | | `toolchains.checkVersion` | Match captured output with an enabled plugin definition's version expression and compare generic numeric components with an optional minimum; never starts a probe | -| `toolchains.discoveryPlan` | Return platform-filtered definition-owned scan declarations, layouts, probes, PATH entries, login-shell home variables and budgets; never scans native directories | -| `toolchains.candidates` | List one tool's login-shell homes (declared `environment` variables and, from the optional `commandHomes`, declared commands found on the PATH) and host-scanned installations with checked executables, versions or skip reasons, and the automatic-layer choice; never starts a probe. A shell home that checks out is also an `installations` entry with provider `host:shell`, once per canonical home, so a picker can offer every home the resolver may run; `selected` remains the automatic layer's own choice | +| `toolchains.discoveryPlan` | Return platform-filtered definition-owned scan declarations, layouts, probes, PATH entries, login-shell home variables, project-file candidates and budgets; never scans native directories | +| `toolchains.candidates` | List one tool's root project-file candidates, login-shell homes (declared `environment` variables and, from the optional `commandHomes`, declared commands found on the PATH) and host-scanned installations with checked executables, versions or skip reasons, and the automatic-layer choice; never starts a probe. A shell home that checks out is also an `installations` entry with provider `host:shell`, once per canonical home, so a picker can offer every home the resolver may run; `selected` remains the automatic layer's own choice | | `toolchains.instantiateLaunch` | Expand an enabled tool definition's `launch` template for a selected executable, entry, runtime arguments and arguments; a part the template cannot carry is `plugin.toolchain.launchMismatch`; performs no I/O | | `run.decodeStart` | Validate a plugin backend's `lithe/host/run/start` params against its manifest and the workspace, and return the normalized start with temporary-file paths substituted | | `debug.decodeBackendConfiguration` | Validate a plugin backend's `lithe/host/debug/start` params against its manifest and return the qualified adapter, request, label and configuration | @@ -7234,15 +7234,22 @@ must not infer executable names from opaque runtime IDs. ### Global SDK registrations without an open project -`toolchains.catalogState` accepts `{document:string|null,platform,filesystemCaseSensitive?}` -and returns `{status:"ok",state:{document,storage:{relativePath:"toolchains/global.json",maximumBytes:262144}}}`. +`toolchains.catalogState` accepts `{document:string|null,platform,filesystemCaseSensitive?,workspaceRoot?}` +and returns `{status:"ok",state:{document,storage:{relativePath:"toolchains/global.json",maximumBytes:262144},projectCodeAllowed?}}`. +When `workspaceRoot` is supplied, `projectCodeAllowed` reports whether that normalized workspace +root is in the machine-local `trustedWorkspaces` list (`false` when `workspaceRoot` is `""`); +when `workspaceRoot` is omitted, `projectCodeAllowed` is omitted. Native clients resolve the relative path below their platform user-preference directory, never below a workspace, SDK, installed package or application bundle. Reading an absent source returns `{version:1,tools:{}}` and must not create a directory or file. -`toolchains.editCatalog` accepts the same source fields and a nonempty `edits` array of -`{tool,homes:[absoluteHome],defaultHome:string|null}`. Each edit replaces only that tool's -registrations and default; other tools, including dormant plugins, remain intact. At most +`toolchains.editCatalog` accepts `{document:string|null,platform,filesystemCaseSensitive?,edits?,workspaceTrust?}`, +where at least one of a nonempty `edits` array of `{tool,homes:[absoluteHome],defaultHome:string|null}` +or `workspaceTrust:{workspace,trusted}` is required. Each tool edit replaces only that tool's +registrations and default; other tools, dormant plugins and `trustedWorkspaces` remain intact. +`workspaceTrust` grants or revokes machine-local `projectCodeAllowed` trust for one normalized +workspace root (at most 256 distinct workspaces), preserving `tools`; revoking trust on an absent +document returns `changed:false,document:null` and creates no file. At most 64 tools and 32 distinct homes per tool are accepted. Native platform path normalization and case identity apply before deduplication. A selected default is registered if needed; null clears only the default. Empty registrations plus null remove the tool entry. @@ -7270,3 +7277,9 @@ existing precedence remains fixed consumer choice, project override, global defa automatic discovery. Clearing the global default exposes live automatic selection without removing manual registrations. Each new consumer resolves fresh facts and probes; already running processes retain their launch-time environment. + +When no candidate resolves, `toolchains.resolve` reports the first failure in resolution +order. A nearer directory masks the project root even when the workspace is a filesystem +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. diff --git a/rust/contracts/toolchain-global-v1.schema.json b/rust/contracts/toolchain-global-v1.schema.json index 9e57ab4b..629112ba 100644 --- a/rust/contracts/toolchain-global-v1.schema.json +++ b/rust/contracts/toolchain-global-v1.schema.json @@ -37,6 +37,15 @@ } } } + }, + "trustedWorkspaces": { + "type": "array", + "maxItems": 256, + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1 + } } } } diff --git a/rust/crates/core/src/tests/toolchain_resolution.rs b/rust/crates/core/src/tests/toolchain_resolution.rs index 8730ca25..b9f5cc1a 100644 --- a/rust/crates/core/src/tests/toolchain_resolution.rs +++ b/rust/crates/core/src/tests/toolchain_resolution.rs @@ -253,6 +253,29 @@ fn toolchain_resolution_valid_pin_does_not_depend_on_provider_availability() { assert_eq!(result["outcome"]["selection"]["layer"], "pinned"); } +#[test] +fn toolchain_resolution_review_keeps_pin_when_project_paths_exceed_the_native_limit() { + let mut value = input(); + installation(&mut value, HOME, "21.0.4"); + value["local"] = local_pins(); + let definition = &mut value["registry"]["plugins"][0]["manifest"]["toolDefinitions"][0]; + let runner = "long-but-valid-fixture-wrapper"; + definition["wrappers"] = json!([{"path":runner,"platforms":["macos"]}]); + definition["executables"].as_array_mut().unwrap().insert( + 1, + json!({"id":"wrapper","kind":"projectFile","path":runner,"platforms":["macos"]}), + ); + // The root is within the native path budget, but appending the optional layout is not. + let root = format!("/{}fixture", "sample-project/".repeat(272)); + value["workspaceRoot"] = json!(root); + value["filesystem"].as_array_mut().unwrap()[0] = fact(&root, "directory", false); + + let result = resolve(&value); + assert_eq!(result["outcome"]["selection"]["home"], HOME); + assert_eq!(result["outcome"]["selection"]["layer"], "pinned"); + assert_eq!(result["projectCandidates"], json!([])); +} + #[test] fn toolchain_resolution_optional_provider_timeout_keeps_shell_fallback_visible() { let mut value = input(); @@ -1091,6 +1114,83 @@ fn toolchain_resolution_wrapper_requires_action_and_never_invents_installation_h assert_eq!(selection["pathPrepend"], json!([])); } +#[test] +fn toolchain_resolution_review_reports_the_first_project_failure_and_still_falls_back() { + let mut value = input(); + let definition = &mut value["registry"]["plugins"][0]["manifest"]["toolDefinitions"][0]; + definition["wrappers"] = json!([{"path":"fixture-wrapper","platforms":["macos"]}]); + definition["executables"].as_array_mut().unwrap().splice( + 1..1, + [ + json!({"id":"wrapper","kind":"projectFile","path":"fixture-wrapper","platforms":["macos"]}), + json!({"id":"env","kind":"projectFile","projectKind":"environment","home":"env","path":"env/bin/java","platforms":["macos","linux"]}), + ], + ); + let executable = format!("{WORKSPACE}/env/bin/java"); + value["projectCodeAllowed"] = json!(true); + value["filesystem"].as_array_mut().unwrap().extend([ + fact(&format!("{WORKSPACE}/fixture-wrapper"), "file", false), + fact(&format!("{WORKSPACE}/env"), "directory", false), + fact(&format!("{WORKSPACE}/env/bin"), "directory", false), + fact(&executable, "file", true), + ]); + + let skipped = resolve(&value); + assert_eq!(skipped["outcome"]["reason"]["code"], "notExecutable"); + assert_eq!(skipped["projectCandidates"][0]["reason"], "notExecutable"); + assert_eq!(skipped["projectCandidates"][1]["reason"], "probeFailed"); + + value["probes"] = json!([{ + "executable":executable, + "output":"openjdk version \"21.0.4\"", + "exitCode":0 + }]); + assert_eq!( + resolve(&value)["outcome"]["selection"]["executable"], + executable + ); +} + +#[test] +fn toolchain_resolution_review_subdirectory_masks_wrappers_at_filesystem_roots() { + for (platform, root) in [ + ("macos", "/"), + ("windows", "C:/"), + ("windows", "//server/share/"), + ] { + let mut value = input(); + let definition = &mut value["registry"]["plugins"][0]["manifest"]["toolDefinitions"][0]; + let runner = "fixture-wrapper"; + definition["wrappers"] = json!([{"path":runner,"platforms":[platform]}]); + definition["executables"].as_array_mut().unwrap().insert( + 1, + json!({"id":"wrapper","kind":"projectFile","path":runner,"platforms":[platform]}), + ); + value["platform"] = json!(platform); + value["workspaceRoot"] = json!(root); + value["directory"] = json!("sub"); + value["projectCodeAllowed"] = json!(true); + let child = format!("{root}sub"); + let executable = format!("{child}/{runner}"); + value["filesystem"] = json!([ + fact(root, "directory", false), + fact(&format!("{root}{runner}"), "file", true), + fact(&child, "directory", false), + fact(&executable, "file", false) + ]); + let result = resolve(&value); + assert_eq!( + result["outcome"]["reason"]["code"], "notExecutable", + "{root}" + ); + assert_eq!( + result["projectCandidates"], + json!([{"candidateID":"wrapper","projectKind":"wrapper","path":executable,"reason":"notExecutable"}]), + "{root}" + ); + } +} + #[test] fn toolchain_resolution_project_environment_home_cannot_symlink_out_of_workspace() { let mut value = input(); @@ -1174,3 +1274,573 @@ fn global_toolchain_mode_refuses_project_pins_and_ignores_project_executables() let rejected = resolve_command(value, validated_manifest_json).unwrap(); assert_eq!(rejected["status"], "rejected", "{rejected}"); } + +#[test] +fn toolchain_discovery_plan_exposes_platform_filtered_project_files() { + let mut value = input(); + let definition = &mut value["registry"]["plugins"][0]["manifest"]["toolDefinitions"][0]; + definition["executableLayouts"] = json!([ + {"path":"bin/java","platforms":["macos","linux"]}, + {"path":"Scripts/java.exe","platforms":["windows"]}, + {"path":"bin/java.exe","platforms":["windows"]} + ]); + definition["wrappers"] = json!([ + {"path":"mvnw","requires":[".mvn/wrapper/maven-wrapper.properties"],"platforms":["macos","linux"]}, + {"path":"mvnw.cmd","platforms":["windows"]} + ]); + definition["executables"] = json!([ + {"id":"pinned","kind":"setting","settingID":"executable","layer":"project"}, + {"id":"wrapper-unix","kind":"projectFile","path":"mvnw","requires":[".mvn/wrapper/maven-wrapper.properties"],"platforms":["macos","linux"]}, + {"id":"wrapper-win","kind":"projectFile","path":"mvnw.cmd","platforms":["windows"]}, + {"id":"venv-unix","kind":"projectFile","projectKind":"environment","home":".venv","path":".venv/bin/java","requires":[".venv/pyvenv.cfg"],"platforms":["macos","linux"]}, + {"id":"venv-win","kind":"projectFile","projectKind":"environment","home":".venv","path":".venv/Scripts/java.exe","requires":[".venv/pyvenv.cfg"],"platforms":["windows"]}, + {"id":"shell","kind":"command","command":"java"}, + {"id":"home","kind":"environment","variable":"JAVA_HOME","path":"bin/java","platforms":["macos","linux"]}, + {"id":"home-windows","kind":"environment","variable":"JAVA_HOME","path":"bin/java.exe","platforms":["windows"]} + ]); + let macos = discovery_plan_command( + json!({"registry":value["registry"],"platform":"macos"}), + validated_manifest_json, + ) + .unwrap(); + assert_eq!(macos["status"], "ok", "{macos}"); + assert_eq!( + macos["plan"]["tools"][0]["projectFiles"], + json!([ + {"id":"wrapper-unix","projectKind":"wrapper","path":"mvnw","requires":[".mvn/wrapper/maven-wrapper.properties"]}, + {"id":"venv-unix","projectKind":"environment","home":".venv","path":".venv/bin/java","requires":[".venv/pyvenv.cfg"]} + ]) + ); + let windows = discovery_plan_command( + json!({"registry":value["registry"],"platform":"windows"}), + validated_manifest_json, + ) + .unwrap(); + assert_eq!(windows["status"], "ok", "{windows}"); + assert_eq!( + windows["plan"]["tools"][0]["projectFiles"], + json!([ + {"id":"wrapper-win","projectKind":"wrapper","path":"mvnw.cmd","requires":[]}, + {"id":"venv-win","projectKind":"environment","home":".venv","path":".venv/Scripts/java.exe","requires":[".venv/pyvenv.cfg"]} + ]) + ); +} + +#[test] +fn toolchain_resolution_project_environment_allows_symlinked_interpreter_and_preserves_lexical_path( +) { + // Covers Unix single-hop and multi-hop interpreter links (resolved to an external base + // interpreter) and Windows copied or linked `.venv\Scripts` interpreters. + for (platform, workspace, venv_rel_exec, external_target, extra_missing_prepend) in [ + ( + "macos", + WORKSPACE, + "bin/java", + "/opt/lithe-fixtures/uv/runtime/21.0.4/bin/java-real", + "Scripts", + ), + ( + "linux", + WORKSPACE, + "bin/java", + "/usr/lib/lithe-fixtures/runtime/bin/java21", + "Scripts", + ), + ( + "windows", + "C:/Projects/sample", + "Scripts/java.exe", + "C:/Projects/sample/.venv/Scripts/java.exe", + "bin", + ), + ( + "windows", + "C:/Projects/sample", + "Scripts/java.exe", + "C:/Users/dev/AppData/Local/uv/runtime/21.0.4/java.exe", + "bin", + ), + ] { + let mut value = input(); + value["platform"] = json!(platform); + value["workspaceRoot"] = json!(workspace); + let definition = &mut value["registry"]["plugins"][0]["manifest"]["toolDefinitions"][0]; + definition["executableLayouts"] = json!([ + {"path":"bin/java","platforms":["macos","linux"]}, + {"path":"Scripts/java.exe","platforms":["windows"]}, + {"path":"bin/java.exe","platforms":["windows"]} + ]); + definition["pathPrepend"] = json!(["${home}/bin", "${home}/Scripts"]); + definition["executables"].as_array_mut().unwrap().insert( + 1, + json!({ + "id":"venv", + "kind":"projectFile", + "projectKind":"environment", + "home":".venv", + "path":format!(".venv/{venv_rel_exec}"), + "requires":[".venv/pyvenv.cfg"], + "platforms":[platform] + }), + ); + let home = format!("{workspace}/.venv"); + let parent_dir = if platform == "windows" { + format!("{home}/Scripts") + } else { + format!("{home}/bin") + }; + let lexical_exec = format!("{home}/{venv_rel_exec}"); + let cfg_marker = format!("{home}/pyvenv.cfg"); + let missing_prepend = format!("{home}/{extra_missing_prepend}"); + value["filesystem"] = json!([ + fact(workspace, "directory", false), + fact(&home, "directory", false), + fact(&parent_dir, "directory", false), + fact(&cfg_marker, "file", false), + {"path":missing_prepend,"canonicalPath":missing_prepend,"kind":"missing"}, + {"path":lexical_exec,"canonicalPath":external_target,"kind":"file","executable":true} + ]); + + // Before workspace trust is granted, no probe target is emitted and resolution skips. + let untrusted = resolve(&value); + assert_eq!(untrusted["outcome"]["kind"], "skip", "{platform}"); + assert_eq!( + untrusted["outcome"]["reason"]["code"], "projectCodeRequiresAction", + "{platform}" + ); + assert_eq!( + untrusted["projectCandidates"], + json!([{ + "candidateID":"venv", + "projectKind":"environment", + "path":lexical_exec, + "home":home, + "reason":"projectCodeRequiresAction" + }]), + "{platform}" + ); + + // Once trusted, the first pass without probes requests probing the lexical interpreter. + value["projectCodeAllowed"] = json!(true); + let unprobed = resolve(&value); + assert_eq!(unprobed["outcome"]["kind"], "skip", "{platform}"); + assert_eq!( + unprobed["projectCandidates"], + json!([{ + "candidateID":"venv", + "projectKind":"environment", + "path":lexical_exec, + "home":home, + "executable":lexical_exec, + "reason":"probeFailed" + }]), + "{platform}" + ); + + // With the probe result on the lexical path, selection keeps the lexical executable + // so virtual environments resolve pyvenv.cfg and sys.prefix. + value["probes"] = json!([{ + "executable":lexical_exec, + "output":"openjdk version \"21.0.4\"", + "exitCode":0 + }]); + let resolved = resolve(&value); + assert_eq!(resolved["outcome"]["kind"], "resolved", "{platform}"); + let selection = &resolved["outcome"]["selection"]; + assert_eq!(selection["executable"], lexical_exec, "{platform}"); + assert_eq!(selection["home"], home, "{platform}"); + assert_eq!(selection["version"], "21.0.4", "{platform}"); + assert_eq!(selection["layer"], "project", "{platform}"); + assert_eq!(selection["provider"], "host:project", "{platform}"); + assert_eq!(selection["projectCode"], true, "{platform}"); + assert_eq!( + selection["environment"], + json!({"JAVA_HOME":home,"LITHE_JAVA_PATH":lexical_exec}), + "{platform}" + ); + assert_eq!(selection["pathPrepend"], json!([parent_dir]), "{platform}"); + } +} + +#[test] +fn toolchain_resolution_project_environment_rejects_escaping_parent_or_marker_or_non_executable_target( +) { + let setup_venv = |platform: &str, workspace: &str, rel_dir: &str, rel_exe: &str| { + let mut value = input(); + value["platform"] = json!(platform); + value["workspaceRoot"] = json!(workspace); + value["projectCodeAllowed"] = json!(true); + let definition = &mut value["registry"]["plugins"][0]["manifest"]["toolDefinitions"][0]; + definition["executableLayouts"] = json!([ + {"path":format!("{rel_dir}/{rel_exe}"),"platforms":[platform]}, + {"path":"bin/java","platforms":["macos","linux"]}, + {"path":"bin/java.exe","platforms":["windows"]} + ]); + definition["pathPrepend"] = json!([format!("${{home}}/{rel_dir}")]); + definition["executables"].as_array_mut().unwrap().insert( + 1, + json!({ + "id":"venv", + "kind":"projectFile", + "projectKind":"environment", + "home":".venv", + "path":format!(".venv/{rel_dir}/{rel_exe}"), + "requires":[".venv/pyvenv.cfg"], + "platforms":[platform] + }), + ); + value + }; + + for (platform, workspace, outside, rel_dir, rel_exe) in [ + ( + "macos", + WORKSPACE, + "/opt/lithe-fixtures/outside", + "bin", + "java", + ), + ( + "windows", + "C:/Projects/sample", + "C:/Outside", + "Scripts", + "java.exe", + ), + ] { + let home = format!("{workspace}/.venv"); + let bin = format!("{home}/{rel_dir}"); + let exe = format!("{bin}/{rel_exe}"); + let cfg = format!("{home}/pyvenv.cfg"); + let external_interp = format!("{outside}/runtime/{rel_exe}"); + + // 1. Intermediate `bin` / `Scripts` parent directory escapes `.venv` (outside workspace or sibling dir). + for escaped_bin in [format!("{outside}/{rel_dir}"), format!("{workspace}/other")] { + let mut value = setup_venv(platform, workspace, rel_dir, rel_exe); + value["filesystem"] = json!([ + fact(workspace, "directory", false), + fact(&home, "directory", false), + {"path":bin,"canonicalPath":escaped_bin,"kind":"directory"}, + fact(&cfg, "file", false), + {"path":exe,"canonicalPath":external_interp,"kind":"file","executable":true} + ]); + let result = resolve(&value); + assert_eq!(result["outcome"]["kind"], "skip", "{platform}"); + assert_eq!(result["outcome"]["reason"]["code"], "unsafePath"); + assert!(result["projectCandidates"][0].get("executable").is_none()); + } + + // 2. `requires` marker escapes workspace via symlink. + let mut value = setup_venv(platform, workspace, rel_dir, rel_exe); + value["filesystem"] = json!([ + fact(workspace, "directory", false), + fact(&home, "directory", false), + fact(&bin, "directory", false), + {"path":cfg,"canonicalPath":format!("{outside}/pyvenv.cfg"),"kind":"file","executable":false}, + {"path":exe,"canonicalPath":external_interp,"kind":"file","executable":true} + ]); + let result = resolve(&value); + assert_eq!(result["outcome"]["kind"], "skip", "{platform}"); + assert_eq!(result["outcome"]["reason"]["code"], "unsafePath"); + + // 3. Executable symlink points to a non-executable file. + let mut value = setup_venv(platform, workspace, rel_dir, rel_exe); + value["filesystem"] = json!([ + fact(workspace, "directory", false), + fact(&home, "directory", false), + fact(&bin, "directory", false), + fact(&cfg, "file", false), + {"path":exe,"canonicalPath":external_interp,"kind":"file","executable":false} + ]); + let result = resolve(&value); + assert_eq!(result["outcome"]["kind"], "skip", "{platform}"); + assert_eq!(result["outcome"]["reason"]["code"], "notExecutable"); + assert!(result["projectCandidates"][0].get("executable").is_none()); + + // 4. Environment root `.venv` itself escapes via symlink (outside workspace or sibling dir). + for escaped_home in [format!("{outside}/venv"), format!("{workspace}/other")] { + let mut value = setup_venv(platform, workspace, rel_dir, rel_exe); + value["filesystem"] = json!([ + fact(workspace, "directory", false), + {"path":home,"canonicalPath":escaped_home,"kind":"directory"}, + fact(&bin, "directory", false), + fact(&cfg, "file", false), + {"path":exe,"canonicalPath":external_interp,"kind":"file","executable":true} + ]); + let result = resolve(&value); + assert_eq!(result["outcome"]["kind"], "skip", "{platform}"); + assert_eq!(result["outcome"]["reason"]["code"], "unsafePath"); + assert!(result["projectCandidates"][0].get("executable").is_none()); + } + + // 5. Unobserved intermediate `bin` / `Scripts` directory fails closed as `unsafePath`. + let mut value = setup_venv(platform, workspace, rel_dir, rel_exe); + value["filesystem"] = json!([ + fact(workspace, "directory", false), + fact(&home, "directory", false), + fact(&cfg, "file", false), + {"path":exe,"canonicalPath":external_interp,"kind":"file","executable":true} + ]); + let result = resolve(&value); + assert_eq!(result["outcome"]["kind"], "skip", "{platform}"); + assert_eq!(result["outcome"]["reason"]["code"], "unsafePath"); + assert!(result["projectCandidates"][0].get("executable").is_none()); + + // 6. Escaping `pathPrepend` directory fails closed before probing (`executable` omitted). + let mut value = setup_venv(platform, workspace, rel_dir, rel_exe); + value["registry"]["plugins"][0]["manifest"]["toolDefinitions"][0]["pathPrepend"] = + json!([format!("${{home}}/{rel_dir}"), "${home}/extra"]); + let extra = format!("{home}/extra"); + value["filesystem"] = json!([ + fact(workspace, "directory", false), + fact(&home, "directory", false), + fact(&bin, "directory", false), + {"path":extra,"canonicalPath":format!("{outside}/extra"),"kind":"directory"}, + fact(&cfg, "file", false), + {"path":exe,"canonicalPath":external_interp,"kind":"file","executable":true} + ]); + let result = resolve(&value); + assert_eq!(result["outcome"]["kind"], "skip", "{platform}"); + assert_eq!(result["outcome"]["reason"]["code"], "unsafePath"); + assert!(result["projectCandidates"][0].get("executable").is_none()); + } +} + +#[test] +fn toolchain_resolution_wrapper_allows_workspace_internal_link_but_rejects_external_link() { + for (platform, workspace, outside, wrapper_name) in [ + ("macos", WORKSPACE, "/opt/lithe-fixtures/outside", "mvnw"), + ("windows", "C:/Projects/sample", "C:/Outside", "mvnw.cmd"), + ] { + let mut value = input(); + value["platform"] = json!(platform); + value["workspaceRoot"] = json!(workspace); + value["directory"] = json!("sub"); + value["projectCodeAllowed"] = json!(true); + let definition = &mut value["registry"]["plugins"][0]["manifest"]["toolDefinitions"][0]; + definition["launch"] = json!(["${executable}", "${arguments}"]); + definition["wrappers"] = json!([{"path":wrapper_name,"platforms":[platform]}]); + definition["executables"].as_array_mut().unwrap().insert( + 1, + json!({"id":"wrapper","kind":"projectFile","path":wrapper_name,"platforms":[platform]}), + ); + let sub = format!("{workspace}/sub"); + let sub_wrapper = format!("{sub}/{wrapper_name}"); + let root_wrapper = format!("{workspace}/{wrapper_name}"); + + // Workspace-internal link (e.g., `sub/mvnw -> ../mvnw`) resolves and preserves `sub/mvnw`. + value["filesystem"] = json!([ + fact(workspace, "directory", false), + fact(&sub, "directory", false), + fact(&root_wrapper, "file", true), + {"path":sub_wrapper,"canonicalPath":root_wrapper,"kind":"file","executable":true} + ]); + let internal = resolve(&value); + assert_eq!(internal["outcome"]["kind"], "resolved", "{platform}"); + assert_eq!(internal["outcome"]["selection"]["executable"], sub_wrapper); + + // Link escaping workspace (`sub/mvnw -> /opt/.../mvnw`) is rejected as `unsafePath`. + value["filesystem"] = json!([ + fact(workspace, "directory", false), + fact(&sub, "directory", false), + {"path":sub_wrapper,"canonicalPath":format!("{outside}/{wrapper_name}"),"kind":"file","executable":true} + ]); + let external = resolve(&value); + assert_eq!(external["outcome"]["kind"], "skip", "{platform}"); + assert_eq!(external["outcome"]["reason"]["code"], "unsafePath"); + } +} + +#[test] +fn toolchain_candidates_and_multi_hop_environment_links_use_synthetic_tool_definition() { + let synthetic_manifest = json!({ + "schemaVersion": 0, + "id": "dev.lithe.test.runtime-support", + "displayName": "Synthetic Runtime", + "version": "0.1.0", + "pluginAPIVersion": 0, + "vendor": {"id": "dev.lithe.test", "displayName": "Test", "signatureRequirement": "publisherPackage"}, + "permissions": [], + "requires": {"toolDefinitions": 0}, + "toolDefinitions": [{ + "id": "dev.lithe.test.runtime-support:vm", + "displayName": "Synthetic VM", + "executableLayouts": [ + {"path": "bin/vm3", "platforms": ["macos", "linux"]}, + {"path": "bin/vm", "platforms": ["macos", "linux"]}, + {"path": "Scripts/vm.exe", "platforms": ["windows"]}, + {"path": "vm.exe", "platforms": ["windows"]} + ], + "executables": [ + {"id": "pinned", "kind": "setting", "settingID": "executable", "layer": "project"}, + {"id": "venv-unix-3", "kind": "projectFile", "projectKind": "environment", "home": ".venv", "path": ".venv/bin/vm3", "requires": [".venv/env.cfg"], "platforms": ["macos", "linux"]}, + {"id": "venv-unix", "kind": "projectFile", "projectKind": "environment", "home": ".venv", "path": ".venv/bin/vm", "requires": [".venv/env.cfg"], "platforms": ["macos", "linux"]}, + {"id": "venv-win", "kind": "projectFile", "projectKind": "environment", "home": ".venv", "path": ".venv/Scripts/vm.exe", "requires": [".venv/env.cfg"], "platforms": ["windows"]}, + {"id": "global", "kind": "setting", "settingID": "executable", "layer": "global"}, + {"id": "shell", "kind": "command", "command": "vm"}, + {"id": "installed", "kind": "toolchain", "scope": "installed"} + ], + "version": {"arguments": ["--version"], "pattern": "SyntheticVM ([0-9]+\\.[0-9]+\\.[0-9]+)"}, + "commands": ["vm"], + "exports": [ + {"name": "SYNTHETIC_VM_HOME", "value": "${home}"}, + {"name": "SYNTHETIC_VM_EXEC", "value": "${executable}"} + ], + "pathPrepend": ["${home}/bin", "${home}/Scripts"], + "launch": ["${executable}", "${runtimeArguments}", "${entry}", "${arguments}"] + }] + }); + + for (platform, workspace, rel_dir, primary, hop, base_exec, missing_dir, sys_home, sys_exec) in [ + ( + "macos", + "/opt/lithe-fixtures/synthetic-ws", + "bin", + "vm3", + Some("vm"), + "/opt/lithe-fixtures/base-vm/3.12.7/bin/vm-real", + "Scripts", + "/opt/lithe-fixtures/system-vm/3.11.9", + "/opt/lithe-fixtures/system-vm/3.11.9/bin/vm3", + ), + ( + "linux", + "/opt/lithe-fixtures/synthetic-ws", + "bin", + "vm3", + Some("vm"), + "/usr/lib/lithe-fixtures/base-vm/3.12.7/bin/vm-real", + "Scripts", + "/usr/lib/lithe-fixtures/system-vm/3.11.9", + "/usr/lib/lithe-fixtures/system-vm/3.11.9/bin/vm3", + ), + ( + "windows", + "C:/Projects/synthetic-ws", + "Scripts", + "vm.exe", + None, + "C:/Projects/synthetic-ws/.venv/Scripts/vm.exe", + "bin", + "C:/ProgramData/SyntheticVM/3.11.9", + "C:/ProgramData/SyntheticVM/3.11.9/vm.exe", + ), + ] { + let home = format!("{workspace}/.venv"); + let dir = format!("{home}/{rel_dir}"); + let lexical_primary = format!("{dir}/{primary}"); + let marker = format!("{home}/env.cfg"); + let missing = format!("{home}/{missing_dir}"); + + let mut fs = vec![ + fact(workspace, "directory", false), + fact(&home, "directory", false), + fact(&dir, "directory", false), + fact(&marker, "file", false), + json!({"path": missing, "canonicalPath": missing, "kind": "missing"}), + json!({"path": lexical_primary, "canonicalPath": base_exec, "kind": "file", "executable": true}), + fact(sys_home, "directory", false), + fact(sys_exec, "file", true), + json!({"path": format!("{sys_home}/Scripts"), "canonicalPath": format!("{sys_home}/Scripts"), "kind": "missing"}), + ]; + if platform != "windows" { + fs.push(fact(&format!("{sys_home}/bin"), "directory", false)); + } else { + fs.push(json!({"path": format!("{sys_home}/bin"), "canonicalPath": format!("{sys_home}/bin"), "kind": "missing"})); + } + if let Some(second_link) = hop { + let lexical_hop = format!("{dir}/{second_link}"); + // Multi-hop symlink chain in `.venv/bin` (`vm -> vm3 -> base_exec`), plus explicit base target fact. + fs.push(json!({"path": lexical_hop, "canonicalPath": base_exec, "kind": "file", "executable": true})); + fs.push(fact(base_exec, "file", true)); + } + + let registry = json!({"plugins": [{"manifest": synthetic_manifest}]}); + let mut cand_req = json!({ + "registry": registry, + "tool": "dev.lithe.test.runtime-support:vm", + "platform": platform, + "workspaceRoot": workspace, + "filesystem": fs, + "probes": [{"executable": sys_exec, "output": "SyntheticVM 3.11.9", "exitCode": 0}], + "systemInstallations": [{"tool": "dev.lithe.test.runtime-support:vm", "home": sys_home}], + "projectCodeAllowed": false + }); + + // 1. Untrusted `candidates`: `project` reports `projectCodeRequiresAction` without `executable`. + let untrusted_res = candidates_command(cand_req.clone(), validated_manifest_json).unwrap(); + assert_eq!(untrusted_res["status"], "ok", "{untrusted_res}"); + let untrusted_cand = untrusted_res["candidates"].clone(); + assert_eq!( + untrusted_cand["project"][0]["reason"], "projectCodeRequiresAction", + "{platform}" + ); + assert!( + untrusted_cand["project"][0].get("executable").is_none(), + "{platform}" + ); + assert_eq!(untrusted_cand["installations"].as_array().unwrap().len(), 1); + assert_eq!(untrusted_cand["installations"][0]["home"], sys_home); + + // 2. Trusted `candidates` before probing `.venv`: emits lexical `executable` with `probeFailed`. + cand_req["projectCodeAllowed"] = json!(true); + let unprobed_cand = candidates_command(cand_req.clone(), validated_manifest_json).unwrap() + ["candidates"] + .clone(); + assert_eq!( + unprobed_cand["project"][0]["executable"], lexical_primary, + "{platform}" + ); + assert_eq!( + unprobed_cand["project"][0]["reason"], "probeFailed", + "{platform}" + ); + + // 3. Trusted `candidates` after probing lexical paths: reports `version`, never mixes `.venv` into `installations`. + let mut probes = vec![ + json!({"executable": sys_exec, "output": "SyntheticVM 3.11.9", "exitCode": 0}), + json!({"executable": lexical_primary, "output": "SyntheticVM 3.12.7", "exitCode": 0}), + ]; + if let Some(second_link) = hop { + probes.push(json!({"executable": format!("{dir}/{second_link}"), "output": "SyntheticVM 3.12.7", "exitCode": 0})); + } + cand_req["probes"] = json!(probes); + let probed_cand = candidates_command(cand_req.clone(), validated_manifest_json).unwrap() + ["candidates"] + .clone(); + assert_eq!(probed_cand["project"][0]["version"], "3.12.7", "{platform}"); + assert!(probed_cand["project"][0].get("reason").is_none()); + assert_eq!(probed_cand["installations"].as_array().unwrap().len(), 1); + + // 4. Full resolution selects `.venv` over `installed` and preserves the lexical interpreter path. + let resolved = resolve(&json!({ + "registry": registry, + "operationID": "synth-1", + "generation": 1, + "context": {"contextID": "ctx-1", "generation": 1}, + "tool": "dev.lithe.test.runtime-support:vm", + "directory": ".", + "platform": platform, + "workspaceRoot": workspace, + "filesystem": fs, + "probes": probes, + "queries": [], + "systemInstallations": [{"tool": "dev.lithe.test.runtime-support:vm", "home": sys_home}], + "environment": {}, + "commandHomes": {}, + "projectCodeAllowed": true + })); + assert_eq!(resolved["outcome"]["kind"], "resolved", "{platform}"); + let selection = &resolved["outcome"]["selection"]; + assert_eq!(selection["executable"], lexical_primary, "{platform}"); + assert_eq!(selection["home"], home, "{platform}"); + assert_eq!(selection["version"], "3.12.7", "{platform}"); + assert_eq!(selection["layer"], "project", "{platform}"); + assert_eq!( + selection["environment"], + json!({"SYNTHETIC_VM_HOME": home, "SYNTHETIC_VM_EXEC": lexical_primary}), + "{platform}" + ); + assert_eq!(selection["pathPrepend"], json!([dir]), "{platform}"); + } +} diff --git a/rust/crates/toolchain/src/catalog.rs b/rust/crates/toolchain/src/catalog.rs index a12b3e53..3c9c767b 100644 --- a/rust/crates/toolchain/src/catalog.rs +++ b/rust/crates/toolchain/src/catalog.rs @@ -11,6 +11,7 @@ use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; const MAX_BYTES: usize = 256 * 1024; +const MAX_TRUSTED_WORKSPACES: usize = 256; #[derive(Clone, Default, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -21,10 +22,12 @@ struct Entry { } #[derive(Clone, Deserialize, PartialEq, Serialize)] -#[serde(deny_unknown_fields)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] struct Catalog { version: u32, tools: BTreeMap, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + trusted_workspaces: Vec, } #[derive(Deserialize)] @@ -34,6 +37,8 @@ struct Request { platform: String, #[serde(default)] filesystem_case_sensitive: Option, + #[serde(default)] + workspace_root: Option, } #[derive(Deserialize)] @@ -44,6 +49,14 @@ struct Edit { default_home: Option, } +/// Explicit machine-local trust mutation for executing tool environments inside one workspace. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct WorkspaceTrustEdit { + workspace: String, + trusted: bool, +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct EditRequest { @@ -51,7 +64,10 @@ struct EditRequest { platform: String, #[serde(default)] filesystem_case_sensitive: Option, + #[serde(default)] edits: Vec, + #[serde(default)] + workspace_trust: Option, } fn invalid(field: &str) -> PluginRejection { @@ -111,6 +127,24 @@ impl Request { }) } + fn trusted_workspaces(&self, workspaces: &[String]) -> Validation> { + let case_sensitive = self.case_sensitive()?; + if workspaces.len() > MAX_TRUSTED_WORKSPACES { + return Err(invalid("trustedWorkspaces")); + } + let mut by_key = BTreeMap::new(); + for workspace in workspaces { + let path = paths::normalize(workspace, &self.platform, true) + .ok_or_else(|| invalid("trustedWorkspaces"))?; + let key = paths::normalize(&path, &self.platform, case_sensitive) + .ok_or_else(|| invalid("trustedWorkspaces"))?; + if by_key.insert(key, path).is_some() { + return Err(invalid("trustedWorkspaces")); + } + } + Ok(by_key.into_values().collect()) + } + fn read(&self) -> Validation { self.case_sensitive()?; let mut catalog = if let Some(text) = &self.document { @@ -123,6 +157,7 @@ impl Request { Catalog { version: 1, tools: BTreeMap::new(), + trusted_workspaces: Vec::new(), } }; if catalog.version != 1 || catalog.tools.len() > 64 { @@ -134,30 +169,59 @@ impl Request { } *entry = self.entry(&entry.homes, &entry.default_home)?; } + catalog.trusted_workspaces = self.trusted_workspaces(&catalog.trusted_workspaces)?; Ok(catalog) } + + fn workspace_trusted(&self, catalog: &Catalog, workspace: &str) -> Validation { + if workspace.is_empty() { + return Ok(false); + } + let case_sensitive = self.case_sensitive()?; + let key = paths::normalize(workspace, &self.platform, case_sensitive) + .ok_or_else(|| invalid("workspaceRoot"))?; + Ok(catalog.trusted_workspaces.iter().any(|entry| { + paths::normalize(entry, &self.platform, case_sensitive).as_ref() == Some(&key) + })) + } } /// Returns the complete validated catalog and the native read plan. pub(crate) fn state(input: &Value) -> Validation { let request: Request = serde_json::from_value(input.clone()).map_err(|_| invalid("input"))?; - Ok( - json!({"document":request.read()?,"storage":{"relativePath":"toolchains/global.json","maximumBytes":MAX_BYTES}}), - ) + let catalog = request.read()?; + let project_code_allowed = request + .workspace_root + .as_deref() + .map(|root| request.workspace_trusted(&catalog, root)) + .transpose()?; + let mut response = json!({ + "document": catalog, + "storage": { + "relativePath": "toolchains/global.json", + "maximumBytes": MAX_BYTES + } + }); + if let Some(allowed) = project_code_allowed { + response["projectCodeAllowed"] = json!(allowed); + } + Ok(response) } -/// Merges only the confirmed tools, preserving all dormant registrations. +/// Merges confirmed tool edits and explicit machine-local workspace trust, preserving dormant registrations. pub(crate) fn edit(input: &Value) -> Validation { let request: EditRequest = serde_json::from_value(input.clone()).map_err(|_| invalid("input"))?; - if request.edits.is_empty() || request.edits.len() > 64 { + if (request.edits.is_empty() && request.workspace_trust.is_none()) || request.edits.len() > 64 { return Err(invalid("edits")); } let source = Request { document: request.document, platform: request.platform, filesystem_case_sensitive: request.filesystem_case_sensitive, + workspace_root: None, }; + let case_sensitive = source.case_sensitive()?; let mut catalog = source.read()?; let original = catalog.clone(); let mut tools = BTreeSet::new(); @@ -175,6 +239,31 @@ pub(crate) fn edit(input: &Value) -> Validation { if catalog.tools.len() > 64 { return Err(invalid("tools")); } + if let Some(trust) = request.workspace_trust { + let normalized = paths::normalize(&trust.workspace, &source.platform, true) + .ok_or_else(|| invalid("workspaceTrust.workspace"))?; + let key = paths::normalize(&normalized, &source.platform, case_sensitive) + .ok_or_else(|| invalid("workspaceTrust.workspace"))?; + let mut by_key: BTreeMap = catalog + .trusted_workspaces + .iter() + .filter_map(|entry| { + Some(( + paths::normalize(entry, &source.platform, case_sensitive)?, + entry.clone(), + )) + }) + .collect(); + if trust.trusted { + by_key.entry(key).or_insert(normalized); + if by_key.len() > MAX_TRUSTED_WORKSPACES { + return Err(invalid("trustedWorkspaces")); + } + } else { + by_key.remove(&key); + } + catalog.trusted_workspaces = by_key.into_values().collect(); + } let changed = catalog != original; let document = if changed { let text = serde_json::to_string_pretty(&catalog).map_err(|_| invalid("document"))? + "\n"; @@ -239,4 +328,93 @@ mod tests { } assert!(edit(&json!({"document":null,"platform":"macos","edits":[{"tool":"vm","homes":["../sdk"],"defaultHome":null}]})).is_err()); } + + #[test] + fn trusted_workspaces_are_normalized_and_preserved_across_sdk_and_trust_edits() { + for (platform, workspace, lookup, other) in [ + ( + "macos", + "/Users/dev/project", + "/Users/dev/project/", + "/Users/dev/other", + ), + ( + "windows", + r"C:\Projects\Sample\", + "c:/projects/sample", + r"C:\Projects\Other", + ), + ] { + // Revoking trust on an absent document is a no-op and creates no file. + let noop = edit(&json!({ + "document": null, + "platform": platform, + "workspaceTrust": {"workspace": workspace, "trusted": false} + })) + .unwrap(); + assert_eq!(noop["changed"], false, "{platform}"); + assert_eq!(noop["document"], Value::Null, "{platform}"); + + // Granting trust normalizes the path and reports projectCodeAllowed only for that root. + let trusted = edit(&json!({ + "document": null, + "platform": platform, + "workspaceTrust": {"workspace": workspace, "trusted": true} + })) + .unwrap(); + assert_eq!(trusted["changed"], true, "{platform}"); + let doc = trusted["document"].as_str().unwrap(); + let allowed = state(&json!({ + "document": doc, + "platform": platform, + "workspaceRoot": lookup + })) + .unwrap(); + assert_eq!(allowed["projectCodeAllowed"], true, "{platform}"); + let denied = state(&json!({ + "document": doc, + "platform": platform, + "workspaceRoot": other + })) + .unwrap(); + assert_eq!(denied["projectCodeAllowed"], false, "{platform}"); + + // Editing SDK homes preserves trustedWorkspaces, and revoking trust preserves SDK homes. + let with_sdk = edit(&json!({ + "document": doc, + "platform": platform, + "edits": [{"tool": "vm", "homes": [other], "defaultHome": null}] + })) + .unwrap(); + let doc2 = with_sdk["document"].as_str().unwrap(); + assert_eq!( + state(&json!({"document": doc2, "platform": platform, "workspaceRoot": lookup})) + .unwrap()["projectCodeAllowed"], + true, + "{platform}" + ); + let revoked = edit(&json!({ + "document": doc2, + "platform": platform, + "workspaceTrust": {"workspace": lookup, "trusted": false} + })) + .unwrap(); + let doc3 = revoked["document"].as_str().unwrap(); + let after_revoke = state(&json!({ + "document": doc3, + "platform": platform, + "workspaceRoot": lookup + })) + .unwrap(); + assert_eq!(after_revoke["projectCodeAllowed"], false, "{platform}"); + assert_eq!( + after_revoke["document"]["tools"]["vm"]["homes"] + .as_array() + .unwrap() + .len(), + 1, + "{platform}" + ); + } + } } diff --git a/rust/crates/toolchain/src/resolution.rs b/rust/crates/toolchain/src/resolution.rs index 8d3b25a5..c1ded77a 100644 --- a/rust/crates/toolchain/src/resolution.rs +++ b/rust/crates/toolchain/src/resolution.rs @@ -91,6 +91,7 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va vec![], vec![], vec![], + vec![], )); }; let generation = input["generation"] @@ -118,6 +119,7 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va vec![json!({"candidateID":"consumerFixed","layer":"pinned","state":"resolved"})], vec![], vec![], + vec![], ), Err(code) => output( input, @@ -127,11 +129,29 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va ], vec![], vec![], + vec![], ), }); } + let candidates: Vec<_> = definition["executables"] + .as_array() + .into_iter() + .flatten() + .filter(|value| applicable(value, platform)) + .collect(); // A failed optional provider must never revoke a usable explicit fixed value. if let Some(home) = pin["pin"]["home"].as_str() { + let project_candidates = if input["global"] == true { + Vec::new() + } else { + let mut file_choices = + collect_project_file_choices(&snapshot, &candidates, &root, directory); + keep_nearest_project_choices(&mut file_choices); + file_choices + .iter() + .map(|choice| project_candidate_row(&snapshot, choice)) + .collect() + }; let result = snapshot.selection( home, pin["pin"]["provider"].as_str().unwrap_or(""), @@ -142,6 +162,7 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va input, json!({"kind":"resolved","selection":selection}), vec![json!({"candidateID":"pinned","layer":"pinned","state":"resolved"})], + project_candidates, vec![], vec![], ), @@ -151,6 +172,7 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va vec![ json!({"candidateID":"pinned","layer":"pinned","state":"terminalFailure","reason":reason(code,tool)}), ], + project_candidates, vec![], vec![], ), @@ -252,15 +274,11 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va ); } installations.extend(system_installations(input, tool)?); - let candidates: Vec<_> = definition["executables"] - .as_array() - .into_iter() - .flatten() - .filter(|value| applicable(value, platform)) - .collect(); let mut trace_rows = Vec::new(); + let mut project_candidates = Vec::new(); let mut conflicts = Vec::new(); let mut outcome = None; + let mut first_failure = None; let mut project_done = false; if let Some(default) = input.get("globalDefault").filter(|value| !value.is_null()) { fields(default, &["home"])?; @@ -345,61 +363,8 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va } (_, "project") if !project_done => { project_done = true; - let mut choices = Vec::new(); - for source in &candidates { - if source["kind"] != "projectFile" { - continue; - } - for ancestor in ancestors(directory) { - let anchor = if ancestor == "." { - root.clone() - } else { - paths::join(&root, ancestor, platform) - .ok_or_else(|| reject("directory"))? - }; - let native = - paths::join(&anchor, source["path"].as_str().unwrap_or(""), platform) - .ok_or_else(|| reject("projectFile"))?; - if snapshot.fact(&native, "file").is_err() { - continue; - } - let markers = - source["requires"] - .as_array() - .into_iter() - .flatten() - .all(|marker| { - marker - .as_str() - .and_then(|marker| paths::join(&anchor, marker, platform)) - .is_some_and(|path| snapshot.fact(&path, "file").is_ok()) - }); - if !markers { - continue; - } - let mut value = (*source).clone(); - value["nativePath"] = json!(native); - if let Some(home) = source["home"].as_str() { - value["nativeHome"] = json!(if home == "." { - anchor.clone() - } else { - paths::join(&anchor, home, platform) - .ok_or_else(|| reject("projectFile.home"))? - }); - } - choices.push(ProjectChoice { - anchor, - category: if source["projectKind"] == "environment" { - 1 - } else { - 0 - }, - native: true, - value, - candidate: true, - }); - } - } + let mut choices = + collect_project_file_choices(&snapshot, &candidates, &root, directory); if candidates .iter() .any(|value| value["kind"] == "toolchain" && value["scope"] == "project") @@ -424,25 +389,18 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va }); } } - choices.sort_by_key(|value| { - ( - std::cmp::Reverse(value.anchor.split('/').count()), - value.category, - ) - }); // The nearest declaration masks inherited declarations even when unmet. - if let Some(nearest) = choices.first().map(|value| value.anchor.split('/').count()) - { - choices.retain(|value| value.anchor.split('/').count() == nearest); - } + keep_nearest_project_choices(&mut choices); + project_candidates = choices + .iter() + .filter(|choice| choice.candidate) + .map(|choice| project_candidate_row(&snapshot, choice)) + .collect(); while let Some(first) = choices.first() { - let depth = first.anchor.split('/').count(); let category = first.category; let count = choices .iter() - .take_while(|value| { - value.anchor.split('/').count() == depth && value.category == category - }) + .take_while(|value| value.category == category) .count(); let mut group: Vec<_> = choices.drain(..count).collect(); let native_sources: BTreeSet<_> = group @@ -489,7 +447,7 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va .filter_map(|value| value.value["provider"].as_str()) .collect(); conflicts.push(json!({"scope":"project","providers":providers,"action":"chooseProvider"})); - failure = Some(reason("providerConflict", tool)); + failure.get_or_insert_with(|| reason("providerConflict", tool)); break; } for choice in &group { @@ -508,7 +466,7 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va if code == "requestedNotInstalled" && !unmet.contains(&why) { unmet.push(why.clone()); } - failure = Some(why); + failure.get_or_insert(why); } } } @@ -624,6 +582,8 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va ); if terminal { outcome = Some(json!({"kind":"terminalFailure","reason":why})); + } else if first_failure.is_none() { + first_failure = Some(why); } } else { trace(&mut trace_rows, id, layer, "empty", None); @@ -640,8 +600,14 @@ pub(crate) fn resolve(input: &Value, validate_manifest: ManifestValidator) -> Va } Ok(output( input, - outcome.unwrap_or_else(|| json!({"kind":"skip","reason":reason("notFound",tool)})), + outcome.unwrap_or_else(|| { + json!({ + "kind": "skip", + "reason": first_failure.unwrap_or_else(|| reason("notFound", tool)) + }) + }), trace_rows, + project_candidates, unmet, conflicts, )) diff --git a/rust/crates/toolchain/src/resolution/automatic.rs b/rust/crates/toolchain/src/resolution/automatic.rs index daa38024..84154826 100644 --- a/rust/crates/toolchain/src/resolution/automatic.rs +++ b/rust/crates/toolchain/src/resolution/automatic.rs @@ -150,7 +150,7 @@ pub(crate) fn candidates(input: &Value, validate_manifest: ManifestValidator) -> .filter(|tool| lithe_plugin_model::is_tool_id(tool)) .ok_or_else(|| reject("tool"))?; let definition = enabled(®istry, tool).ok_or_else(|| reject("tool"))?; - let (snapshot, _) = prepare(input, definition)?; + let (snapshot, root) = prepare(input, definition)?; if input .get("projectCodeAllowed") .is_some_and(|value| !value.is_boolean()) @@ -158,14 +158,23 @@ pub(crate) fn candidates(input: &Value, validate_manifest: ManifestValidator) -> return Err(reject("projectCodeAllowed")); } string_maps(input, &["environment", "commandHomes"])?; - let mut shell = Vec::new(); - let mut shell_selections = Vec::new(); - for candidate in definition["executables"] + let applicable_candidates: Vec<_> = definition["executables"] .as_array() .into_iter() .flatten() .filter(|value| applicable(value, snapshot.platform)) - { + .collect(); + let project = if root.is_empty() { + Vec::new() + } else { + collect_project_file_choices(&snapshot, &applicable_candidates, &root, ".") + .iter() + .map(|choice| project_candidate_row(&snapshot, choice)) + .collect() + }; + let mut shell = Vec::new(); + let mut shell_selections = Vec::new(); + for candidate in &applicable_candidates { // The same lookups the resolver's environment and command layers make. let (source, home, layout) = match candidate["kind"].as_str() { Some("environment") => { @@ -256,7 +265,7 @@ pub(crate) fn candidates(input: &Value, validate_manifest: ManifestValidator) -> } let (selected, conflict) = automatic_choice(&snapshot, set.eligible, None)?; Ok( - json!({"tool":tool,"shell":shell,"installations":installations,"skipped":skipped, + json!({"tool":tool,"project":project,"shell":shell,"installations":installations,"skipped":skipped, "selected":selected.map(|value| value["home"].clone()), "conflicts":conflict.into_iter().collect::>()}), ) diff --git a/rust/crates/toolchain/src/resolution/discovery.rs b/rust/crates/toolchain/src/resolution/discovery.rs index 8d401176..4498536b 100644 --- a/rust/crates/toolchain/src/resolution/discovery.rs +++ b/rust/crates/toolchain/src/resolution/discovery.rs @@ -54,11 +54,38 @@ pub(crate) fn discovery_plan( .filter(|value| value["kind"] == "environment" && applicable(value, platform)) .map(|value| json!({"variable":value["variable"],"path":value.get("path")})) .collect(); + // Project-local wrappers and environments (`kind: "projectFile"`) the host + // observes along the workspace ancestor chain; never probed until trusted. + let project_files: Vec<_> = definition["executables"] + .as_array() + .into_iter() + .flatten() + .filter(|value| value["kind"] == "projectFile" && applicable(value, platform)) + .map(|value| { + let project_kind = value + .get("projectKind") + .and_then(Value::as_str) + .unwrap_or("wrapper"); + let requires = value.get("requires").cloned().unwrap_or_else(|| json!([])); + let mut row = json!({ + "projectKind": project_kind, + "path": value["path"], + "requires": requires, + }); + if let Some(id) = value.get("id") { + row["id"] = id.clone(); + } + if let Some(home) = value.get("home") { + row["home"] = home.clone(); + } + row + }) + .collect(); json!({"tool":definition["id"],"pluginID":entry["pluginID"],"scans":scans,"providers":providers, "homeLayouts":definition.get("homeLayouts").cloned().unwrap_or(json!([])), "executableLayouts":definition["executableLayouts"],"version":definition["version"], "pathPrepend":definition.get("pathPrepend").cloned().unwrap_or(json!([])), - "environment":environment}) + "environment":environment,"projectFiles":project_files}) }) .collect::>(); Ok(json!({"tools":tools,"limits":{"roots":256,"entries":4096,"ancestors":64}})) diff --git a/rust/crates/toolchain/src/resolution/project.rs b/rust/crates/toolchain/src/resolution/project.rs index 30bb419c..a5daf924 100644 --- a/rust/crates/toolchain/src/resolution/project.rs +++ b/rust/crates/toolchain/src/resolution/project.rs @@ -11,6 +11,24 @@ pub(crate) struct ProjectChoice { pub(crate) candidate: bool, } +impl ProjectChoice { + fn depth(&self) -> usize { + // Native roots can end in a separator without contributing a directory. + self.anchor + .split('/') + .filter(|part| !part.is_empty()) + .count() + } +} + +/// Keeps the nearest declaring directory and orders its candidates by category. +pub(crate) fn keep_nearest_project_choices(choices: &mut Vec) { + choices.sort_by_key(|choice| (std::cmp::Reverse(choice.depth()), choice.category)); + if let Some(nearest) = choices.first().map(ProjectChoice::depth) { + choices.retain(|choice| choice.depth() == nearest); + } +} + pub(crate) fn ancestors(directory: &str) -> Vec<&str> { let mut result = vec![directory]; let mut current = directory; @@ -21,76 +39,289 @@ pub(crate) fn ancestors(directory: &str) -> Vec<&str> { result } -pub(crate) fn project_selection( +/// Collects `projectFile` candidates present along `ancestors(directory)` without +/// probing or granting execution authority. Layouts that cannot be represented +/// within the native path rules cannot identify a candidate in this snapshot. +pub(crate) fn collect_project_file_choices( snapshot: &Snapshot<'_>, - choice: &ProjectChoice, -) -> Result { - if !choice.candidate { - let home = choice.value["installation"] - .as_str() - .ok_or("requestedNotInstalled")?; - return snapshot.selection( - home, - choice.value["provider"].as_str().unwrap_or(""), - "project", - ); + candidates: &[&Value], + root: &str, + directory: &str, +) -> Vec { + let mut choices = Vec::new(); + let directories = ancestors(directory); + for source in candidates { + if source["kind"] != "projectFile" { + continue; + } + for &ancestor in &directories { + let anchor = if ancestor == "." { + root.to_owned() + } else if let Some(anchor) = paths::join(root, ancestor, snapshot.platform) { + anchor + } else { + continue; + }; + let Some(native) = paths::join( + &anchor, + source["path"].as_str().unwrap_or(""), + snapshot.platform, + ) else { + continue; + }; + if snapshot.fact(&native, "file").is_err() { + continue; + } + let markers = source["requires"] + .as_array() + .into_iter() + .flatten() + .all(|marker| { + marker + .as_str() + .and_then(|marker| paths::join(&anchor, marker, snapshot.platform)) + .is_some_and(|path| snapshot.fact(&path, "file").is_ok()) + }); + if !markers { + continue; + } + let mut value = (*source).clone(); + value["nativePath"] = json!(native); + if let Some(home) = source["home"].as_str() { + let native_home = if home == "." { + anchor.clone() + } else if let Some(home) = paths::join(&anchor, home, snapshot.platform) { + home + } else { + continue; + }; + value["nativeHome"] = json!(native_home); + } + choices.push(ProjectChoice { + anchor, + category: if source["projectKind"] == "environment" { + 1 + } else { + 0 + }, + native: true, + value, + candidate: true, + }); + } } + choices +} + +/// Validates authorization, directory containment, marker containment, executable +/// evidence and `pathPrepend` safety for one `projectFile` candidate before any probe. +pub(crate) fn validate_project_candidate<'a>( + snapshot: &Snapshot<'_>, + choice: &'a ProjectChoice, +) -> Result<(&'a str, Option<&'a str>), &'static str> { if snapshot.input["projectCodeAllowed"] != true { return Err("projectCodeRequiresAction"); } let path = choice.value["nativePath"].as_str().ok_or("unsafePath")?; - let file = snapshot.fact(path, "file").map_err(|_| "notFound")?; - if file["executable"] != true { - return Err("notExecutable"); - } - let canonical = file["canonicalPath"].as_str().ok_or("unsafePath")?; - if snapshot.key(canonical).map_err(|_| "unsafePath")? - != snapshot.key(path).map_err(|_| "unsafePath")? - { - // Native link-chain identities are not available in this Core-only slice. + let containing_root = snapshot + .roots + .iter() + .find(|root| { + paths::within(path, root, snapshot.platform, snapshot.case_sensitive) + && paths::within( + &choice.anchor, + root, + snapshot.platform, + snapshot.case_sensitive, + ) + }) + .ok_or("unsafePath")?; + let anchor_fact = snapshot + .fact(&choice.anchor, "directory") + .map_err(|_| "unsafePath")?; + let canonical_anchor = anchor_fact["canonicalPath"].as_str().ok_or("unsafePath")?; + if !paths::within( + canonical_anchor, + containing_root, + snapshot.platform, + snapshot.case_sensitive, + ) { return Err("unsafePath"); } + let rel_path = choice.value["path"].as_str().ok_or("unsafePath")?; let home = choice.value["nativeHome"].as_str(); if let Some(home) = home { + if !paths::within(path, home, snapshot.platform, snapshot.case_sensitive) { + return Err("unsafePath"); + } let fact = snapshot.fact(home, "directory").map_err(|_| "unsafePath")?; let canonical_home = fact["canonicalPath"].as_str().ok_or("unsafePath")?; if snapshot.key(canonical_home).map_err(|_| "unsafePath")? != snapshot.key(home).map_err(|_| "unsafePath")? - || !snapshot.roots.iter().any(|root| { - paths::within( + || !paths::within( + canonical_home, + containing_root, + snapshot.platform, + snapshot.case_sensitive, + ) + { + return Err("unsafePath"); + } + // Every intermediate parent directory between `home` and the leaf executable + // (such as `.venv/bin` or `.venv/Scripts`) must be an observed directory whose + // canonical target remains inside `home` and the workspace root. + let mut prefix = String::new(); + let segments: Vec<&str> = rel_path.split('/').collect(); + for segment in &segments[..segments.len().saturating_sub(1)] { + if !prefix.is_empty() { + prefix.push('/'); + } + prefix.push_str(segment); + let dir = + paths::join(&choice.anchor, &prefix, snapshot.platform).ok_or("unsafePath")?; + if paths::within(&dir, home, snapshot.platform, snapshot.case_sensitive) { + let dir_fact = snapshot.fact(&dir, "directory").map_err(|_| "unsafePath")?; + let canonical_dir = dir_fact["canonicalPath"].as_str().ok_or("unsafePath")?; + if !paths::within( + canonical_dir, canonical_home, - root, snapshot.platform, snapshot.case_sensitive, - ) - }) + ) || !paths::within( + canonical_dir, + containing_root, + snapshot.platform, + snapshot.case_sensitive, + ) { + return Err("unsafePath"); + } + } + } + } else { + // Any observed parent directory above a wrapper must remain within the workspace. + let mut prefix = String::new(); + let segments: Vec<&str> = rel_path.split('/').collect(); + for segment in &segments[..segments.len().saturating_sub(1)] { + if !prefix.is_empty() { + prefix.push('/'); + } + prefix.push_str(segment); + let dir = + paths::join(&choice.anchor, &prefix, snapshot.platform).ok_or("unsafePath")?; + if let Ok(dir_fact) = snapshot.fact(&dir, "directory") { + let canonical_dir = dir_fact["canonicalPath"].as_str().ok_or("unsafePath")?; + if !paths::within( + canonical_dir, + containing_root, + snapshot.platform, + snapshot.case_sensitive, + ) { + return Err("unsafePath"); + } + } + } + if snapshot.definition["launch"] + .as_array() + .into_iter() + .flatten() + .any(|token| token == "${home}") { + return Err("homeUnavailable"); + } + } + for marker in choice.value["requires"].as_array().into_iter().flatten() { + let marker_rel = marker.as_str().ok_or("unsafePath")?; + let marker_path = + paths::join(&choice.anchor, marker_rel, snapshot.platform).ok_or("unsafePath")?; + let marker_fact = snapshot + .fact(&marker_path, "file") + .map_err(|_| "notFound")?; + let canonical_marker = marker_fact["canonicalPath"].as_str().ok_or("unsafePath")?; + if !paths::within( + canonical_marker, + containing_root, + snapshot.platform, + snapshot.case_sensitive, + ) { return Err("unsafePath"); } + if let Some(home) = home { + if paths::within( + &marker_path, + home, + snapshot.platform, + snapshot.case_sensitive, + ) && !paths::within( + canonical_marker, + home, + snapshot.platform, + snapshot.case_sensitive, + ) { + return Err("unsafePath"); + } + } } - // A lexical project path must never turn into a provider-owned installation. - if !snapshot - .roots - .iter() - .any(|root| paths::within(path, root, snapshot.platform, snapshot.case_sensitive)) + let file = snapshot.fact(path, "file").map_err(|_| "notFound")?; + if file["executable"] != true { + return Err("notExecutable"); + } + let canonical = file["canonicalPath"].as_str().ok_or("unsafePath")?; + let target = snapshot.fact(canonical, "file").map_err(|_| "unsafePath")?; + if target["executable"] != true { + return Err("notExecutable"); + } + let target_canonical = target["canonicalPath"].as_str().ok_or("unsafePath")?; + if snapshot.key(target_canonical).map_err(|_| "unsafePath")? + != snapshot.key(canonical).map_err(|_| "unsafePath")? { return Err("unsafePath"); } + // Wrappers (no `home`) must resolve inside the workspace root; project environments + // (`home` present, such as `.venv`) may link their leaf interpreter to an external + // base runtime while keeping their environment root and parent directories contained. if home.is_none() - && snapshot.definition["launch"] - .as_array() - .into_iter() - .flatten() - .any(|token| token == "${home}") + && !paths::within( + canonical, + containing_root, + snapshot.platform, + snapshot.case_sensitive, + ) { - return Err("homeUnavailable"); + return Err("unsafePath"); } - // Preserve the lexical interpreter path for project environments (including venv). - let version = match snapshot.version(path) { - Ok(version) => Some(version), - Err(code) if snapshot.minimum.is_some() => return Err(code), - Err(_) => None, + // Verify `exports` and `pathPrepend` before probing so broken environments never run. + snapshot.environment_selection(home, path, None, "host:project", "project", true)?; + Ok((path, home)) +} + +pub(crate) fn project_selection( + snapshot: &Snapshot<'_>, + choice: &ProjectChoice, +) -> Result { + if !choice.candidate { + let home = choice.value["installation"] + .as_str() + .ok_or("requestedNotInstalled")?; + return snapshot.selection( + home, + choice.value["provider"].as_str().unwrap_or(""), + "project", + ); + } + let (path, home) = validate_project_candidate(snapshot, choice)?; + // Project environments require a probe on the lexical interpreter path; wrappers only + // require a probe when the caller requested a `minimumVersion`. + let version = if home.is_some() { + Some(snapshot.version(path)?) + } else { + match snapshot.version(path) { + Ok(version) => Some(version), + Err(code) if snapshot.minimum.is_some() => return Err(code), + Err(_) => None, + } }; + // Preserve the lexical interpreter path so virtual environments resolve `pyvenv.cfg` + // and `sys.prefix` relative to the project environment rather than the base runtime. snapshot.environment_selection( home, path, @@ -101,6 +332,45 @@ pub(crate) fn project_selection( ) } +/// Formats one discovered `projectFile` candidate for `candidates.project` and +/// `resolve.projectCandidates`, emitting `executable` only after authorization and +/// containment checks pass. +pub(crate) fn project_candidate_row(snapshot: &Snapshot<'_>, choice: &ProjectChoice) -> Value { + let id = choice.value["id"].as_str().unwrap_or("projectFile"); + let project_kind = choice + .value + .get("projectKind") + .and_then(Value::as_str) + .unwrap_or("wrapper"); + let mut row = json!({ + "candidateID": id, + "projectKind": project_kind, + "path": choice.value["nativePath"], + }); + if let Some(home) = choice.value["nativeHome"].as_str() { + row["home"] = json!(home); + } + match validate_project_candidate(snapshot, choice) { + Ok((executable, _)) => { + row["executable"] = json!(executable); + match project_selection(snapshot, choice) { + Ok(selection) => { + if let Some(version) = selection["version"].as_str() { + row["version"] = json!(version); + } + } + Err(code) => { + row["reason"] = json!(code); + } + } + } + Err(code) => { + row["reason"] = json!(code); + } + } + row +} + /// Validates the native evidence shared by resolution and candidate listing: platform /// and case policy, workspace roots, filesystem facts and bounded probe outputs. pub(crate) fn prepare<'a>( diff --git a/rust/crates/toolchain/src/resolution/snapshot.rs b/rust/crates/toolchain/src/resolution/snapshot.rs index a931d2fc..67d9ce3e 100644 --- a/rust/crates/toolchain/src/resolution/snapshot.rs +++ b/rust/crates/toolchain/src/resolution/snapshot.rs @@ -222,7 +222,18 @@ impl Snapshot<'_> { .as_str() .and_then(|template| template.strip_prefix("${home}")) .ok_or("unsafePath")?; - let path = format!("{home}{suffix}"); + let path = if suffix.is_empty() { + home.to_owned() + } else { + paths::join(home, suffix.trim_start_matches('/'), self.platform) + .ok_or("unsafePath")? + }; + // Cross-platform definitions may declare both `bin` and `Scripts`; an entry + // attested as `missing` on this layout is omitted, while unobserved or + // escaping entries still fail closed. + if self.fact(&path, "missing").is_ok() { + continue; + } let fact = self.fact(&path, "directory").map_err(|_| "unsafePath")?; let canonical = fact["canonicalPath"].as_str().ok_or("unsafePath")?; if !paths::within(canonical, home, self.platform, self.case_sensitive) { @@ -260,9 +271,10 @@ pub(crate) fn output( input: &Value, outcome: Value, trace: Vec, + project_candidates: Vec, unmet: Vec, conflicts: Vec, ) -> Value { json!({"operationID":input["operationID"],"tool":input["tool"],"directory":input["directory"], - "outcome":outcome,"trace":trace,"unmet":unmet,"conflicts":conflicts}) + "outcome":outcome,"trace":trace,"projectCandidates":project_candidates,"unmet":unmet,"conflicts":conflicts}) } diff --git a/rust/fixtures/toolchain-global-catalog.json b/rust/fixtures/toolchain-global-catalog.json index 628581c4..dce1c746 100644 --- a/rust/fixtures/toolchain-global-catalog.json +++ b/rust/fixtures/toolchain-global-catalog.json @@ -56,6 +56,64 @@ "platform": "windows" }, "error": "plugin.toolchain.invalidDocument" + }, + { + "name": "workspace-trust-grant-normalizes-and-Preserves-tools", + "command": "toolchains.editCatalog", + "input": { + "document": "{\"version\":1,\"tools\":{\"vm\":{\"homes\":[\"C:/SDK/21\"]}}}", + "platform": "windows", + "workspaceTrust": { + "workspace": "C:\\Projects\\Sample\\", + "trusted": true + } + }, + "expected": { + "status": "ok", + "edit": { + "changed": true, + "document": "{\n \"version\": 1,\n \"tools\": {\n \"vm\": {\n \"homes\": [\n \"C:/SDK/21\"\n ]\n }\n },\n \"trustedWorkspaces\": [\n \"C:/Projects/Sample\"\n ]\n}\n", + "catalog": { + "version": 1, + "tools": { + "vm": { + "homes": [ + "C:/SDK/21" + ] + } + }, + "trustedWorkspaces": [ + "C:/Projects/Sample" + ] + } + } + } + }, + { + "name": "workspace-trust-lookup-uses-platform-case-policy", + "command": "toolchains.catalogState", + "input": { + "document": "{\"version\":1,\"tools\":{},\"trustedWorkspaces\":[\"C:/Projects/Sample\"]}", + "platform": "windows", + "workspaceRoot": "c:\\projects\\sample\\" + }, + "expected": { + "status": "ok", + "state": { + "document": { + "version": 1, + "tools": {}, + "trustedWorkspaces": [ + "C:/Projects/Sample" + ] + }, + "storage": { + "relativePath": "toolchains/global.json", + "maximumBytes": 262144 + }, + "projectCodeAllowed": true + } + } } ] } diff --git a/shared/plugins/contract/v1/toolchains/README.md b/shared/plugins/contract/v1/toolchains/README.md index 028c5c95..4146e0f5 100644 --- a/shared/plugins/contract/v1/toolchains/README.md +++ b/shared/plugins/contract/v1/toolchains/README.md @@ -1,21 +1,20 @@ # Plugin-owned toolchains: Core foundation -**Status: shared Core implemented; the macOS settings pages run both routes -read-only.** Core validates data and resolves captured facts; it does not launch -providers, probe programs, parse manager files, watch paths, write pins, or -download tools. The macOS settings host expands `discoveryPlan` scans, starts or -reuses each enabled provider's plugin backend, sends `toolchains/query` through -`lsp.toolchainRequest`, passes every raw reply with native facts to `decodeReply`, +**Status: shared Core implemented; the desktop client (macOS, Windows, and +Linux) declares `toolDefinitions` and runs declarative discovery, project +candidates, version probes, directory pins, global SDK registrations, and +explicit workspace project-code trust.** Core validates data and resolves +captured facts; it does not launch providers, probe programs, parse manager +files, watch paths, write pins, or download tools. A host that declares +`toolDefinitions` expands `discoveryPlan` scans and project-file candidates, runs the definition's version probe on executables Core returns from -`candidates`, and shows the result. Any change to a watched input reloads the -whole snapshot. Nothing is saved by these pages. A separate fresh-resolution -adapter serves macOS Build and Provider Run; settings detections are never used -as launch permits. Language-server consumers resolve their tools with their -own adapters. Windows has no -toolchain adapter and does not advertise `toolDefinitions` or -`toolchainProviders`, so Core refuses packages that require them there. -Consumer migration, the native query lifecycle and cache, pin saving and -version-manager plugins are not specified yet. The manifest shape is +`candidates` or `resolve`, and renders or launches the selected installation; +settings detections are never used as launch permits. A host that also declares +`toolchainProviders` starts or reuses each enabled provider's plugin backend, +sends `toolchains/query` through `lsp.toolchainRequest`, and passes every raw +reply with native facts to `decodeReply` (the desktop client does not declare +`toolchainProviders` yet, so packages requiring it are not offered for +installation there). The manifest shape is [plugin-manifest.schema.json](../plugin-manifest.schema.json). ## Manifest admission and registry @@ -295,7 +294,9 @@ platform,workspaceRoot,filesystem}` and accepts `workspaceRoots`, `systemInstallations`, `globalDefault`, `environment`, `commandHomes`, `projectCodeAllowed`, `providerChoices` and `fixed`. `local` defaults to an empty document. Probes are host observations `{executable,output,exitCode}` keyed by the -canonical executable a selection reports; system installations are `{tool,home}`. +executable a selection reports (canonical for external installations, lexical for +`fixed:{executable}` and `projectFile` candidates); system installations are +`{tool,home}`. Shell environment home variables and `commandHomes` come from the native login-shell adapter, not command-name guessing. An environment candidate selects only through its declared `path` layout. @@ -339,15 +340,37 @@ Conflicts require explicit choices, never plugin-ID or home-path precedence. Manual pin-only installations are not automatic candidates. Outcome is `resolved` with `{home,executable,version,provider,layer,projectCode, -environment,pathPrepend}`, `skip` with a reason, or `terminalFailure` with a reason. -Output also carries operation/tool/directory, `trace`, `unmet` and `conflicts`. +environment,pathPrepend}`, `skip` with a reason, or `terminalFailure` with a reason +(when every candidate skips without resolving, `skip.reason` retains the first +failure in resolution order, or `notFound` when every layer was empty). +Output also carries `operationID`, `tool`, `directory`, `trace`, `projectCandidates`, +`unmet` and `conflicts`. Wrapper homes may be `null`; home exports/PATH are then omitted. Project code -requires an explicit consumer authorization snapshot and is never passively -probed. This foundation rejects project programs or environment homes whose -canonical identity differs from their declared lexical identity; -complete native link-chain validation, including common venv interpreter links, -is deferred rather than silently treated as safe. Each candidate builds a fresh -environment, so rejected exports cannot leak into its successor. +requires an explicit machine-local authorization snapshot (`projectCodeAllowed: true`) +and is never passively probed; when `projectCodeAllowed` is `false` or omitted, every +`projectFile` candidate skips with `projectCodeRequiresAction` and emits no probe target. +For `projectKind: "environment"` (with `home`, such as `.venv`), `home`, every +intermediate parent directory between `home` and `path` (such as `.venv/bin` or +`.venv/Scripts`), `requires` markers inside `home`, and existing `pathPrepend` +directories must canonically stay within the workspace root and `home`. For any +installation with a home, `pathPrepend` omits directories observed as `missing`. +Unobserved directories or directories whose canonical paths escape the home fail +with `unsafePath`. The leaf executable `path` may be a regular executable file or +a single-hop or multi-hop symbolic link to a regular executable file inside or outside +the workspace (both `path` and its resolved `canonicalPath` attested as `file` with +`executable: true`), requires a version probe on the lexical `path`, and +`selection.executable` (plus `${executable}` exports) preserves the lexical `path` so +virtual environments retain their environment root (`pyvenv.cfg` / `sys.prefix`). For +`projectKind: "wrapper"` (no `home`), the resolved `canonicalPath` and `requires` markers +must remain inside the workspace root; links escaping the workspace fail closed with +`unsafePath`, while workspace-internal links preserve the lexical wrapper `path`. +`projectCandidates` lists present nearest-ancestor `projectFile` candidates as +`{candidateID,projectKind,path,home?,executable?,version?,reason?}`, emitting +`executable` only after `projectCodeAllowed: true` and containment/executable checks pass. +An optional layout whose joined native path is outside the supported path bounds is +omitted from discovery. A usable pin can still resolve in that snapshot. +Each candidate builds a fresh environment, so rejected exports cannot leak into its +successor. `checkVersion` returns `{satisfied,version}` from the definition's first regex capture. Numeric dotted components (at most eight unsigned 32-bit parts, 64 bytes) @@ -355,9 +378,11 @@ compare with trailing zeros ignored; aliases and tool-specific version syntax ar not interpreted. No match gives `version:null,satisfied:false`. `discoveryPlan` returns `{tools,limits}`. Each tool carries platform-filtered `scans`, the sorted qualified `providers` that declare it, and the definition's `homeLayouts`, -`executableLayouts`, `version` probe, `pathPrepend` templates and `environment` +`executableLayouts`, `version` probe, `pathPrepend` templates, `environment` login-shell home variables (`{variable,path}` from its platform-applicable -`environment` candidates). It neither scans, queries nor executes them; limits +`environment` candidates), and platform-filtered `projectFiles` +(`{id?,projectKind,path,home?,requires}` from its platform-applicable `projectFile` +candidates). It neither scans, queries nor executes them; limits are 256 roots, 4096 entries and 64 ancestors for the host adapter. ## Launching a tool definition @@ -390,25 +415,33 @@ expanded argv. ## Settings candidates -`candidates` reports what a settings page shows for one tool's global and -automatic layers without resolving a directory. It requires `{registry,tool, -platform,workspaceRoot,filesystem}` and accepts `workspaceRoots`, -`filesystemCaseSensitive`, `minimumVersion`, `probes`, `systemInstallations`, -`providerInstallations`, `environment`, `fixed` and `projectCodeAllowed`, with the same meaning and checks as in -`resolve`. `providerInstallations` (at most 512) are `{tool,home,provider}` rows a -host copies from `decodeReply` snapshots; `provider` must name a registry provider -`pluginID:providerID` declaring the tool, and the row keeps that attribution when -a scan reports the same canonical home. The output is -`{tool,shell,installations,skipped,selected,conflicts}`: +`candidates` reports what a settings page shows for one tool's root project +candidates, login-shell homes and automatic layer without resolving a nested +directory. It requires `{registry,tool,platform,workspaceRoot,filesystem}` and +accepts `global`, `workspaceRoots`, `filesystemCaseSensitive`, `minimumVersion`, +`probes`, `systemInstallations`, `providerInstallations`, `environment`, +`commandHomes`, `fixed` and `projectCodeAllowed`, with the same meaning and +checks as in `resolve`. `providerInstallations` (at most 512) are +`{tool,home,provider}` rows a host copies from `decodeReply` snapshots; +`provider` must name a registry provider `pluginID:providerID` declaring the +tool, and the row keeps that attribution when a scan reports the same canonical +home. The output is `{tool,project,shell,installations,skipped,selected,conflicts}`: A checked `fixed` choice without a version contributes a `probeFailed` skipped row with its executable for the native probe. An unauthorized workspace program never contributes such a target. This candidate report itself grants no authority. - -- `shell` lists each declared home variable present in `environment` as - `{candidateID,variable,home,executable?,version?|reason?}`, checked through - the candidate's own `path` layout. -- `installations` are eligible host-scanned homes `{home,executable,version, +- `project` lists `projectFile` candidates present at `workspaceRoot` (empty when + `global: true`) as `{candidateID,projectKind,path,home?,executable?,version?, + reason?}`. When `projectCodeAllowed` is not `true`, `reason` is + `projectCodeRequiresAction` and `executable` is omitted so the host never probes + workspace code; once trusted and containment checks pass, `executable` carries + the lexical path to probe and `project` stays separate from `installations`. +- `shell` lists each declared home variable present in `environment` and each + declared command present in `commandHomes` as + `{candidateID,variable?|command?,home,executable?,version?|reason?}`. A shell + home that checks out is also offered once per canonical home in `installations` + with provider `host:shell`. +- `installations` are eligible installations `{home,executable,version, provider}`, highest version first, with the canonical home Core checked. - `skipped` lists homes that failed a check as `{home,provider,reason, executable?}`; reasons are stable codes such as `unsafePath`, `probeFailed` @@ -416,12 +449,15 @@ contributes such a target. This candidate report itself grants no authority. - `selected` is the automatic-layer home, or `null`; equal highest versions in different homes leave it `null` and add an `automatic` entry to `conflicts`. -A first call without `probes` returns every checked executable as `probeFailed`. +A first call without `probes` reports `probeFailed` for checked executables +that require a version. A wrapper can resolve without a version unless the +caller supplies a minimum. The host runs only those executables with the definition's probe arguments, -then calls again with their `{executable,output,exitCode}`. Homes inside a -workspace root are refused before any probe, so a project program is never run -to read its version. The macOS host bounds probes by count, concurrency and -total time, and reports skipped work as diagnostics rather than a missing tool. +then calls again with their `{executable,output,exitCode}`. External homes inside a +workspace root and untrusted `projectFile` candidates are refused before any probe, +so a project program is never run passively to read its version. The desktop host +bounds probes by count, concurrency and total time, and reports skipped work as +diagnostics rather than a missing tool. Production-shape examples are [tool-definition.plugin.json](../fixtures/toolchains/tool-definition.plugin.json) and [toolchain-provider.plugin.json](../fixtures/toolchains/toolchain-provider.plugin.json). diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 7442de5b..5df6241d 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -4,9 +4,9 @@ ## 中文 -本页把插件会碰到的所有版本号放在一起:`pluginAPIVersion`、清单格式、各项能力、进程协议和文档格式。**它们现在的版本全部是 `0`。** 规范以 [`contract/v1/README.md`](../contract/v1/README.md) 的 [Versioning](../contract/v1/README.md#versioning)、[Capabilities](../contract/v1/README.md#capabilities)、[Host capabilities](../contract/v1/README.md#host-capabilities) 和 [Publishing](../contract/v1/README.md#publishing) 为准;本页与契约不一致时以契约为准,并请到 [Lithe-core-rust 的 Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues) 反馈。 +本页把插件会碰到的所有版本号放在一起:`pluginAPIVersion`、清单格式、各项能力、进程协议和文档格式。**它们都从 `0` 开始(仅下表显式列出 `1` 的能力已有新版本)。** 规范以 [`contract/v1/README.md`](../contract/v1/README.md) 的 [Versioning](../contract/v1/README.md#versioning)、[Capabilities](../contract/v1/README.md#capabilities)、[Host capabilities](../contract/v1/README.md#host-capabilities) 和 [Publishing](../contract/v1/README.md#publishing) 为准;本页与契约不一致时以契约为准,并请到 [Lithe-core-rust 的 Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues) 反馈。 -Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-model/src/capabilities.rs) 的 `SUPPORTED_CAPABILITIES`,[`plugin-manifest/src/lib.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-manifest/src/lib.rs) 的 `SUPPORTED_PLUGIN_API_VERSIONS`);Lithe 桌面端列以桌面端的[声明与说明](https://github.com/1lck/Lithe-IDEA/blob/preview/desktop/internal/pluginhost/pluginhost.go)为准。Core 能校验不等于宿主能运行:宿主未声明的能力不会提供给插件,市场按实际声明筛选版本。 +Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-model/src/capabilities.rs) 的 `SUPPORTED_CAPABILITIES`,[`plugin-manifest/src/lib.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-manifest/src/lib.rs) 的 `SUPPORTED_PLUGIN_API_VERSIONS`);Lithe 桌面端列以桌面端的[声明与说明](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go)为准。Core 能校验不等于宿主能运行:宿主未声明的能力不会提供给插件,市场按实际声明筛选版本。 ### 四类版本号 @@ -45,17 +45,17 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `languageServers` `0` | `languageServers[]`(启动字段按[启动进程](../contract/v1/README.md#process-start)),包括[`workspaceConfiguration`](../contract/v1/README.md#workspace-configuration)、[`indexingExclusions`](../contract/v1/README.md#indexing-exclusions)和[插件自有服务器的会话字段](../contract/v1/README.md#plugin-owned-sessions) | ✅ | ✅¹ | [语言](domains/languages.md)、[Language servers](../contract/v1/README.md#language-servers) | | `executionProviders` `0` | `executionProviders[]`:用声明的命令运行和发现测试 | ✅ | 未声明 | [语言](domains/languages.md)、[Execution providers](../contract/v1/README.md#execution-providers) | | `settings` `0` | `settings[]` 与 `settingActions[]`,含[放置位置、作用域、生效方式、页面按钮](../contract/v1/README.md#placement-scope-effect-and-page-buttons) | ✅ | ✅ | [插件设置](domains/settings.md)、[Plugin settings](../contract/v1/README.md#plugin-settings) | -| `sourceSettings` `0` | 真实配置来源表单、编译器页、私有暂存与显式保存 | ✅ | 待宿主接入 / Pending host integration | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | -| `sourceSettings` `1` | 在 `0` 之上加:模块列表布局 `sidebar`(来源可用 `parent` 嵌套)、字段 `section`(标签页或小标题)、有序类型化条目列表 `entryList`(添加菜单、文件/目录选择器、可选项、按条目的属性列) | ✅ | 待宿主接入 / Pending host integration | [Entry lists](../contract/v1/README.md#source-backed-settings-editors) | +| `sourceSettings` `0` | 真实配置来源表单、编译器页、私有暂存与显式保存 | ✅ | ✅ | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | +| `sourceSettings` `1` | 在 `0` 之上加:模块列表布局 `sidebar`(来源可用 `parent` 嵌套)、字段 `section`(标签页或小标题)、有序类型化条目列表 `entryList`(添加菜单、文件/目录选择器、可选项、按条目的属性列) | ✅ | ✅ | [Entry lists](../contract/v1/README.md#source-backed-settings-editors) | | `ui` `0` | [`ui`](../contract/v1/README.md#host-owned-workbench-ui):文本、[包内网页](../contract/v1/README.md#web-content)和[原生控件](../contract/v1/README.md#host-rendered-native-content)的工具窗口、命令,以及[不打开工具窗口的后端命令](../contract/v1/README.md#backend-only-commands) | ✅ | ✅¹ | [界面](domains/ui.md) | | `buildSystems` `0` | 不带 `provider` 的 [`buildSystems[]`](../contract/v1/README.md#build-systems):检测、选项、项目模型、任务、运行入口、测试、诊断、依赖、同步和[声明式项目准备](../contract/v1/README.md#declarative-project-preparation) | ✅ | ✅¹ | [声明式构建系统](domains/build-systems.md) | | `buildProviders` `0` | `buildSystems[].provider`:[构建提供者](../contract/v1/README.md#build-providers),可以是自有进程或共享语言服务器;说 `litheBuild`,包含任务执行、测试执行与发现、运行准备、原生调试准备、原生配置、内联测试报告、语义测试选择器、类型化运行选项和注册表连接调试 | ✅ | ✅¹ | [构建提供者](domains/build-providers.md) | | `buildProviders` `1` | 在 `0` 之上加:运行声明 `entrypoints: true`(入口运行,不需要目标),提供者用 `lithe/build/runEntrypoints` 回答一个源文件里可运行的入口,宿主把它保存为运行配置并按入口启动 | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `buildModelInputs` `0` | `buildSystems[].modelSharing` 与 `modelInputs`:[已启用工作区插件之间共享的只读模型输入](../contract/v1/README.md#optional-read-only-model-inputs)(可选) | ✅ | 未声明 | [构建提供者](domains/build-providers.md) | | `runConfigurationTypes` `0` | `buildSystems[].runConfigurationTypes`:插件声明的运行配置类型(如 Go Build、Go Test),宿主按声明的字段画编辑器,Core 用 `build.runConfigurationPlan` 把保存的配置展开成命令行;所有运行配置共用“允许多个实例”开关 | ✅ | 未声明 | [Run configuration types](../contract/v1/README.md#run-configuration-types) | -| `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers);说 `litheVcs` | ✅ | 未声明 | [版本控制提供者](domains/vcs.md) | +| `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers);说 `litheVcs` | ✅ | ✅¹ | [版本控制提供者](domains/vcs.md) | | `debugAdapters` `0` | [`debugAdapters[]`](../contract/v1/README.md#debug-adapters):独立适配器、语言服务器内的适配器、[远程附加](../contract/v1/README.md#remote-attach)、参数和环境变量、[`features` 与 `defaults`](../contract/v1/README.md#adapter-features-and-defaults) | ✅ | ✅ | [调试适配器](domains/debug-adapters.md) | -| `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers):用插件已依赖的工具安装 `systemCommand` 启动缺的裸命令,装到 Lithe 管理的目录(`managed`)或工具默认位置(`toolDefault`),用户确认后才运行 | ✅ | 未声明 | [工具链](domains/toolchains.md#安装缺失的命令) | +| `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers):用插件已依赖的工具安装 `systemCommand` 启动缺的裸命令,装到 Lithe 管理的目录(`managed`)或工具默认位置(`toolDefault`),用户确认后才运行 | ✅ | ✅ | [工具链](domains/toolchains.md#安装缺失的命令) | | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers):插件声明的匹配规则让 Run 和测试控制台的输出出现链接;Core 负责匹配,`resolve` 函数在点击时才调用 | ✅ | ✅ | [语言](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators):新建项目窗口里的条目,含 [`tool` 字段](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [项目生成器](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend):插件自己的长驻进程,带或不带页面启动,按权限提供宿主服务,说 `litheFunctions` | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | @@ -64,12 +64,13 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `pluginFunctions` `0` | 清单顶层 [`pluginFunctions`](../contract/v1/README.md#cross-plugin-calls):导出的函数(`exports`)和要调用的其他插件函数(`calls`);不授予任何清单权限,调用经 Core 中转 | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | | `keymapImportProviders` `0` | `keymapImportProviders[]`:[独立的快捷键导入提供者](../contract/v1/README.md#shortcut-import-providers-core-foundation);说 `litheKeymapImport` | ✅ | 未声明 | [快捷键导入](domains/keymap-import.md) | -¹ 桌面端声明了这个能力,但其中有些部分还没有界面:对应的部分没有按钮、菜单或窗口,插件照常安装,也不会因此失败。尚未呈现的部分以桌面端源码里 `Declared()` 上方的注释为准([`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/preview/desktop/internal/pluginhost/pluginhost.go)): +¹ 桌面端声明了这个能力,但其中有些部分还没有界面:对应的部分没有按钮、菜单或窗口,插件照常安装,也不会因此失败。尚未呈现的部分以桌面端源码里 `Declared()` 上方的注释为准([`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go)): -- 语言服务器只呈现诊断;补全、悬停、跳转、重命名和格式化没有编辑器界面;启动应答 `{kind: "tool"}` 会被拒绝。 -- 系统命令的工具发现只读 `PATH`;依赖项目工具链或用户覆盖的计划会被拒绝。 -- 构建提供者的运行准备、测试、调试准备、模型输入、原生配置、内联测试报告和运行期调试;构建系统的实例选项和任务准备。 +- 语言服务器的代码操作(code actions)、签名帮助(signature help)和内嵌提示(inlay hints)尚未呈现,插件的 `foldingRange` 提供者未路由;诊断、补全、悬停、定义、引用、重命名、格式化、文档符号、文档链接和语义高亮均已呈现,`{kind: "tool"}` 启动按工作区工具链解析。 +- `systemCommand` 启动的命令查找只读 `PATH` 和插件已安装的受管命令目录;依赖项目工具链或用户覆盖的启动应使用 `tool` 启动。 +- 构建提供者的调试准备、模型输入、原生配置、内联测试报告和运行期调试;构建系统的实例选项和任务准备。 - 不属于任何工具窗口的 `ui` 命令。 +- VCS 提供者的逐行追溯(annotation)、文件历史、文件操作、元数据监听、认证、历史提交差异、项目树与编辑器行号栏状态,以及 `lithe/vcs/execution` 控制台输出。 - 后端宿主服务:工作区文件与搜索(`workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText`)和 `preview/openHTML` 尚未注册,请求这些权限的插件被拒绝。运行期以 `lithe/host/getCapabilities` 的返回为准,见 [API 总表](api-catalog.md)。 ### 进程协议版本 @@ -81,7 +82,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `litheFunctions` `0`(`backend`) | 插件函数:注册、撤回、调用、结果、进度、取消;宿主服务 `lithe/host/*`(凭据、工作区上下文与能力发现、宿主通知、公共文档/文件/窗口方法、插件自有原生终端、独立编辑器动作、编辑器语言功能 Provider、运行与调试会话、语言服务器方法、内容提供者);跨插件调用 `functions/providers`、`functions/invoke`。提供给插件拥有的会话 | ✅ | ✅¹ | [Plugin functions](../contract/v1/README.md#plugin-functions) | | `litheBuild` `0`(`buildProviders`) | `lithe/build/*`:模型与依赖、任务执行、测试执行与发现、运行准备、原生调试准备、只读模型输入、原生配置、内联测试报告、语义测试选择器、类型化运行选项、注册表连接调试。提供给构建提供者 | ✅ | ✅¹ | [Build providers](../contract/v1/README.md#build-providers) | | `litheBuild` `1`(`buildProviders`) | 在 `0` 之上加 `lithe/build/runEntrypoints`:按源文件找运行入口 | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | -| `litheVcs` `0`(`vcsProviders`) | VCS 提供者的能力和请求(`lithe/vcs/*`)。提供给 VCS 提供者 | ✅ | 未声明 | [VCS providers](../contract/v1/README.md#vcs-providers) | +| `litheVcs` `0`(`vcsProviders`) | VCS 提供者的能力和请求(`lithe/vcs/*`)。提供给 VCS 提供者 | ✅ | ✅¹ | [VCS providers](../contract/v1/README.md#vcs-providers) | | `litheToolchains` `0`(`toolchainProviders`) | `toolchains/query`;后端从声明的提供者中选出子集。提供给声明了工具链提供者的插件会话 | ✅ | 未声明 | [Provider backend negotiation](../contract/v1/toolchains/README.md#provider-backend-negotiation) | | `litheKeymapImport` `0`(`keymapImportProviders`) | 后端从声明的提供者中选出要启用的子集;`lithe/keymap/import`。提供给声明了 `keymapImportProviders` 的插件会话 | ✅ | 未声明 | [Shortcut import](../contract/v1/README.md#shortcut-import-providers-core-foundation) | | `litheLogging` `0`(`pluginAPIVersion`) | 结构化诊断通知 `lithe/log`;官方 SDK 要求宿主提供它,否则拒绝初始化。提供给每个插件拥有的进程 | ✅ | ✅ | [Structured diagnostics](../contract/v1/README.md#structured-plugin-diagnostics) | @@ -113,9 +114,9 @@ Node.js SDK 0.5.0、Java SDK 0.5.0 和 Rust SDK 0.4.0 说的是版本 `0` 的协 ## English -This page puts every version number a plugin meets in one place: `pluginAPIVersion`, the manifest format, the capabilities, the process protocols, and the document formats. **Every one of them is `0`.** The normative text is [Versioning](../contract/v1/README.md#versioning), [Capabilities](../contract/v1/README.md#capabilities), [Host capabilities](../contract/v1/README.md#host-capabilities), and [Publishing](../contract/v1/README.md#publishing) in [`contract/v1/README.md`](../contract/v1/README.md). Where this page disagrees with the contract, the contract wins; please report it in the [Lithe-core-rust issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues). +This page puts every version number a plugin meets in one place: `pluginAPIVersion`, the manifest format, the capabilities, the process protocols, and the document formats. **Every version starts at `0` (only capabilities explicitly listed at `1` below have a newer version).** The normative text is [Versioning](../contract/v1/README.md#versioning), [Capabilities](../contract/v1/README.md#capabilities), [Host capabilities](../contract/v1/README.md#host-capabilities), and [Publishing](../contract/v1/README.md#publishing) in [`contract/v1/README.md`](../contract/v1/README.md). Where this page disagrees with the contract, the contract wins; please report it in the [Lithe-core-rust issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues). -The Core column follows the Core source on this repository's `main` (`SUPPORTED_CAPABILITIES` in [`capabilities.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-model/src/capabilities.rs), `SUPPORTED_PLUGIN_API_VERSIONS` in [`plugin-manifest/src/lib.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-manifest/src/lib.rs)); the Lithe desktop column follows the desktop client's [declarations and notes](https://github.com/1lck/Lithe-IDEA/blob/preview/desktop/internal/pluginhost/pluginhost.go). Validating a capability is not running it: the marketplace offers only versions whose requirements the host declares. +The Core column follows the Core source on this repository's `main` (`SUPPORTED_CAPABILITIES` in [`capabilities.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-model/src/capabilities.rs), `SUPPORTED_PLUGIN_API_VERSIONS` in [`plugin-manifest/src/lib.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-manifest/src/lib.rs)); the Lithe desktop column follows the desktop client's [declarations and notes](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go). Validating a capability is not running it: the marketplace offers only versions whose requirements the host declares. ### Four kinds of version @@ -154,17 +155,17 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `languageServers` `0` | `languageServers[]` (launch fields as in [Process start](../contract/v1/README.md#process-start)), including [`workspaceConfiguration`](../contract/v1/README.md#workspace-configuration), [`indexingExclusions`](../contract/v1/README.md#indexing-exclusions) and the [session fields for a plugin's own server](../contract/v1/README.md#plugin-owned-sessions) | ✅ | ✅¹ | [Languages](domains/languages.md), [Language servers](../contract/v1/README.md#language-servers) | | `executionProviders` `0` | `executionProviders[]`: run and discover tests through the declared commands | ✅ | Not declared | [Languages](domains/languages.md), [Execution providers](../contract/v1/README.md#execution-providers) | | `settings` `0` | `settings[]` and `settingActions[]`, with [placement, scope, effect, and page buttons](../contract/v1/README.md#placement-scope-effect-and-page-buttons) | ✅ | ✅ | [Plugin settings](domains/settings.md), [Plugin settings](../contract/v1/README.md#plugin-settings) | -| `sourceSettings` `0` | Native source forms, compiler pages, private staging and explicit Save | ✅ | 待宿主接入 / Pending host integration | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | -| `sourceSettings` `1` | Adds to `0`: the `sidebar` module-list layout with sources nested by `parent`, field `section`s shown as tabs or subheadings, and ordered typed `entryList`s with an add menu, file and folder pickers, offered choices and per-entry attribute columns | ✅ | 待宿主接入 / Pending host integration | [Entry lists](../contract/v1/README.md#source-backed-settings-editors) | +| `sourceSettings` `0` | Native source forms, compiler pages, private staging and explicit Save | ✅ | ✅ | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | +| `sourceSettings` `1` | Adds to `0`: the `sidebar` module-list layout with sources nested by `parent`, field `section`s shown as tabs or subheadings, and ordered typed `entryList`s with an add menu, file and folder pickers, offered choices and per-entry attribute columns | ✅ | ✅ | [Entry lists](../contract/v1/README.md#source-backed-settings-editors) | | `ui` `0` | [`ui`](../contract/v1/README.md#host-owned-workbench-ui): text, [web](../contract/v1/README.md#web-content), and [native](../contract/v1/README.md#host-rendered-native-content) tool windows, commands, and [backend-only commands](../contract/v1/README.md#backend-only-commands) without a tool window | ✅ | ✅¹ | [UI](domains/ui.md) | | `buildSystems` `0` | [`buildSystems[]`](../contract/v1/README.md#build-systems) without `provider`: detection, options, project model, tasks, run entries, tests, diagnostics, dependencies, sync, and [declarative preparation](../contract/v1/README.md#declarative-project-preparation) | ✅ | ✅¹ | [Declarative build systems](domains/build-systems.md) | | `buildProviders` `0` | `buildSystems[].provider`: [build providers](../contract/v1/README.md#build-providers), in their own process or a shared language server; they speak `litheBuild`, which covers task execution, test execution and discovery, run preparation, native debug preparation, native configuration, inline test reports, semantic test selectors, typed run options, and registry connection debugging | ✅ | ✅¹ | [Build providers](domains/build-providers.md) | | `buildProviders` `1` | Adds to `0`: run declarations with `entrypoints: true` (entrypoint runs, without a target); the provider answers `lithe/build/runEntrypoints` with the runnable entrypoints of one source file, which the host saves as run configurations and starts | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `buildModelInputs` `0` | `buildSystems[].modelSharing` and `modelInputs`: [optional read-only model inputs](../contract/v1/README.md#optional-read-only-model-inputs) shared between enabled workspace plugins | ✅ | Not declared | [Build providers](domains/build-providers.md) | | `runConfigurationTypes` `0` | `buildSystems[].runConfigurationTypes`: run configuration types a plugin declares (such as Go Build and Go Test); the host draws the editor from the declared fields and Core expands a saved configuration into a command line with `build.runConfigurationPlan`; every run configuration shares the Allow multiple instances switch | ✅ | Not declared | [Run configuration types](../contract/v1/README.md#run-configuration-types) | -| `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers); they speak `litheVcs` | ✅ | Not declared | [VCS providers](domains/vcs.md) | +| `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers); they speak `litheVcs` | ✅ | ✅¹ | [VCS providers](domains/vcs.md) | | `debugAdapters` `0` | [`debugAdapters[]`](../contract/v1/README.md#debug-adapters): standalone adapters, adapters inside a language server, [remote attach](../contract/v1/README.md#remote-attach), arguments and environment, [`features` and `defaults`](../contract/v1/README.md#adapter-features-and-defaults) | ✅ | ✅ | [Debug adapters](domains/debug-adapters.md) | -| `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers): install a bare command a `systemCommand` launch lacks with a tool the plugin already requires, into a directory Lithe manages (`managed`) or the tool's default location (`toolDefault`), only after the user confirms | ✅ | Not declared | [Toolchains](domains/toolchains.md#installing-missing-commands) | +| `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers): install a bare command a `systemCommand` launch lacks with a tool the plugin already requires, into a directory Lithe manages (`managed`) or the tool's default location (`toolDefault`), only after the user confirms | ✅ | ✅ | [Toolchains](domains/toolchains.md#installing-missing-commands) | | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers): plugin-declared patterns that turn Run and Test console output into links; Core does the matching, and the `resolve` function is called only on click | ✅ | ✅ | [Languages](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators): entries of the New Project window, including [`tool` fields](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [Project generators](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend): the plugin's own long-lived process, started with or without a page, serving the host services its permissions grant and speaking `litheFunctions` | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | @@ -173,12 +174,13 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `pluginFunctions` `0` | The manifest's top-level [`pluginFunctions`](../contract/v1/README.md#cross-plugin-calls): the functions the plugin exports (`exports`) and the functions of other plugins it calls (`calls`); grants no manifest permission, and Core relays the calls | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | | `keymapImportProviders` `0` | `keymapImportProviders[]`: [independent shortcut import providers](../contract/v1/README.md#shortcut-import-providers-core-foundation); they speak `litheKeymapImport` | ✅ | Not declared | [Shortcut import](domains/keymap-import.md) | -¹ The desktop client declares this capability, but some of its parts have no surface yet: the missing part has no button, menu, or window, and the plugin installs and does not fail because of it. The notes above `Declared()` in the desktop source are authoritative for what is not presented ([`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/preview/desktop/internal/pluginhost/pluginhost.go)): +¹ The desktop client declares this capability, but some of its parts have no surface yet: the missing part has no button, menu, or window, and the plugin installs and does not fail because of it. The notes above `Declared()` in the desktop source are authoritative for what is not presented ([`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go)): -- Language servers present only diagnostics; completion, hover, navigation, rename, and formatting have no editor surface; a launch answer of `{kind: "tool"}` is refused. -- Tool discovery for system commands reads `PATH` only; a plan that depends on a project toolchain or a user override is refused. -- For build providers: run preparation, tests, debug preparation, model inputs, native configuration, inline test reports, and runtime debugging; for build systems: instance options and task preparations. +- For language servers: code actions, signature help, and inlay hints have no editor surface yet, and a plugin's `foldingRange` provider is not routed; diagnostics, completion, hover, definition, references, rename, formatting, document symbols, document links, and semantic tokens are presented, and `{kind: "tool"}` launches resolve through the workspace toolchain. +- Command lookup for `systemCommand` launches reads `PATH` and the plugin's installed command directories only; a launch that depends on a project toolchain or a user override must use a `tool` launch. +- For build providers: debug preparation, model inputs, native configuration, inline test reports, and runtime debugging; for build systems: instance options and task preparations. - `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. At runtime, the reply of `lithe/host/getCapabilities` is authoritative; see the [API catalog](api-catalog.md). ### Process protocol versions @@ -190,7 +192,7 @@ These protocols are negotiated when a process starts and never appear in the man | `litheFunctions` `0` (`backend`) | Plugin functions: register, withdraw, invoke, results, progress, cancellation; the `lithe/host/*` host services (credentials, workspace contexts and capability discovery, host notifications, public document, file, and window methods, plugin-owned native terminals, independent editor actions, editor language-feature providers, run and debug sessions, language server methods, content providers); cross-plugin calls `functions/providers` and `functions/invoke`. Offered to plugin-owned sessions | ✅ | ✅¹ | [Plugin functions](../contract/v1/README.md#plugin-functions) | | `litheBuild` `0` (`buildProviders`) | `lithe/build/*`: model and dependencies, task execution, test execution and discovery, run preparation, native debug preparation, read-only model inputs, native configuration, inline test reports, semantic test selectors, typed run options, registry connection debugging. Offered to build providers | ✅ | ✅¹ | [Build providers](../contract/v1/README.md#build-providers) | | `litheBuild` `1` (`buildProviders`) | Adds `lithe/build/runEntrypoints` to `0`: the run entrypoints of a source file | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | -| `litheVcs` `0` (`vcsProviders`) | VCS provider capabilities and requests (`lithe/vcs/*`). Offered to VCS providers | ✅ | Not declared | [VCS providers](../contract/v1/README.md#vcs-providers) | +| `litheVcs` `0` (`vcsProviders`) | VCS provider capabilities and requests (`lithe/vcs/*`). Offered to VCS providers | ✅ | ✅¹ | [VCS providers](../contract/v1/README.md#vcs-providers) | | `litheToolchains` `0` (`toolchainProviders`) | `toolchains/query`; the backend selects a subset of its declared providers. Offered to plugin sessions that declare toolchain providers | ✅ | Not declared | [Provider backend negotiation](../contract/v1/toolchains/README.md#provider-backend-negotiation) | | `litheKeymapImport` `0` (`keymapImportProviders`) | The backend selects a subset of its declared providers; `lithe/keymap/import`. Offered to plugin sessions with declared `keymapImportProviders` | ✅ | Not declared | [Shortcut import](../contract/v1/README.md#shortcut-import-providers-core-foundation) | | `litheLogging` `0` (`pluginAPIVersion`) | Structured diagnostic notification `lithe/log`; the official SDKs require the host to offer it and refuse to initialize otherwise. Offered to every plugin-owned process | ✅ | ✅ | [Structured diagnostics](../contract/v1/README.md#structured-plugin-diagnostics) | diff --git a/shared/plugins/reference/domains/toolchains.md b/shared/plugins/reference/domains/toolchains.md index ba426559..7c41869f 100644 --- a/shared/plugins/reference/domains/toolchains.md +++ b/shared/plugins/reference/domains/toolchains.md @@ -36,7 +36,7 @@ | 层 | 规则 | | --- | --- | | 固定(pin) | 最近的祖先目录的固定;只按完整路径段匹配,前缀相似的兄弟目录不继承 | -| 项目 | 最近的声明目录;同一深度 wrapper > 环境变量 > 声明;同一来源里原生读取器优先于兼容读取器。离得近的项目要求遮住更上层的要求 | +| 项目 | 最近的声明目录;同一深度 wrapper > 项目环境(如 `.venv`) > 提供者声明;同一来源里原生读取器优先于兼容读取器。离得近的项目要求遮住更上层的要求。项目候选必须经本机显式信任(`projectCodeAllowed: true`),否则跳过且不运行探针;项目环境的根目录、中间父目录(如 `bin`/`Scripts`)、环境内 `requires` 标记与存在的 `pathPrepend` 目录不得软链逃逸环境或工作区,而叶子可执行文件允许是指向工作区内或工作区外常规可执行文件的单跳/多跳符号链接,校验通过后保留字面路径(如 `/.venv/bin/python`);wrapper 链接目标仍必须留在工作区根之内 | | 全局 | Lithe 的全局默认 > 没有歧义(或用户已选)的提供者全局默认 > 登录 shell | | 自动 | 已安装、满足最低版本的最高版本。只用于固定的安装不参与自动选择。不同主目录有相同最高版本时算冲突,要求用户选择 | @@ -61,11 +61,11 @@ | `toolchains.decodeReply` | 查询请求、提供者应答、宿主观察到的文件系统事实 | `snapshot` | 校验一次 `toolchains/query` 应答,得到 `{installations, statements, watch, diagnostics}` | | `toolchains.failureReply` | `{params, code}` | `reply` | 查询没有应答时生成对应的 JSON-RPC 错误;`code` 只能是 `plugin.toolchain.timeout` 或 `plugin.toolchain.providerUnavailable` | | `toolchains.resolvePins` | `{document, directory, tool}` | `resolution` | 在 `local.json` 里找最近的固定,返回 `{pin, sourceDirectory}` | -| `toolchains.resolve` | 某个目录的完整解析输入 | `resolution` | 走四层选择,结果是 `resolved`、`skip` 或 `terminalFailure`,附带 `trace`、`unmet`、`conflicts` | +| `toolchains.resolve` | 某个目录的完整解析输入 | `resolution` | 走四层选择,结果是 `resolved`、`skip` 或 `terminalFailure`,附带 `trace`、`projectCandidates`、`unmet`、`conflicts` | | `toolchains.checkVersion` | `{registry, tool, output, minimumVersion?}` | `version` | 用定义的版本正则取版本并比较;最多 8 段数字、64 字节,不解释别名 | | `toolchains.instantiateLaunch` | `{registry, tool, executable, home?, entry?, runtimeArguments, arguments}` | `launch` | 按工具定义的 `launch` 模板,为宿主选中的可执行文件展开启动参数,返回 `{executable, arguments, versionArguments}`;见“按工具定义 ID 启动进程” | -| `toolchains.discoveryPlan` | `{registry, platform}` | `plan` | 每个工具的扫描计划和声明它的提供者;最多 256 个根目录、4096 个条目、64 层祖先 | -| `toolchains.candidates` | 设置页的发现输入 | `candidates` | 设置页显示的全局层和自动层:`{tool, shell, installations, skipped, selected, conflicts}`;第一次调用把待探测的可执行文件列为 `probeFailed`,宿主运行探针后再调用一次 | +| `toolchains.discoveryPlan` | `{registry, platform}` | `plan` | 每个工具的扫描计划、声明它的提供者、登录 shell 变量和平台过滤后的 `projectFiles`;最多 256 个根目录、4096 个条目、64 层祖先 | +| `toolchains.candidates` | 设置页的发现输入 | `candidates` | 设置页显示的根级项目候选、登录 shell 和自动层:`{tool, project, shell, installations, skipped, selected, conflicts}`;未授权项目候选不给出待探测 `executable`,已授权且安全校验通过后首次调用把待探测可执行文件列为 `probeFailed`,宿主运行探针后再调用一次 | ### 提供者应答的限制 @@ -124,17 +124,17 @@ ### 本机文档 -`.lithe/toolchains/local.json` 的 `version` 仍为 `1`,这是 Core 当前校验的格式。`toolchains.resolvePins` 校验 `{version: 1, toolchains, pins?}`,`pins` 按目录记录 `{home, version, provider}`。这个文档只读取,不授予执行权限,也不写文件;保存固定尚未实现。 +`.lithe/toolchains/local.json` 的 `version` 为 `1`,`toolchains.resolvePins` / `editPins` / `editPinSources` 校验并按条件更新目录级固定 `{home, version, provider}`,不授予项目代码执行权限。本机应用存储目录下的 `toolchains/global.json`(经 `toolchains.catalogState` / `editCatalog` 管理)保存本机注册的 SDK 目录、全局默认以及显式信任的工作区根路径 `trustedWorkspaces`(绝不写进工作区 `.lithe/`)。 ### 桌面端现状 | 用途 | Lithe 桌面端 | | --- | --- | -| 工具定义(`toolDefinitions`) | 已声明。设置页的发现结果,以及构建和运行选择工具,都通过共享 Core 解析器完成 | +| 工具定义(`toolDefinitions`) | 已声明(macOS、Windows、Linux)。设置页发现、项目环境信任、目录固定保存,以及构建、运行、调试、语言服务器和新建项目选择工具,都通过共享 Core 解析器完成 | | 工具链提供者(`toolchainProviders`) | 未声明。提供者查询路线不可用,需要它的插件不会被提供安装 | -| 安装缺失的命令(`commandInstallers`) | 未声明 | -| 语言服务器的 `{kind: "tool"}` 启动应答 | 启动时被拒绝,因为工具还没有经过工具链注册表解析(见[语言](languages.md)) | -| 保存固定(pin)、`toolchainConsumers`、通用运行时启动、提供者热激活 | 契约尚未提供 | +| 安装缺失的命令(`commandInstallers`) | 已声明。插件管理页展示工具、命令行、网络与目标目录,用户确认后安装到受管目录或工具默认目录 | +| 语言服务器的 `{kind: "tool"}` 启动 | 按工作区工具链四层选择解析后启动(见[语言](languages.md)) | +| `toolchainConsumers`、提供者热激活 | 契约尚未提供 | `toolchains.provide` 可以影响某个已定义工具启动哪个程序,但不授权替换任意命令、安装软件、访问网络或执行工作区代码。 @@ -209,7 +209,7 @@ The first argument of the version probe `version.arguments` is a flag (`-version | Layer | Rule | | --- | --- | | Fixed (pin) | The nearest ancestor directory's pin. Matched by whole path segments only; a sibling with a similar prefix does not inherit it | -| Project | The nearest declaring directory; at the same depth, wrapper > environment variable > declaration; within one source, the native reader beats the compatible reader. A nearer project requirement masks a higher one | +| Project | The nearest declaring directory; at the same depth, wrapper > project environment (such as `.venv`) > provider declaration; within one source, the native reader beats the compatible reader. A nearer project requirement masks a higher one. Project candidates require explicit machine-local workspace trust (`projectCodeAllowed: true`) and are never passively probed; for a project environment, `home`, intermediate parent directories (`bin` / `Scripts`), in-home `requires` markers, and existing `pathPrepend` directories must remain canonically inside `home` and the workspace, while the leaf executable may be a single-hop or multi-hop symbolic link to a regular executable inside or outside the workspace and preserves its lexical `executable` path (such as `/.venv/bin/python`); wrapper targets must remain inside the workspace root | | Global | Lithe's global default > an unambiguous (or user-chosen) provider global default > the login shell | | Automatic | The highest installed version that meets the minimum. Installations added only as pins never take part in automatic selection. Equal highest versions in different homes are a conflict that the user must resolve | @@ -234,11 +234,11 @@ Every command accepts UTF-8 JSON, has a 4 MiB input budget, and performs no nati | `toolchains.decodeReply` | The query request, the provider's reply, and the host's observed filesystem facts | `snapshot` | Validates one `toolchains/query` reply and returns `{installations, statements, watch, diagnostics}` | | `toolchains.failureReply` | `{params, code}` | `reply` | Builds the JSON-RPC error when a query gets no reply. `code` is `plugin.toolchain.timeout` or `plugin.toolchain.providerUnavailable` | | `toolchains.resolvePins` | `{document, directory, tool}` | `resolution` | Finds the nearest pin in `local.json`; returns `{pin, sourceDirectory}` | -| `toolchains.resolve` | The full resolution input for one directory | `resolution` | Runs the four layers. The result is `resolved`, `skip`, or `terminalFailure`, with `trace`, `unmet`, and `conflicts` | +| `toolchains.resolve` | The full resolution input for one directory | `resolution` | Runs the four layers. The result is `resolved`, `skip`, or `terminalFailure`, with `trace`, `projectCandidates`, `unmet`, and `conflicts` | | `toolchains.checkVersion` | `{registry, tool, output, minimumVersion?}` | `version` | Reads the version with the definition's regular expression and compares it. At most 8 numeric parts and 64 bytes; aliases are not interpreted | | `toolchains.instantiateLaunch` | `{registry, tool, executable, home?, entry?, runtimeArguments, arguments}` | `launch` | Expands the definition's `launch` template for the executable the host selected, returning `{executable, arguments, versionArguments}`; see "Launching a process by tool-definition ID" | -| `toolchains.discoveryPlan` | `{registry, platform}` | `plan` | Each tool's scan plan and the providers that declare it. Limits: 256 roots, 4096 entries, 64 ancestors | -| `toolchains.candidates` | The settings page's discovery input | `candidates` | The global and automatic layers shown on a settings page: `{tool, shell, installations, skipped, selected, conflicts}`. The first call lists executables to probe as `probeFailed`; the host runs the probes and calls again | +| `toolchains.discoveryPlan` | `{registry, platform}` | `plan` | Each tool's scan plan, the providers that declare it, login-shell variables, and platform-filtered `projectFiles`. Limits: 256 roots, 4096 entries, 64 ancestors | +| `toolchains.candidates` | The settings page's discovery input | `candidates` | Root project candidates, login-shell homes, and the automatic layer shown on a settings page: `{tool, project, shell, installations, skipped, selected, conflicts}`. Untrusted project candidates emit no `executable` to probe; once trusted and checked, the first call lists executables to probe as `probeFailed`, and the host runs the probes and calls again | ### Limits on provider replies @@ -297,17 +297,17 @@ A `systemCommand` launch names only a bare command (such as `dlv` or `gopls`), a ### Local document -`.lithe/toolchains/local.json` keeps `version` `1`, which is the format Core validates today. `toolchains.resolvePins` validates `{version: 1, toolchains, pins?}`, where `pins` maps directory keys to `{home, version, provider}`. The document is read, not written; it grants no execution authority; saving pins is not implemented. +`.lithe/toolchains/local.json` keeps `version` `1`; `toolchains.resolvePins`, `editPins`, and `editPinSources` validate and conditionally update directory pins `{home, version, provider}`, granting no execution authority over project code. Machine-local `toolchains/global.json` under the application preference directory (managed through `toolchains.catalogState` and `editCatalog`) stores registered SDK homes, global defaults, and explicitly trusted workspace roots `trustedWorkspaces` (never written inside `.lithe/`). ### Desktop status | Use | Lithe desktop | | --- | --- | -| Tool definitions (`toolDefinitions`) | Declared. Settings discovery results, and Build and Run tool selection, go through the shared Core resolver | +| Tool definitions (`toolDefinitions`) | Declared (macOS, Windows, and Linux). Settings discovery, workspace project-environment trust, saving pins, and Build, Run, Debug, language-server, and project-generator tool selection all go through the shared Core resolver | | Toolchain providers (`toolchainProviders`) | Not declared. The provider query route is unavailable, and a plugin that needs it is not offered for installation | -| Installing missing commands (`commandInstallers`) | Not declared | -| Language server `{kind: "tool"}` launch answer | Refused at start, because the tool is not yet resolved through the toolchain registry (see [Languages](languages.md)) | -| Saving pins, `toolchainConsumers`, generic runtime launches, live provider activation | Not provided by the contract yet | +| Installing missing commands (`commandInstallers`) | Declared. Plugin management displays the tool, command line, network use, and target directory, and installs into the managed directory or tool default directory after user confirmation | +| Language server `{kind: "tool"}` launch | Resolved through the workspace's four toolchain layers and started (see [Languages](languages.md)) | +| `toolchainConsumers`, live provider activation | Not provided by the contract yet | `toolchains.provide` can influence which program a defined tool launches. It does not grant arbitrary command replacement, installation, network access, or execution of workspace code. diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 871115e4..907c0fb4 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -9,7 +9,7 @@ 时间线的两列这样读: -- **API 编号**:这个 PR 涉及的 API-01–44 规划编号,来自 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/preview/docs/development/macos-plugin-api-plan.md),和协议版本、能力版本分开记录。— 表示没有改到具体 API,例如清单、市场、包信任、SDK 或契约文档整理。 +- **API 编号**:这个 PR 涉及的 API-01–44 规划编号,来自 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md),和协议版本、能力版本分开记录。— 表示没有改到具体 API,例如清单、市场、包信任、SDK 或契约文档整理。 - **协议 / 能力**:**加粗**的是这个 PR 新增的版本号;没有加粗的,是同一版本内的补充、宿主接入或说明修正。 ## 按协议查首次出现 @@ -142,6 +142,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | | [#94](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/94) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-29 | **`runConfigurationTypes` 0** | 插件声明自己的运行配置类型([1lck/Lithe-IDEA#2100](https://github.com/1lck/Lithe-IDEA/issues/2100)):构建系统新增 `runConfigurationTypes`(最多 16 个),每个类型有 `id`、`displayName`、可选的 `description`、`execution`(`application` 或 `task`)、`arguments` 模板和最多 16 个字段 `fields`(`text`、`choice`、`checkbox`、`file`、`directory`、`arguments`,可带 `default`、`required`、`placeholder`、`visibleWhen` 和每个字段自己的 `arguments`)。新模板变量 `${field:}` 是整个参数,每个字段必须在类型参数或字段参数里恰好用一次(只控制显示、不带参数的字段除外);`${userArguments}` 恰好出现一次时,编辑器才显示程序参数。用户保存的配置类型是 `build.run-type`,`extensions.build` 记 `{pluginID, buildSystemID, type, values}`,仍存在 `.lithe/run/plugin/<插件 ID>.toml`。所有运行配置(含 Core 自带的)新增通用开关 `allowMultipleInstances`:关时再次启动先停掉正在运行的进程,开时宿主在旁边再起一个。Core 新增命令 `build.runConfigurationPlan`(把保存的配置展开成 argv 计划),`runConfig.configurationTypes`、`runConfig.editorForm`、`runConfig.saveConfiguration` 新增请求字段 `runTypePlugins`(清单和语言文件),语言文件新增 `runConfigurationTypes.<构建系统 ID>.<类型 ID>`。字段值不合法时是 `plugin.build.invalidRunConfiguration`(字段 `values.`),语言文件不合法时是 `plugin.build.invalidLocalization`。新增 fixture `run-configuration-types/`。用到它的插件声明 `runConfigurationTypes: 0`,不认识它的宿主不会安装。没有新增宿主方法或通知。 | +| [#93](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/93) | [@Mucheen](https://github.com/Mucheen) | API-23 | `toolDefinitions` 0 内的补充 | 项目内工具环境解释器符号链接链校验与项目候选返回([1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)):`projectCodeAllowed != true` 时所有 `projectFile` 候选仍以 `projectCodeRequiresAction` 跳过且不返回探针目标;`projectKind: "environment"`(如 `.venv`)要求 `home`、到可执行文件之间的父目录(如 `.venv/bin`、`.venv/Scripts`)、环境内 `requires` 标记以及实际存在的 `pathPrepend` 目录规范化后留在工作区和 `home` 内(记为 `missing` 的跨平台 `pathPrepend` 子目录忽略,未观察到或软链逃逸以 `unsafePath` 拒绝),叶子可执行文件允许是指向工作区内或工作区外常规可执行文件的单跳或多跳符号链接,探测与选中结果均保留字面 `executable` 路径;`wrapper` 仍要求链接目标留在工作区根内。`toolchains.discoveryPlan` 的每个工具新增平台过滤后的 `projectFiles`;`toolchains.candidates` 新增根级 `project` 候选列表;`toolchains.resolve` 新增 `projectCandidates`,且没有候选解析成功时保留解析顺序中的首个失败原因。最近的项目声明遮住根目录的声明,可选发现无法表示的路径会被跳过,已验证的固定选择仍可生效。项目环境和外部安装都可以省略明确观测为缺失的 PATH 目录。`toolchains.catalogState` / `editCatalog` 支持在本机 `toolchains/global.json` 维护规范化的 `trustedWorkspaces` 并查询 `projectCodeAllowed`。同步更新过时宿主能力对照说明;清单格式和能力版本不变,没有新增插件 RPC 方法或通知。 | | [#89](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/89) | [@1lck](https://github.com/1lck) | — | **`buildProviders` 1**、**`litheBuild` 1** | 按源文件找运行入口([1lck/Lithe-IDEA#2104](https://github.com/1lck/Lithe-IDEA/issues/2104)):运行声明可写 `entrypoints: true`(只能是提供者的 `application`,不写 `fromTargets`、`fromTasks`、`arguments`、`extension`、`debug`),它不对应任何目标,宿主不按目标列出它。新提供者方法 `lithe/build/runEntrypoints`(参数多一个工作区相对路径 `file`)返回 `litheRunEntrypoints` 0 文档,列出这个文件里可运行的入口 `{run, name, entrypoint, project}`,最多 64 个;Core 新增 `build.runEntrypointsPlan` 和 `build.decodeRunEntrypoints` 校验。`lithe/build/prepareRun` 对入口运行不带 `target`,必须带 `launchOptions.entrypoint`。宿主提供 `litheBuild` 版本 `[0, 1]`,三个 SDK 回答宿主提供的最新版本,Java/Node SDK 新增 `onRunEntrypoints`/`build.runEntrypoints`。用入口运行的插件声明 `buildProviders: 1`,只支持 0 的宿主不会安装;其他插件不受影响。新增 fixture `build-provider-run-entrypoints.plugin.json`、`build-run-entrypoints.json`。没有新增宿主方法或通知。 | | [#86](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/86) | [@Mucheen](https://github.com/Mucheen) | API-29 | `buildSystems` 0 内的补充 | 构建树与选项编辑支持模型提供的默认激活项、实际激活集合和取消前缀([1lck/Lithe-IDEA#2092](https://github.com/1lck/Lithe-IDEA/issues/2092))。规范模型可报告 `optionDefaults`、`optionExcludePrefixes` 和 `optionActiveChoices`。Core 按选项指纹匹配实际激活集合,保留兄弟构建根和继承值,并在生成运行条目时解析取消前缀。清单中的 `excludePrefix` 和 `model.map.optionDefaults` 需要支持这些字段的 Core。旧 Core 可忽略规范模型新增字段。宿主方法、通知和能力版本沿用现有契约。 | | [#85](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/85) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 插件清单 `schemaVersion` 0 内的补充 | 清单新增可选字段 `repository`([1lck/Lithe-IDEA#2100](https://github.com/1lck/Lithe-IDEA/issues/2100)):值是插件源码仓库的 GitHub 地址 `https://github.com/<作者>/<仓库>`,格式不对时以 `plugin.manifest.invalid`(字段 `repository`)拒绝。项目里由插件提供的 Run 配置改存 `.lithe/run/plugin/<插件 ID>.toml`(共享)和 `<插件 ID>.local.toml`(本机),文件头 `[plugin]` 记录插件 ID、名称、作者、仓库、版本、版本要求(默认 `>=保存时的版本`)、`pluginAPIVersion` 和用到的能力,作者和仓库取自 `repository`,用来区分同名插件;插件没有安装、仓库不一致或版本不满足要求时,这些配置在 Run 列表里显示为不可用并说明原因,不会让整个列表读取失败。Core 自带的脚本和程序运行(shell、PowerShell、Windows 批处理、可执行文件)不依赖任何插件。没写 `repository` 的插件照常安装,Run 文件里不记作者和仓库、也不比对仓库;清单格式和能力版本不变,没有新增宿主方法或通知。 | @@ -204,7 +205,7 @@ 修改 `shared/plugins/contract/v1/`、`rust/crates/plugin-model/src/capabilities.rs` 或 `rust/crates/plugin-rpc/src/` 的 Core PR,在**同一个 PR** 里更新本页: 1. 把这个 PR 补到时间线最上面(按合入日期分组):PR、修改人、API 编号、协议 / 能力、改了什么。新增的版本号要加粗,并写进“按协议查首次出现”里对应的表:例如给 `buildProviders` 加版本 `1`,就在能力表里为它加一行,并在进程协议表里同步 `litheBuild`。一个 PR 只给一个能力加一个版本。 -2. “API 编号”填这个 PR 涉及的全部 API-01–44 编号,取自 PR 描述里的“原计划编号”。PR 没写时按 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/preview/docs/development/macos-plugin-api-plan.md) 判断,不要自编新号;不属于任何编号的写 —。 +2. “API 编号”填这个 PR 涉及的全部 API-01–44 编号,取自 PR 描述里的“原计划编号”。PR 没写时按 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md) 判断,不要自编新号;不属于任何编号的写 —。 3. PR 新增或修改了宿主方法或通知时,每个方法在“宿主方法(按 API 编号)”表里加一行,写明 API 编号、协议、日期和 PR;同时在 [API 总表](api-catalog.md#已公开的宿主方法)的中英两张方法表里各加一行,写明用途、权限和协议。同一个 API 下的方法分几个 PR 加入时,各自登记自己的 PR。 4. “修改人”填 PR 作者的 GitHub 账号,写成 `[@账号](https://github.com/账号)`。账号可以这样查: