Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion rust/contracts/application-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ this lifecycle protection; actual symbol computation remains upstream-owned.
| GitHub | remote parsing, trusted request plans, normalized branch comparisons and pull requests/reviews/comments, deterministic ordering, and stable errors | OAuth configuration, HTTPS, browser opening, and operating-system credential storage |
| [AI commit messages](ai-commit.md) | provider configuration parsing, commit rules, bounded diff evidence, request plans, and response text | local configuration discovery, credentials, HTTP, cancellation, and draft UI |
| [IDE capability API / MCP](ide-api/v1.md) | canonical tool schemas, narrowing host selection, permission/argument validation, stable execution IDs, bounded output cursors and errors | implemented workflow inventory, explicit project authorization, live environment/Build/Run application actions, helper discovery and writable connection storage |
| Runtime | tool requirements, normalized candidates, and effective toolchain references | tool probing and executable paths |
| Runtime | tool requirements, normalized candidates, effective toolchain references, pinned managed-runtime plans and bounded resolver answers | tool probing, executable paths, approved HTTPS downloads, safe archive extraction, native integrity, interprocess cache locks and atomic set publication |
| Language tooling | provider catalog, local fallback results, complete LSP process/session runtime, capabilities, diagnostics, UTF-16 edits, and normalized feature results | executable/environment discovery and UI provider routing |
| Run/Debug | versioned configuration documents, three-layer resolution, diagnostics, platform-neutral launch plans, DAP framing/state, reverse terminal requests, breakpoint relocation, stepping filters, threads, stacks, variables, and events | project and preference persistence, native edit reporting, adapter discovery, PTY/ConPTY debuggee launch, child processes, sockets, native termination, and UI |
| Terminal | input bytes, output bytes, lifecycle; [shell selection semantics](terminal-profiles.md) | PTY/ConPTY, shell discovery, native profile preferences, and environment |
Expand Down
35 changes: 34 additions & 1 deletion rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,8 @@ or removing a command fails until the table changes in the same commit.
| `plugins.commandInstallers.requirements` | List each `systemCommand` launch of a plugin with its commands and the installer that provides each |
| `plugins.commandInstallers.plan` | Expand one command installer for the target the user chose |
| `plugins.commandInstallers.defaultDirectory` | Read where a `toolDefault` installation puts its commands from the output of its directory probes |
| `plugins.managedRuntimes.plan` | Validate pinned dependencies and select exact platform artifacts with plugin-version-independent cache identities |
| `plugins.managedRuntimes.decodeResolution` | Validate a plugin resolver's complete partition of qualified native homes and missing dependency IDs |
| `plugins.contentProviders.decode` | Bound the answer of a plugin content provider function and return the document text |
| `debug.adapters.startArguments` | Check one debug start against a plugin's `debugAdapters[]` entry and return its DAP launch arguments |
| `debug.validateAdapterEndpoint` | Validate an IDE-to-DAP TCP endpoint and classify whether remote consent is required; performs no DNS or network I/O |
Expand Down Expand Up @@ -3124,6 +3126,9 @@ optional `pluginId` of the plugin that owns the process, its optional
`workspaceConfiguration` (an object, plugin-owned sessions only), its
optional `hostServices` (the launch plan's `backend.hostServices`;
plugin-owned sessions only; legacy service grants or full public host-method names Core defines),
optional `functionRelayEnabled` (defaults to `true`; `false` keeps direct
host-to-session function calls but excludes the session from incoming and outgoing
cross-plugin routing, including the corresponding host service grants),
its optional `hostOptions` (plugin-owned sessions only; `editor:{actionIcons,
actionSourceBytes, providerTypes}` declares the icons, collector source bound and
provider types the host implements, reported through `lithe/host/getCapabilities`
Expand Down Expand Up @@ -4631,7 +4636,8 @@ function, timeoutMilliseconds }` (30000 when absent) and `resolveParams` is the
params the host sends to that backend function, `{ serverID, platform: { os,
arch }, stateDirectory, workspaceStateDirectory, logDirectory,
temporaryDirectory, settings }`; the host adds `context` and, when the plugin
declares tool definitions, `tools`. The request must carry all four of
declares tool definitions, `tools`, and after managed-runtime preparation the
optional read-only `runtimes: {<id>:{home,version}}` map. The request must carry all four of
`stateDirectory`, `workspaceStateDirectory`, `logDirectory`, and
`temporaryDirectory`, and the plan lists them in `requiredDirectories`. Every language-server plan carries a `sessionPolicy`
(`serverID`, `requestMethods`, `commands`, `serializedCommands`,
Expand Down Expand Up @@ -4689,6 +4695,33 @@ runs on. Refusals are `plugin.commandInstaller.unknown`,
`plugin.commandInstaller.probeOutputsInvalid`; the golden cases are
`shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json`.

The `plugins.managedRuntimes.*` commands implement
[Managed runtimes](../../shared/plugins/contract/v1/README.md#managed-runtimes).
`plan` accepts `{manifest, platform:{os,arch}}` and returns
`{status:"ok", plan:{resolve, dependencies:[{id,version,tool?,os,arch,url,
sha256,archive,stripPrefix,home,executable,cacheKey}]}}`. The resolver is
`{function,timeoutMilliseconds}`. No declaration produces an empty dependencies
array without a resolver. Targets are exact (`macos|windows|linux`,
`arm64|x86_64`); `cacheKey` is an opaque lowercase SHA-256 of the normalized
selected dependency identity, excluding plugin version. A host uses it as given.
`decodeResolution` accepts `{manifest, platform:{os,arch}, result}` and returns
`{status:"ok", resolution:{runtimes:[{id,home,version}],missing:[id]}}` with
both arrays sorted by ID. The arrays must partition every declared ID exactly
once; homes are bounded absolute paths for the supplied OS. Neither command
performs I/O or decides tool-specific compatibility. Refusals are
`plugin.managedRuntime.unavailable` for unsupported targets or absent artifacts,
`plugin.managedRuntime.invalidResolution` for hook output, and standard
manifest errors for declarations. The inert shared fixture is
`rust/fixtures/plugins/managed-runtimes.json`.

Hosts run the approved packaged resolver before install/update publication and
again for missing-state repair. Hooks qualify external and staged homes; native
adapters own downloads, hashing, safe extraction, process locks, integrity and
atomic publication. A backend-resolved server launch may receive the host-added
read-only `runtimes: {<id>:{home,version}}` map, and a declared tool binding is
selected only for that plugin's server session. This does not change project
toolchains or add an arbitrary absolute executable kind.

`plugins.contentProviders.decode` accepts `{ result }`, the value a plugin
function returned for a document of its content scheme, and returns
`{ content }`. `result` is a string, or an object whose only member is
Expand Down
12 changes: 12 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,10 @@ pub enum PluginsCommand {
CommandInstallersPlan,
/// Reads where a `toolDefault` installation puts its commands (`plugins.commandInstallers.defaultDirectory`).
CommandInstallersDefaultDirectory,
/// Selects pinned runtime artifacts for one target (`plugins.managedRuntimes.plan`).
ManagedRuntimesPlan,
/// Validates the plugin resolver's complete runtime partition (`plugins.managedRuntimes.decodeResolution`).
ManagedRuntimesDecodeResolution,
/// Checks a plugin content provider's answer (`plugins.contentProviders.decode`).
ContentProvidersDecode,
/// Merges a plugin's stored setting layers into effective values (`plugins.declarative.resolveSettings`).
Expand Down Expand Up @@ -1065,6 +1069,12 @@ impl CoreCommand {
"plugins.commandInstallers.defaultDirectory" => Some(Self::Plugins(
PluginsCommand::CommandInstallersDefaultDirectory,
)),
"plugins.managedRuntimes.plan" => {
Some(Self::Plugins(PluginsCommand::ManagedRuntimesPlan))
}
"plugins.managedRuntimes.decodeResolution" => Some(Self::Plugins(
PluginsCommand::ManagedRuntimesDecodeResolution,
)),
"plugins.contentProviders.decode" => {
Some(Self::Plugins(PluginsCommand::ContentProvidersDecode))
}
Expand Down Expand Up @@ -1725,6 +1735,8 @@ mod tests {
"plugins.commandInstallers.requirements",
"plugins.commandInstallers.plan",
"plugins.commandInstallers.defaultDirectory",
"plugins.managedRuntimes.plan",
"plugins.managedRuntimes.decodeResolution",
"plugins.contentProviders.decode",
"lsp.cancelOperation",
"lsp.pollEvents",
Expand Down
10 changes: 10 additions & 0 deletions rust/crates/core/src/runtime/dispatcher/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,16 @@ pub(super) fn dispatch(
payload,
lithe_plugin_manifest::command_installer_default_directory_command,
),
PluginsCommand::ManagedRuntimesPlan => plugin_response(
id,
payload,
lithe_plugin_manifest::managed_runtime_plan_command,
),
PluginsCommand::ManagedRuntimesDecodeResolution => plugin_response(
id,
payload,
lithe_plugin_manifest::managed_runtime_resolution_command,
),
PluginsCommand::ContentProvidersDecode => plugin_response(
id,
payload,
Expand Down
35 changes: 35 additions & 0 deletions rust/crates/core/src/tests/managed_runtimes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//! Managed-runtime plans and resolver answers through the public JSON boundary.

use serde_json::{json, Value};

fn execute(command: &str, payload: Value) -> Value {
serde_json::from_str(&crate::execute_json(
&json!({"command":command,"payload":payload}).to_string(),
))
.unwrap()
}

#[test]
fn managed_runtime_fixture_crosses_the_public_command_boundary() {
let fixture: Value = serde_json::from_str(include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/plugins/managed-runtimes.json"
)))
.unwrap();
let plan = execute(
"plugins.managedRuntimes.plan",
json!({"manifest":fixture["manifest"],"platform":fixture["platform"]}),
);
assert_eq!(plan["ok"], true, "{plan}");
assert_eq!(plan["data"]["status"], "ok", "{plan}");
assert_eq!(plan["data"]["plan"]["dependencies"][0]["id"], "engine");
let resolved = execute(
"plugins.managedRuntimes.decodeResolution",
json!({"manifest":fixture["manifest"],"platform":fixture["platform"],"result":fixture["resolution"]}),
);
assert_eq!(resolved["ok"], true, "{resolved}");
assert_eq!(resolved["data"]["resolution"], fixture["resolution"]);
let malformed = execute("plugins.managedRuntimes.plan", json!({}));
assert_eq!(malformed["ok"], false, "{malformed}");
assert_eq!(malformed["error"]["code"], "invalid_request");
}
1 change: 1 addition & 0 deletions rust/crates/core/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ mod installed_versions;
mod keymap_import;
mod language_server_sessions;
mod lsp_policy;
mod managed_runtimes;
mod marketplace_plugins;
mod notification_read;
mod plugin_editor_resources;
Expand Down
15 changes: 14 additions & 1 deletion rust/crates/lsp-engine/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ impl LspEngine {
),
provider_id: request.provider_id,
plugin_id: request.plugin_id,
function_relay_enabled: request.function_relay_enabled,
workspace_host: lithe_workspace::current(),
plugin_configuration: Mutex::new(workspace_configuration.map(Arc::new)),
indexing_exclusions,
Expand All @@ -208,7 +209,19 @@ impl LspEngine {
state: Mutex::new(SessionState {
lifecycle: LspLifecycleState::Created,
client: LspClientState {
host_services: request.host_services.into_iter().collect(),
host_services: request
.host_services
.into_iter()
.filter(|service| {
request.function_relay_enabled
|| !matches!(
service.as_str(),
lithe_plugin_rpc::HOST_SERVICE_FUNCTIONS
| lithe_plugin_rpc::FUNCTIONS_PROVIDERS
| lithe_plugin_rpc::FUNCTIONS_INVOKE
)
})
.collect(),
host_options: request.host_options,
..initialize.state
},
Expand Down
57 changes: 57 additions & 0 deletions rust/crates/lsp-engine/src/function_relay_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ impl Fixture {
request.plugin_id = Some(launch.plugin_id.to_string());
request.root_uri = launch.root_uri.to_string();
request.host_services = launch.host_services.clone();
request.function_relay_enabled = launch.function_relay_enabled;
let started = self
.engine
.start_server(request)
Expand Down Expand Up @@ -135,6 +136,7 @@ struct Launch {
root_uri: &'static str,
functions: Vec<&'static str>,
host_services: Vec<String>,
function_relay_enabled: bool,
}

impl Launch {
Expand All @@ -146,6 +148,7 @@ impl Launch {
root_uri: "file:///workspace",
functions: Vec::new(),
host_services: vec!["functions".to_string()],
function_relay_enabled: true,
}
}

Expand All @@ -164,6 +167,11 @@ impl Launch {
self
}

fn without_relay(mut self) -> Self {
self.function_relay_enabled = false;
self
}

fn capabilities(&self) -> Value {
let functions: Vec<Value> = self
.functions
Expand Down Expand Up @@ -513,6 +521,55 @@ fn a_call_the_host_starts_carries_no_caller() {
assert!(received.get("caller").is_none(), "{received}");
}

#[test]
fn preparation_session_is_private_even_when_its_plugin_has_an_installed_backend() {
const OWNER: &str = "dev.lithe.fixture.runtime-owner";
const CALLER: &str = "dev.lithe.fixture.runtime-caller";
let fixture = Fixture::new();
let private = fixture.start(Launch::new(OWNER).serving(&[FORMAT]).without_relay());
let installed = fixture.start(Launch::new(OWNER).serving(&[FORMAT]).at("file:///other"));
let caller = fixture.start(Launch::new(CALLER));
fixture.configure(snapshot(
vec![
plugin(CALLER, &[], &[(FORMAT, 1)]),
plugin(OWNER, &[(FORMAT, 1)], &[(FORMAT, 1)]),
],
"local",
));

// The private session shares the caller's root and was registered first.
// Neither affinity is allowed to route a call to a staged package.
caller.call("installed-call", OWNER, FORMAT);
let (wire_id, _) = installed.await_invoke();
installed.answer(&wire_id, json!({"installed":true}));
assert_eq!(
caller.reply("installed-call")["result"]["value"],
json!({"installed":true})
);
private.assert_not_invoked();

for (id, method, params) in [
(
"private-providers",
PROVIDERS,
json!({"functionID": FORMAT}),
),
("private-call", INVOKE, call_params(OWNER, FORMAT)),
] {
private.ask(id, method, params);
assert_error(&private.reply(id), "plugin.host.permissionDenied", -32010);
}
private.ask(
"private-capabilities",
"lithe/host/getCapabilities",
json!({}),
);
assert!(private.reply("private-capabilities")["result"].is_object());
private.host_call("qualification", OWNER, FORMAT).unwrap();
let (_, received) = private.await_invoke();
assert!(received.get("caller").is_none());
}

#[test]
fn a_failing_callee_keeps_its_own_error_code() {
let fixture = Fixture::new();
Expand Down
16 changes: 15 additions & 1 deletion rust/crates/lsp-engine/src/relay_hub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,15 @@ impl RelayHub {
) -> Result<Vec<String>, CoreError> {
let rpc_id = request.get("id").cloned().unwrap_or(Value::Null);
let params = request.get("params").unwrap_or(&Value::Null);
if !session.function_relay_enabled {
return Ok(vec![reply_message(
&rpc_id,
&Err(RelayFailure::new(
codes::HOST_UNAVAILABLE,
"This session is isolated from cross-plugin function routing.",
)),
)?]);
}
// Only a plugin's own session can negotiate the protocol, so a
// session without a plugin should never get here.
let Some(caller_plugin) = session.plugin_id.as_deref() else {
Expand Down Expand Up @@ -477,7 +486,9 @@ fn find_provider(
let sessions = sessions.lock().unwrap_or_else(PoisonError::into_inner);
let candidates: Vec<Arc<RuntimeSession>> = sessions
.values()
.filter(|session| session.plugin_id.as_deref() == Some(plugin_id))
.filter(|session| {
session.function_relay_enabled && session.plugin_id.as_deref() == Some(plugin_id)
})
.cloned()
.collect();
let caller_root = sessions
Expand Down Expand Up @@ -631,6 +642,9 @@ pub(super) fn observe_lifecycle(session: &RuntimeSession, lifecycle: LspLifecycl

/// Tells the relay that `session` may now serve functions it did not before.
pub(super) fn observe_functions_changed(session: &RuntimeSession) {
if !session.function_relay_enabled {
return;
}
if let Some(plugin_id) = session.plugin_id.as_deref() {
session.relay.provider_changed(plugin_id);
}
Expand Down
9 changes: 9 additions & 0 deletions rust/crates/lsp-engine/src/requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ pub struct StartServerRequest {
/// host-owned servers leave it out.
#[serde(default)]
pub plugin_id: Option<String>,
/// Whether this session participates in cross-plugin function routing.
/// False isolates an approved preparation backend before its package is
/// committed; direct host calls to this session's private functions remain.
#[serde(default = "default_function_relay_enabled")]
pub function_relay_enabled: bool,
/// Declarative `languageServer/start` attempt the host began; Core records its
/// result. Absent for v1 hosts and SDK-owned backend processes.
#[serde(default)]
Expand Down Expand Up @@ -620,6 +625,10 @@ pub struct LspRuntimeError {
pub details: Option<Value>,
}

fn default_function_relay_enabled() -> bool {
true
}

fn default_initialize_timeout() -> u64 {
DEFAULT_INITIALIZE_TIMEOUT_MS
}
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/lsp-engine/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ pub(crate) struct RuntimeSession {
pub(crate) provider_id: String,
/// Plugin that owns the process, if any; see `StartServerRequest::plugin_id`.
pub(crate) plugin_id: Option<String>,
/// Native preparation sessions can serve host calls but never enter the
/// installed-plugin function relay, even when their owner IDs are equal.
pub(crate) function_relay_enabled: bool,
pub(crate) log_identity: SessionLogIdentity,
/// Fixed workspace host, inherited by protocol workers; never a global selection.
pub(crate) workspace_host: Option<lithe_workspace::Host>,
Expand Down
1 change: 1 addition & 0 deletions rust/crates/lsp-engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub(super) fn start_request(server: &ScriptedServer) -> StartServerRequest {
role: SessionRole::LanguageServer,
log_subject: None,
plugin_id: None,
function_relay_enabled: true,
startup_operation: None,
host_services: Vec::new(),
host_options: Default::default(),
Expand Down
6 changes: 3 additions & 3 deletions rust/crates/plugin-language-servers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,9 +347,9 @@ fn is_within(path: &str, directory: &str) -> bool {
}
}

/// Params of the launch function, apart from `context` and `tools`, which
/// the host attaches: the server, the machine, the writable directories,
/// and the plugin's effective settings.
/// Params of the launch function, apart from `context`, `tools`, and the
/// optional read-only `runtimes` map, which the host attaches: the server,
/// the machine, the writable directories, and the plugin's effective settings.
pub fn resolve_params(
server_id: &str,
architecture: &str,
Expand Down
Loading
Loading