Skip to content

Commit 7f1fc4b

Browse files
feat(plugins): add managed runtime preparation and isolated resolver sessions (#96)
* feat(plugins): add managed runtime preparation contract (1/5) * feat(plugins): add managed runtime preparation contract (2/5) * feat(plugins): add managed runtime preparation contract (3/5) * feat(plugins): add managed runtime preparation contract (4/5) * feat(plugins): add managed runtime preparation contract (5/5) * docs(plugins): link managed runtime protocol implementation --------- Co-authored-by: lithe-support[bot] <356900028+lithe-support[bot]@users.noreply.github.com>
1 parent c146247 commit 7f1fc4b

31 files changed

Lines changed: 1230 additions & 17 deletions

File tree

‎rust/Cargo.lock‎

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

‎rust/contracts/application-boundary.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ this lifecycle protection; actual symbol computation remains upstream-owned.
6969
| 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 |
7070
| [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 |
7171
| [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 |
72-
| Runtime | tool requirements, normalized candidates, and effective toolchain references | tool probing and executable paths |
72+
| 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 |
7373
| 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 |
7474
| 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 |
7575
| Terminal | input bytes, output bytes, lifecycle; [shell selection semantics](terminal-profiles.md) | PTY/ConPTY, shell discovery, native profile preferences, and environment |

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

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,8 @@ or removing a command fails until the table changes in the same commit.
462462
| `plugins.commandInstallers.requirements` | List each `systemCommand` launch of a plugin with its commands and the installer that provides each |
463463
| `plugins.commandInstallers.plan` | Expand one command installer for the target the user chose |
464464
| `plugins.commandInstallers.defaultDirectory` | Read where a `toolDefault` installation puts its commands from the output of its directory probes |
465+
| `plugins.managedRuntimes.plan` | Validate pinned dependencies and select exact platform artifacts with plugin-version-independent cache identities |
466+
| `plugins.managedRuntimes.decodeResolution` | Validate a plugin resolver's complete partition of qualified native homes and missing dependency IDs |
465467
| `plugins.contentProviders.decode` | Bound the answer of a plugin content provider function and return the document text |
466468
| `debug.adapters.startArguments` | Check one debug start against a plugin's `debugAdapters[]` entry and return its DAP launch arguments |
467469
| `debug.validateAdapterEndpoint` | Validate an IDE-to-DAP TCP endpoint and classify whether remote consent is required; performs no DNS or network I/O |
@@ -3124,6 +3126,9 @@ optional `pluginId` of the plugin that owns the process, its optional
31243126
`workspaceConfiguration` (an object, plugin-owned sessions only), its
31253127
optional `hostServices` (the launch plan's `backend.hostServices`;
31263128
plugin-owned sessions only; legacy service grants or full public host-method names Core defines),
3129+
optional `functionRelayEnabled` (defaults to `true`; `false` keeps direct
3130+
host-to-session function calls but excludes the session from incoming and outgoing
3131+
cross-plugin routing, including the corresponding host service grants),
31273132
its optional `hostOptions` (plugin-owned sessions only; `editor:{actionIcons,
31283133
actionSourceBytes, providerTypes}` declares the icons, collector source bound and
31293134
provider types the host implements, reported through `lithe/host/getCapabilities`
@@ -4631,7 +4636,8 @@ function, timeoutMilliseconds }` (30000 when absent) and `resolveParams` is the
46314636
params the host sends to that backend function, `{ serverID, platform: { os,
46324637
arch }, stateDirectory, workspaceStateDirectory, logDirectory,
46334638
temporaryDirectory, settings }`; the host adds `context` and, when the plugin
4634-
declares tool definitions, `tools`. The request must carry all four of
4639+
declares tool definitions, `tools`, and after managed-runtime preparation the
4640+
optional read-only `runtimes: {<id>:{home,version}}` map. The request must carry all four of
46354641
`stateDirectory`, `workspaceStateDirectory`, `logDirectory`, and
46364642
`temporaryDirectory`, and the plan lists them in `requiredDirectories`. Every language-server plan carries a `sessionPolicy`
46374643
(`serverID`, `requestMethods`, `commands`, `serializedCommands`,
@@ -4689,6 +4695,33 @@ runs on. Refusals are `plugin.commandInstaller.unknown`,
46894695
`plugin.commandInstaller.probeOutputsInvalid`; the golden cases are
46904696
`shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json`.
46914697

4698+
The `plugins.managedRuntimes.*` commands implement
4699+
[Managed runtimes](../../shared/plugins/contract/v1/README.md#managed-runtimes).
4700+
`plan` accepts `{manifest, platform:{os,arch}}` and returns
4701+
`{status:"ok", plan:{resolve, dependencies:[{id,version,tool?,os,arch,url,
4702+
sha256,archive,stripPrefix,home,executable,cacheKey}]}}`. The resolver is
4703+
`{function,timeoutMilliseconds}`. No declaration produces an empty dependencies
4704+
array without a resolver. Targets are exact (`macos|windows|linux`,
4705+
`arm64|x86_64`); `cacheKey` is an opaque lowercase SHA-256 of the normalized
4706+
selected dependency identity, excluding plugin version. A host uses it as given.
4707+
`decodeResolution` accepts `{manifest, platform:{os,arch}, result}` and returns
4708+
`{status:"ok", resolution:{runtimes:[{id,home,version}],missing:[id]}}` with
4709+
both arrays sorted by ID. The arrays must partition every declared ID exactly
4710+
once; homes are bounded absolute paths for the supplied OS. Neither command
4711+
performs I/O or decides tool-specific compatibility. Refusals are
4712+
`plugin.managedRuntime.unavailable` for unsupported targets or absent artifacts,
4713+
`plugin.managedRuntime.invalidResolution` for hook output, and standard
4714+
manifest errors for declarations. The inert shared fixture is
4715+
`rust/fixtures/plugins/managed-runtimes.json`.
4716+
4717+
Hosts run the approved packaged resolver before install/update publication and
4718+
again for missing-state repair. Hooks qualify external and staged homes; native
4719+
adapters own downloads, hashing, safe extraction, process locks, integrity and
4720+
atomic publication. A backend-resolved server launch may receive the host-added
4721+
read-only `runtimes: {<id>:{home,version}}` map, and a declared tool binding is
4722+
selected only for that plugin's server session. This does not change project
4723+
toolchains or add an arbitrary absolute executable kind.
4724+
46924725
`plugins.contentProviders.decode` accepts `{ result }`, the value a plugin
46934726
function returned for a document of its content scheme, and returns
46944727
`{ content }`. `result` is a string, or an object whose only member is

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,10 @@ pub enum PluginsCommand {
244244
CommandInstallersPlan,
245245
/// Reads where a `toolDefault` installation puts its commands (`plugins.commandInstallers.defaultDirectory`).
246246
CommandInstallersDefaultDirectory,
247+
/// Selects pinned runtime artifacts for one target (`plugins.managedRuntimes.plan`).
248+
ManagedRuntimesPlan,
249+
/// Validates the plugin resolver's complete runtime partition (`plugins.managedRuntimes.decodeResolution`).
250+
ManagedRuntimesDecodeResolution,
247251
/// Checks a plugin content provider's answer (`plugins.contentProviders.decode`).
248252
ContentProvidersDecode,
249253
/// Merges a plugin's stored setting layers into effective values (`plugins.declarative.resolveSettings`).
@@ -1065,6 +1069,12 @@ impl CoreCommand {
10651069
"plugins.commandInstallers.defaultDirectory" => Some(Self::Plugins(
10661070
PluginsCommand::CommandInstallersDefaultDirectory,
10671071
)),
1072+
"plugins.managedRuntimes.plan" => {
1073+
Some(Self::Plugins(PluginsCommand::ManagedRuntimesPlan))
1074+
}
1075+
"plugins.managedRuntimes.decodeResolution" => Some(Self::Plugins(
1076+
PluginsCommand::ManagedRuntimesDecodeResolution,
1077+
)),
10681078
"plugins.contentProviders.decode" => {
10691079
Some(Self::Plugins(PluginsCommand::ContentProvidersDecode))
10701080
}
@@ -1725,6 +1735,8 @@ mod tests {
17251735
"plugins.commandInstallers.requirements",
17261736
"plugins.commandInstallers.plan",
17271737
"plugins.commandInstallers.defaultDirectory",
1738+
"plugins.managedRuntimes.plan",
1739+
"plugins.managedRuntimes.decodeResolution",
17281740
"plugins.contentProviders.decode",
17291741
"lsp.cancelOperation",
17301742
"lsp.pollEvents",

‎rust/crates/core/src/runtime/dispatcher/plugins.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,16 @@ pub(super) fn dispatch(
7878
payload,
7979
lithe_plugin_manifest::command_installer_default_directory_command,
8080
),
81+
PluginsCommand::ManagedRuntimesPlan => plugin_response(
82+
id,
83+
payload,
84+
lithe_plugin_manifest::managed_runtime_plan_command,
85+
),
86+
PluginsCommand::ManagedRuntimesDecodeResolution => plugin_response(
87+
id,
88+
payload,
89+
lithe_plugin_manifest::managed_runtime_resolution_command,
90+
),
8191
PluginsCommand::ContentProvidersDecode => plugin_response(
8292
id,
8393
payload,
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//! Managed-runtime plans and resolver answers through the public JSON boundary.
2+
3+
use serde_json::{json, Value};
4+
5+
fn execute(command: &str, payload: Value) -> Value {
6+
serde_json::from_str(&crate::execute_json(
7+
&json!({"command":command,"payload":payload}).to_string(),
8+
))
9+
.unwrap()
10+
}
11+
12+
#[test]
13+
fn managed_runtime_fixture_crosses_the_public_command_boundary() {
14+
let fixture: Value = serde_json::from_str(include_str!(concat!(
15+
env!("CARGO_MANIFEST_DIR"),
16+
"/../../fixtures/plugins/managed-runtimes.json"
17+
)))
18+
.unwrap();
19+
let plan = execute(
20+
"plugins.managedRuntimes.plan",
21+
json!({"manifest":fixture["manifest"],"platform":fixture["platform"]}),
22+
);
23+
assert_eq!(plan["ok"], true, "{plan}");
24+
assert_eq!(plan["data"]["status"], "ok", "{plan}");
25+
assert_eq!(plan["data"]["plan"]["dependencies"][0]["id"], "engine");
26+
let resolved = execute(
27+
"plugins.managedRuntimes.decodeResolution",
28+
json!({"manifest":fixture["manifest"],"platform":fixture["platform"],"result":fixture["resolution"]}),
29+
);
30+
assert_eq!(resolved["ok"], true, "{resolved}");
31+
assert_eq!(resolved["data"]["resolution"], fixture["resolution"]);
32+
let malformed = execute("plugins.managedRuntimes.plan", json!({}));
33+
assert_eq!(malformed["ok"], false, "{malformed}");
34+
assert_eq!(malformed["error"]["code"], "invalid_request");
35+
}

‎rust/crates/core/src/tests/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ mod installed_versions;
4343
mod keymap_import;
4444
mod language_server_sessions;
4545
mod lsp_policy;
46+
mod managed_runtimes;
4647
mod marketplace_plugins;
4748
mod notification_read;
4849
mod plugin_editor_resources;

‎rust/crates/lsp-engine/src/engine.rs‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ impl LspEngine {
198198
),
199199
provider_id: request.provider_id,
200200
plugin_id: request.plugin_id,
201+
function_relay_enabled: request.function_relay_enabled,
201202
workspace_host: lithe_workspace::current(),
202203
plugin_configuration: Mutex::new(workspace_configuration.map(Arc::new)),
203204
indexing_exclusions,
@@ -208,7 +209,19 @@ impl LspEngine {
208209
state: Mutex::new(SessionState {
209210
lifecycle: LspLifecycleState::Created,
210211
client: LspClientState {
211-
host_services: request.host_services.into_iter().collect(),
212+
host_services: request
213+
.host_services
214+
.into_iter()
215+
.filter(|service| {
216+
request.function_relay_enabled
217+
|| !matches!(
218+
service.as_str(),
219+
lithe_plugin_rpc::HOST_SERVICE_FUNCTIONS
220+
| lithe_plugin_rpc::FUNCTIONS_PROVIDERS
221+
| lithe_plugin_rpc::FUNCTIONS_INVOKE
222+
)
223+
})
224+
.collect(),
212225
host_options: request.host_options,
213226
..initialize.state
214227
},

‎rust/crates/lsp-engine/src/function_relay_tests.rs‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ impl Fixture {
9999
request.plugin_id = Some(launch.plugin_id.to_string());
100100
request.root_uri = launch.root_uri.to_string();
101101
request.host_services = launch.host_services.clone();
102+
request.function_relay_enabled = launch.function_relay_enabled;
102103
let started = self
103104
.engine
104105
.start_server(request)
@@ -135,6 +136,7 @@ struct Launch {
135136
root_uri: &'static str,
136137
functions: Vec<&'static str>,
137138
host_services: Vec<String>,
139+
function_relay_enabled: bool,
138140
}
139141

140142
impl Launch {
@@ -146,6 +148,7 @@ impl Launch {
146148
root_uri: "file:///workspace",
147149
functions: Vec::new(),
148150
host_services: vec!["functions".to_string()],
151+
function_relay_enabled: true,
149152
}
150153
}
151154

@@ -164,6 +167,11 @@ impl Launch {
164167
self
165168
}
166169

170+
fn without_relay(mut self) -> Self {
171+
self.function_relay_enabled = false;
172+
self
173+
}
174+
167175
fn capabilities(&self) -> Value {
168176
let functions: Vec<Value> = self
169177
.functions
@@ -513,6 +521,55 @@ fn a_call_the_host_starts_carries_no_caller() {
513521
assert!(received.get("caller").is_none(), "{received}");
514522
}
515523

524+
#[test]
525+
fn preparation_session_is_private_even_when_its_plugin_has_an_installed_backend() {
526+
const OWNER: &str = "dev.lithe.fixture.runtime-owner";
527+
const CALLER: &str = "dev.lithe.fixture.runtime-caller";
528+
let fixture = Fixture::new();
529+
let private = fixture.start(Launch::new(OWNER).serving(&[FORMAT]).without_relay());
530+
let installed = fixture.start(Launch::new(OWNER).serving(&[FORMAT]).at("file:///other"));
531+
let caller = fixture.start(Launch::new(CALLER));
532+
fixture.configure(snapshot(
533+
vec![
534+
plugin(CALLER, &[], &[(FORMAT, 1)]),
535+
plugin(OWNER, &[(FORMAT, 1)], &[(FORMAT, 1)]),
536+
],
537+
"local",
538+
));
539+
540+
// The private session shares the caller's root and was registered first.
541+
// Neither affinity is allowed to route a call to a staged package.
542+
caller.call("installed-call", OWNER, FORMAT);
543+
let (wire_id, _) = installed.await_invoke();
544+
installed.answer(&wire_id, json!({"installed":true}));
545+
assert_eq!(
546+
caller.reply("installed-call")["result"]["value"],
547+
json!({"installed":true})
548+
);
549+
private.assert_not_invoked();
550+
551+
for (id, method, params) in [
552+
(
553+
"private-providers",
554+
PROVIDERS,
555+
json!({"functionID": FORMAT}),
556+
),
557+
("private-call", INVOKE, call_params(OWNER, FORMAT)),
558+
] {
559+
private.ask(id, method, params);
560+
assert_error(&private.reply(id), "plugin.host.permissionDenied", -32010);
561+
}
562+
private.ask(
563+
"private-capabilities",
564+
"lithe/host/getCapabilities",
565+
json!({}),
566+
);
567+
assert!(private.reply("private-capabilities")["result"].is_object());
568+
private.host_call("qualification", OWNER, FORMAT).unwrap();
569+
let (_, received) = private.await_invoke();
570+
assert!(received.get("caller").is_none());
571+
}
572+
516573
#[test]
517574
fn a_failing_callee_keeps_its_own_error_code() {
518575
let fixture = Fixture::new();

‎rust/crates/lsp-engine/src/relay_hub.rs‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,15 @@ impl RelayHub {
8787
) -> Result<Vec<String>, CoreError> {
8888
let rpc_id = request.get("id").cloned().unwrap_or(Value::Null);
8989
let params = request.get("params").unwrap_or(&Value::Null);
90+
if !session.function_relay_enabled {
91+
return Ok(vec![reply_message(
92+
&rpc_id,
93+
&Err(RelayFailure::new(
94+
codes::HOST_UNAVAILABLE,
95+
"This session is isolated from cross-plugin function routing.",
96+
)),
97+
)?]);
98+
}
9099
// Only a plugin's own session can negotiate the protocol, so a
91100
// session without a plugin should never get here.
92101
let Some(caller_plugin) = session.plugin_id.as_deref() else {
@@ -477,7 +486,9 @@ fn find_provider(
477486
let sessions = sessions.lock().unwrap_or_else(PoisonError::into_inner);
478487
let candidates: Vec<Arc<RuntimeSession>> = sessions
479488
.values()
480-
.filter(|session| session.plugin_id.as_deref() == Some(plugin_id))
489+
.filter(|session| {
490+
session.function_relay_enabled && session.plugin_id.as_deref() == Some(plugin_id)
491+
})
481492
.cloned()
482493
.collect();
483494
let caller_root = sessions
@@ -631,6 +642,9 @@ pub(super) fn observe_lifecycle(session: &RuntimeSession, lifecycle: LspLifecycl
631642

632643
/// Tells the relay that `session` may now serve functions it did not before.
633644
pub(super) fn observe_functions_changed(session: &RuntimeSession) {
645+
if !session.function_relay_enabled {
646+
return;
647+
}
634648
if let Some(plugin_id) = session.plugin_id.as_deref() {
635649
session.relay.provider_changed(plugin_id);
636650
}

0 commit comments

Comments
 (0)