diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index 5895898f..134b61ab 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -910,9 +910,10 @@ fn plugin_backend_is_planned_without_a_workspace_and_names_its_host_services() { /// A `backend` process starts without a page, its plan names the `backend` /// version so the host may start it on `onWorkspaceOpen`, and -/// `workspace.metadata` grants the `workspace` host service. A host that does -/// not offer `backend` refuses the manifest instead of starting a process it -/// would misuse. +/// `workspace.metadata` grants the `workspace` host service and the +/// `getHostPaths` method grant; a host that does not serve that method drops +/// the grant when it starts the backend. A host that does not offer `backend` +/// refuses the manifest instead of starting a process it would misuse. #[test] fn workspace_backend_is_planned_with_its_version_and_workspace_service() { let outcome = validate(fixture("backend-workspace.plugin.json")); @@ -930,7 +931,10 @@ fn workspace_backend_is_planned_with_its_version_and_workspace_service() { assert_eq!(launch["status"], "ok", "{launch}"); assert_eq!( launch["plan"]["backend"], - json!({ "hostServices": ["workspace"], "version": 0 }) + json!({ + "hostServices": ["lithe/host/workspace/getHostPaths", "workspace"], + "version": 0 + }) ); let hosted = |host: Value| { diff --git a/rust/crates/lsp-engine/src/function_relay_tests.rs b/rust/crates/lsp-engine/src/function_relay_tests.rs index 8a4991a3..43c40bc8 100644 --- a/rust/crates/lsp-engine/src/function_relay_tests.rs +++ b/rust/crates/lsp-engine/src/function_relay_tests.rs @@ -490,6 +490,31 @@ fn a_declared_exported_call_reaches_the_callee_and_returns_its_value() { }); } +/// Both backends run on this machine for a remote workspace too, so a call +/// naming a remote context reaches the callee like a local one (API-35). +#[test] +fn a_call_for_a_remote_workspace_reaches_the_callee() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(snapshot( + vec![ + plugin(PYTHON, &[], &[(FORMAT, 1)]), + plugin(GO, &[(FORMAT, 1)], &[]), + ], + "remote", + )); + + python.ask("call-1", INVOKE, call_params(GO, FORMAT)); + let (wire_id, received) = go.await_invoke(); + assert_eq!(received["context"], workspace_context()); + go.answer(&wire_id, json!({ "edits": 1 })); + assert_eq!( + python.reply("call-1")["result"], + json!({ "value": { "edits": 1 } }) + ); +} + #[test] fn a_caller_field_in_the_host_request_is_refused() { let fixture = Fixture::new(); @@ -728,19 +753,6 @@ fn refusals() -> Vec { code: "plugin.host.contextExpired", rpc_code: -32011, }, - Refusal { - name: "the workspace is remote", - snapshot: snapshot( - vec![ - plugin(PYTHON, &[], &[(FORMAT, 1)]), - plugin(GO, &[(FORMAT, 1)], &[]), - ], - "remote", - ), - params: call_params(GO, FORMAT), - code: "plugin.host.authorityUnsupported", - rpc_code: -32012, - }, Refusal { name: "the params are above the relay limit", snapshot: standard_snapshot(), diff --git a/rust/crates/plugin-function-relay/src/lib.rs b/rust/crates/plugin-function-relay/src/lib.rs index d594bd20..7ded46d5 100644 --- a/rust/crates/plugin-function-relay/src/lib.rs +++ b/rust/crates/plugin-function-relay/src/lib.rs @@ -84,7 +84,11 @@ pub struct RelayContext { #[serde(rename = "contextID")] pub(crate) context_id: String, pub(crate) generation: u64, - pub(crate) authority: ContextAuthority, + /// Checked as part of the snapshot, but the relay does not depend on it: + /// both backends run on this machine for a remote workspace too, and the + /// callee's host requests are routed by the context's authority (API-35). + #[serde(rename = "authority")] + pub(crate) _authority: ContextAuthority, } /// A function an enabled plugin exports. @@ -639,12 +643,6 @@ impl FunctionRelay { codes::HOST_CONTEXT_EXPIRED, "The workspace context is no longer current.", )), - Some(context) if context.authority == ContextAuthority::Remote => { - Err(RelayFailure::new( - codes::HOST_AUTHORITY_UNSUPPORTED, - "Plugin functions do not run for remote workspaces.", - )) - } Some(_) => Ok(()), } } @@ -924,7 +922,7 @@ mod tests { RelayContext { context_id: "workspace-1".to_string(), generation: 3, - authority: ContextAuthority::Local, + _authority: ContextAuthority::Local, } } @@ -1228,25 +1226,18 @@ mod tests { assert_eq!(refusal(&mut relay, unknown), codes::HOST_CONTEXT_EXPIRED); } + /// Both backends run on this machine for a remote workspace too, so a call + /// naming a remote context is dispatched like a local one (API-35). #[test] - fn a_remote_workspace_is_refused() { - let mut relay = relay(); + fn a_remote_workspace_is_relayed() { + let mut relay = FunctionRelay::default(); relay - .configure(RelaySnapshot { - plugins: vec![ - plugin(PYTHON, &[], &[(FUNCTION, 1)]), - plugin(GO, &[(FUNCTION, 1)], &[]), - ], - contexts: vec![RelayContext { - authority: ContextAuthority::Remote, - ..local_context() - }], - }) + .configure(snapshot_with_contexts(vec![RelayContext { + _authority: ContextAuthority::Remote, + ..local_context() + }])) .unwrap(); - assert_eq!( - refusal(&mut relay, request("py", PYTHON, GO, 1)), - codes::HOST_AUTHORITY_UNSUPPORTED - ); + admitted_call(&mut relay, request("py", PYTHON, GO, 1), Instant::now()); } #[test] diff --git a/rust/crates/plugin-rpc/src/failures.rs b/rust/crates/plugin-rpc/src/failures.rs index 52b3913c..4d53cf40 100644 --- a/rust/crates/plugin-rpc/src/failures.rs +++ b/rust/crates/plugin-rpc/src/failures.rs @@ -42,6 +42,9 @@ pub fn host_rpc_code(code: &str) -> i64 { // must tell the provider's error from Core's by the number alone. codes::FAILED => -32070, codes::INVALID_RESULT => -32071, + // -32072 to -32077 are the toolchain provider protocol's. + codes::HOST_REMOTE_DISCONNECTED => -32078, + codes::HOST_PLATFORM_UNAVAILABLE => -32079, _ => -32603, } } @@ -86,6 +89,8 @@ pub fn host_failure(code: Option<&str>) -> (&'static str, i64) { Some(codes::HOST_METHOD_NOT_DECLARED) => codes::HOST_METHOD_NOT_DECLARED, Some(codes::HOST_TOOL_UNRESOLVED) => codes::HOST_TOOL_UNRESOLVED, Some(codes::HOST_FOREIGN_CONTRIBUTION) => codes::HOST_FOREIGN_CONTRIBUTION, + Some(codes::HOST_REMOTE_DISCONNECTED) => codes::HOST_REMOTE_DISCONNECTED, + Some(codes::HOST_PLATFORM_UNAVAILABLE) => codes::HOST_PLATFORM_UNAVAILABLE, // A backend exit is reported to pages, never to the backend itself. Some(codes::BACKEND_EXITED) => codes::HOST_FAILED, _ => codes::HOST_FAILED, diff --git a/rust/crates/plugin-rpc/src/host_api.rs b/rust/crates/plugin-rpc/src/host_api.rs index 7b1c583e..19db0388 100644 --- a/rust/crates/plugin-rpc/src/host_api.rs +++ b/rust/crates/plugin-rpc/src/host_api.rs @@ -98,6 +98,10 @@ mod tests { method("lithe/host/workspace/readFile")["grant"], "lithe/host/workspace/readFile" ); + assert_eq!( + method("lithe/host/workspace/getHostPaths")["grant"], + "lithe/host/workspace/getHostPaths" + ); assert!(method("lithe/host/subscriptions/dispose")["grant"].is_null()); assert_eq!(method("lithe/host/functions/invoke")["coreServed"], true); } diff --git a/rust/crates/plugin-rpc/src/host_params.rs b/rust/crates/plugin-rpc/src/host_params.rs index ceace255..64967150 100644 --- a/rust/crates/plugin-rpc/src/host_params.rs +++ b/rust/crates/plugin-rpc/src/host_params.rs @@ -35,6 +35,7 @@ pub(crate) fn check_host_params( HostParams::Credential { with_secret: false } => &["key"], HostParams::Subscription => &["subscriptionID"], HostParams::Context => &["context"], + HostParams::HostPaths => &["context", "rootIDs"], HostParams::FunctionProviders => &["functionID"], HostParams::FunctionInvoke => &[ "pluginID", @@ -117,6 +118,27 @@ pub(crate) fn check_host_params( return Err(invalid(CONTEXT_REFERENCE_MESSAGE)); } } + HostParams::HostPaths => { + if !params.get("context").is_some_and(is_context_reference) { + return Err(invalid(CONTEXT_REFERENCE_MESSAGE)); + } + if let Some(root_ids) = params.get("rootIDs") { + let root_ids = root_ids + .as_array() + .filter(|ids| !ids.is_empty() && ids.len() <= MAX_HOST_PATH_ROOTS); + let mut seen = BTreeSet::new(); + if !root_ids.is_some_and(|ids| { + ids.iter().all(|id| { + id.as_str() + .is_some_and(|id| is_credential_key(id) && seen.insert(id)) + }) + }) { + return Err(invalid( + "`rootIDs` is 1-256 distinct root IDs of 1-128 ASCII letters, digits, '.', '_', ':' or '-'.", + )); + } + } + } HostParams::FunctionProviders => { if !params .get("functionID") diff --git a/rust/crates/plugin-rpc/src/host_requests.rs b/rust/crates/plugin-rpc/src/host_requests.rs index cf766d95..5ed7b62b 100644 --- a/rust/crates/plugin-rpc/src/host_requests.rs +++ b/rust/crates/plugin-rpc/src/host_requests.rs @@ -40,6 +40,9 @@ pub(crate) enum HostParams { Subscription, /// Exactly `{ context }`, a well-formed context reference. Context, + /// `{ context, rootIDs? }`: a well-formed context reference and at most + /// 256 distinct root IDs (plan API-40). + HostPaths, /// Snapshot source listing or one bounded chunk from a selected source. KeymapSnapshot { chunk: bool }, /// `{ context, serverID, method, params?, timeoutMilliseconds? }`: one @@ -209,6 +212,12 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ permission: None, params: HostParams::Context, }, + HostMethod { + method: WORKSPACE_GET_HOST_PATHS, + service: HOST_SERVICE_WORKSPACE, + permission: Some("workspace.metadata"), + params: HostParams::HostPaths, + }, HostMethod { method: "lithe/host/workspace/readDirectory", service: "workspace", diff --git a/rust/crates/plugin-rpc/src/lib.rs b/rust/crates/plugin-rpc/src/lib.rs index ef682db8..c4a870fc 100644 --- a/rust/crates/plugin-rpc/src/lib.rs +++ b/rust/crates/plugin-rpc/src/lib.rs @@ -183,6 +183,15 @@ const WORKSPACE_GET_CONTEXT: &str = "lithe/host/workspace/getContext"; const WORKSPACE_GET_FOLDERS: &str = "lithe/host/workspace/getFolders"; +/// Paths of a remote context's root folders on the remote host (plan +/// API-40). `workspace.metadata` admits it as a grant of its own, not as +/// part of the `workspace` service, so a host that does not serve it leaves +/// it out of the session and adding it widened no existing grant. +const WORKSPACE_GET_HOST_PATHS: &str = "lithe/host/workspace/getHostPaths"; + +/// Most root IDs one `getHostPaths` request may name. +const MAX_HOST_PATH_ROOTS: usize = 256; + /// Backend request listing the plugins that export a function it may call. pub const FUNCTIONS_PROVIDERS: &str = "lithe/host/functions/providers"; @@ -291,6 +300,13 @@ pub mod codes { /// The request names a contribution, such as a language server, that /// another plugin owns. pub const HOST_FOREIGN_CONTRIBUTION: &str = "plugin.host.foreignContribution"; + /// The connection to the remote workspace host was lost while the + /// operation ran. Whether the operation took effect on the host is + /// unknown; the backend asks again once the context is current. + pub const HOST_REMOTE_DISCONNECTED: &str = "plugin.host.remoteDisconnected"; + /// The plugin has no package or managed runtime for the remote host's + /// platform, so the process the request needs cannot run there. + pub const HOST_PLATFORM_UNAVAILABLE: &str = "plugin.host.platformUnavailable"; /// A page's call or a host operation ended because the backend process /// exited. Reported by hosts to pages, never sent to a backend. pub const BACKEND_EXITED: &str = "plugin.backend.exited"; @@ -804,6 +820,50 @@ mod tests { .is_err()); } + /// `workspace.metadata` admits `getHostPaths` as a method grant of its + /// own, and one request names at most 256 root IDs (plan API-40). + #[test] + fn host_paths_are_a_method_grant_with_bounded_root_ids() { + assert_eq!( + methods_for_permission("workspace.metadata"), + [WORKSPACE_GET_HOST_PATHS] + ); + assert!(is_host_grant(WORKSPACE_GET_HOST_PATHS)); + let granted = BTreeSet::from([ + HOST_SERVICE_WORKSPACE.to_string(), + WORKSPACE_GET_HOST_PATHS.to_string(), + ]); + let context = json!({ "contextID": "w-3f2a", "generation": 2 }); + let root_ids = + |count: usize| -> Vec { (0..count).map(|i| format!("r{i}")).collect() }; + let request = |count| { + host_request( + WORKSPACE_GET_HOST_PATHS, + Some(&json!({ "context": context, "rootIDs": root_ids(count) })), + Some(0), + &granted, + ) + }; + assert_eq!( + request(MAX_HOST_PATH_ROOTS), + Ok(HostRoute::Forward(HOST_SERVICE_WORKSPACE)) + ); + assert_eq!( + request(MAX_HOST_PATH_ROOTS + 1).unwrap_err().code, + codes::HOST_INVALID_PARAMS + ); + // The method is not part of the `workspace` service's methods, so a + // session granted only the service never learns it exists. + let capabilities = + capabilities_answer(0, &BTreeSet::from([HOST_SERVICE_WORKSPACE.to_string()])); + assert!(!capabilities.to_string().contains(WORKSPACE_GET_HOST_PATHS)); + let capabilities = capabilities_answer(0, &granted); + assert!(capabilities["services"][HOST_SERVICE_WORKSPACE]["methods"] + .as_array() + .unwrap() + .contains(&json!(WORKSPACE_GET_HOST_PATHS))); + } + /// A message over the bound is cut at a character boundary, never inside /// a multi-byte character. #[test] diff --git a/rust/fixtures/plugins/host-api-v1.json b/rust/fixtures/plugins/host-api-v1.json index 0f40eaaf..f96dd033 100644 --- a/rust/fixtures/plugins/host-api-v1.json +++ b/rust/fixtures/plugins/host-api-v1.json @@ -10,6 +10,16 @@ "input": { "method": "lithe/host/workspace/readFile", "service": "workspace", "grants": ["workspace"] }, "expected": { "allowed": false, "code": "plugin.host.permissionDenied" } }, + { + "name": "metadata grant alone does not grant host paths", + "input": { "method": "lithe/host/workspace/getHostPaths", "service": "workspace", "grants": ["workspace"] }, + "expected": { "allowed": false, "code": "plugin.host.permissionDenied" } + }, + { + "name": "the host-paths grant admits host paths", + "input": { "method": "lithe/host/workspace/getHostPaths", "service": "workspace", "grants": ["workspace", "lithe/host/workspace/getHostPaths"] }, + "expected": { "allowed": true } + }, { "name": "a method cannot be attributed to another service", "input": { "method": "lithe/host/editor/applyEdits", "service": "workspace", "grants": ["workspace"] }, diff --git a/shared/plugins/README.md b/shared/plugins/README.md index aee5f29e..c545a7da 100644 --- a/shared/plugins/README.md +++ b/shared/plugins/README.md @@ -155,6 +155,7 @@ SDK 与插件后端在构建时下载,并按锁定的 SHA-256(或 Git commit | [构建、运行与测试接入](guides/build-tool-integration.md) | 执行提供者示例、工程后端边界,以及声明式构建系统的现状和已发布示例 | | [编写调试适配器插件](guides/debug-adapter-plugin.md) | 从最小清单到启动方式、先编译再调试的 `executable`,以及调试控制台补全 | | [插件后端:工作区上下文与宿主服务](guides/plugin-backend-workspace.md) | 免页面启动、工作区上下文、纯后端命令、文档/文件/窗口宿主方法、宿主通知、失败码,以及宿主服务只增不改时后端要遵守的规则 | +| [插件后端:远程工作区](guides/plugin-backend-remote-workspaces.md) | 远程上下文的来源与远端平台、单独获取的远端路径 `getHostPaths`、`path` 与 `hostPath` 的区别、断线与平台失败,以及插件函数中转 | | [插件自有的原生终端](guides/native-terminals.md) | `terminal/*`:创建、显示、关闭、重开和退出通知(本机工作区) | 收录和上架的规则由 Lithe Store 维护:[发布社区插件](https://github.com/Lithe-IDEA/Lithe-store/blob/main/docs/publishing.md)讲怎么打包、提交收录和发布新版本,[版本追踪与更新](https://github.com/Lithe-IDEA/Lithe-store/blob/main/docs/versioning-and-updates.md)讲 Lithe 怎么选择可安装的版本。 @@ -375,6 +376,7 @@ The example plugins are maintained in their own repositories. Before copying one | [Build, run, and test integration](guides/build-tool-integration.md) | Execution provider examples, the project backend boundary, and the current status and published examples of declarative build systems | | [Writing a debug adapter plugin](guides/debug-adapter-plugin.md) | From a minimal manifest to launch modes, compile-then-debug `executable`, and debug console completion | | [Plugin backend: workspace contexts and host services](guides/plugin-backend-workspace.md) | Launching without a page, workspace contexts, backend-only commands, document, file, and window host methods, host notifications, failure codes, and the rules a backend follows while host services only grow | +| [Plugin backend: remote workspaces](guides/plugin-backend-remote-workspaces.md) | A remote context's authority and the remote platform, remote paths fetched on their own with `getHostPaths`, how `path` and `hostPath` differ, disconnect and platform failures, and the function relay | | [Plugin-owned native terminals](guides/native-terminals.md) | `terminal/*`: create, show, close, reopen, and exit notifications (local workspaces) | Lithe Store maintains the listing rules: [Publishing community plugins](https://github.com/Lithe-IDEA/Lithe-store/blob/main/docs/publishing.md) covers packaging, submitting a listing, and releasing new versions, and [Version tracking and updates](https://github.com/Lithe-IDEA/Lithe-store/blob/main/docs/versioning-and-updates.md) covers how Lithe chooses an installable version. diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 1122a55f..2d0aa87b 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -1219,7 +1219,7 @@ untrusted, and a process that would run project code is then | `sessionPolicy` | Present for a language server that declares session fields: the [session policy](#plugin-owned-sessions) the host passes to `lsp.startServer` unchanged. | | `buildProvider` | Present only for a `buildSystemID` selection: `{buildSystemID, executesProjectCode, mayUseNetwork, languageServer?}`. `languageServer` names the language whose server is the provider; the rest of the plan is then that server's plan, and the host reuses its running session instead of starting a second process. | | `vcsProvider` | Present only for a `vcsProviderID` selection: the [provider descriptor](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/vcs-provider-v1.md#provider-descriptor) the host keeps for the session. | -| `backend` | Present only for a `backend` selection: `{hostServices, version}`, the sorted [host services](#host-services) the plugin's permissions grant, plus `version`, the manifest's `requires.backend` (`0`). The host passes `hostServices` to `lsp.startServer.hostServices` unchanged. | +| `backend` | Present only for a `backend` selection: `{hostServices, version}`, the sorted [host services](#host-services) the plugin's permissions grant, plus `version`, the manifest's `requires.backend` (`0`). The list holds service names (`workspace`, `credentials`) and the full names of methods a permission grants one by one, such as `lithe/host/workspace/getHostPaths`. The host passes it to `lsp.startServer.hostServices` without the method names it registered no handler for; a backend calling one of those gets `plugin.host.permissionDenied`. | A language without a server, an undeclared build system, a build system without a provider, an undeclared VCS provider, and a plugin without a @@ -3888,7 +3888,8 @@ running on that session, is dropped. A backend may send these requests to the host. Each service is granted by one manifest permission; Core receives the granted services as `lsp.startServer.hostServices` (from the launch plan's -`backend.hostServices`) and checks every request before the host sees it. +`backend.hostServices`, less the method grants the host does not serve) and +checks every request before the host sees it. | Request | Params | Result | Permission | | --- | --- | --- | --- | @@ -3935,6 +3936,7 @@ notifications. | `lithe/host/workspace/listContexts` | none or `{}` | `{ revision, contexts: [] }` | `workspace.metadata` | | `lithe/host/workspace/getContext` | `{ context: { contextID, generation } }` | `` | `workspace.metadata` | | `lithe/host/workspace/getFolders` | `{ context: { contextID, generation } }` | `{ folders: [] }` | `workspace.metadata` | +| `lithe/host/workspace/getHostPaths` | `{ context: { contextID, generation }, rootIDs?: [] }` | `{ folders: [{ rootID, hostPath }] }` | `workspace.metadata`, as a method grant of its own | - Core answers `getCapabilities` itself; `protocolVersion` is the negotiated `litheFunctions` version. `services` maps each service the session may use (the implicit `host`, `subscriptions`, and `commands`, and @@ -3987,6 +3989,41 @@ notifications. process services answer a request for a context whose authority they do not implement with `plugin.host.authorityUnsupported`; they never read the placeholder or run the operation locally instead. +- A `remote` authority also has `platform: { os, arch }`, the remote host's + operating system and CPU architecture, with the values of + [managed runtimes](#managed-runtimes): `os` is `linux` and `arch` is + `arm64` or `x86_64`. A backend uses it to choose the package or runtime a + process on the host needs. A `local` authority has no `platform`; the + backend runs on that machine. A backend ignores an `os` or `arch` it does + not know, as a later host may connect to other systems. + + ```json + "authority": { "kind": "remote", "id": "c-7d41", "platform": { "os": "linux", "arch": "x86_64" } } + ``` +- `getHostPaths` gives the paths of a `remote` context's root folders on the + remote host. They are not part of the context, so a backend that does not + need them never sees the remote user name or directory layout, and a + backend written before remote workspaces cannot take one for a local path. + - It is granted by `workspace.metadata` as a method grant of its own, not + with the `workspace` service: a host that does not serve it leaves it + out of `getCapabilities`, and the service grant alone is + `plugin.host.permissionDenied`. + - `rootIDs`, when present, names 1 to 256 distinct root IDs of the + context, in the key alphabet; `folders` then holds those roots in that + order. Without it, `folders` holds every root in `getFolders` order. A + root ID the context does not have is `plugin.host.notFound`. + - A `local` context is `plugin.host.authorityUnsupported`: its folders + already carry `path`. A closed context, or one whose generation changed, + is `plugin.host.contextExpired`, and earlier answers are void. + - `hostPath` is an absolute POSIX path on the remote host. A backend uses + it only in what runs on that host: process arguments and working + directories, a debug configuration's `program` and `cwd`, a language + server's `initializationOptions`. It never names a file on the machine + that runs Lithe, so a backend never reads or writes it locally; files of + the workspace are read through the file services by `{ rootID, path }`. + - The official SDKs give `path` and `hostPath` distinct types, and their + helper that picks the path a process uses returns `path` for a `local` + context without asking the host. - `stateDirectory` is private to the plugin and the workspace, outside the plugin package and the application bundle. Only `getContext` returns it, and creates it then; `listContexts` entries carry every other field and @@ -4032,6 +4069,8 @@ notifications. | `plugin.host.methodNotDeclared` | `-32024` | The method, or the `workspace/executeCommand` command, is not in the server's declared session | | `plugin.host.toolUnresolved` | `-32025` | A tool definition the request names resolves to no executable for this workspace; `details` is `{ tool, reason }`, `reason` being `notFound` (no candidate of the four layers meets the definition and its minimum version) or `unusable` (a chosen executable cannot be used) | | `plugin.host.foreignContribution` | `-32026` | The named server or contribution belongs to another plugin | + | `plugin.host.remoteDisconnected` | `-32078` | The connection to the remote host was lost while the operation ran; whether it took effect on the host is unknown, and the backend asks again once the context is current | + | `plugin.host.platformUnavailable` | `-32079` | The plugin has no package or managed runtime for the remote host's `platform`, so the process the request needs cannot run there | JSON-RPC reserves `-32768` to `-32000` for the protocol and lets implementations define `-32099` to `-32000` as server errors. `-32000` @@ -4102,8 +4141,8 @@ without a new version: - an optional field of request params (an *option*) whose absence keeps the earlier behavior, or a field of a result, a notification, `details`, or `limits`; -- a failure code, which takes the next unused JSON-RPC number after - `-32021`; a number never changes meaning. +- a failure code, which takes the next JSON-RPC number no code of this + contract uses yet; a number never changes meaning. A change an existing backend would misread gives `backend` version 1, and the protocol moves with it: removing or renaming a method, notification, or @@ -4829,7 +4868,6 @@ the provider; the first failing check wins: | The provider exports the function | `plugin.function.notExported` | | The declared and exported versions are equal | `plugin.function.versionMismatch` | | The context is open, and has this generation | `plugin.host.contextExpired` | -| The context is a local workspace | `plugin.host.authorityUnsupported` | | The params are at most 256 KiB | `plugin.function.payloadTooLarge` | | The call named by `parentOperationID` is still running | `plugin.host.cancelled` | | The provider is not on the call chain, the caller included | `plugin.function.callCycle` | @@ -4941,10 +4979,13 @@ same way. #### Remote workspaces -The relay is a local-workspace feature. A call whose context is a remote -workspace is refused with `plugin.host.authorityUnsupported`, and the -exported `context` value `"workspace"` means a local workspace only. Backends -still run on the machine that runs Lithe. +Backends run on the machine that runs Lithe for a remote workspace too, so the +relay dispatches a call whose context is a remote workspace like a local one, +and the exported `context` value `"workspace"` means a workspace of either +authority. The callee learns the authority from `getContext`, and its own host +requests for that context reach the remote host or are +`plugin.host.authorityUnsupported` by the rules of each service; the relay +neither reads nor rewrites paths in the params or the result. #### Hot activation @@ -5150,6 +5191,8 @@ command payload is a Core `invalid_request` failure instead. | `plugin.host.languageServerError` | Core | The language server answered a forwarded request with an error; `details` is `{code, message}` | | `plugin.host.methodNotDeclared` | Core | A forwarded method or command is not in the server's declared session | | `plugin.host.foreignContribution` | Core | The named language server belongs to another plugin | +| `plugin.host.remoteDisconnected` | Host | The connection to the remote host was lost while the operation ran | +| `plugin.host.platformUnavailable` | Host | The plugin has no package or managed runtime for the remote host's platform | | `plugin.backend.exited` | Host | A page's call, or a host operation for the backend, ended because the backend process exited | Host-facing plugin states are `notInstalled`, `installed` (enabled or diff --git a/shared/plugins/contract/v1/fixtures/backend/function-protocol.json b/shared/plugins/contract/v1/fixtures/backend/function-protocol.json index e0cb1d53..70b72d1a 100644 --- a/shared/plugins/contract/v1/fixtures/backend/function-protocol.json +++ b/shared/plugins/contract/v1/fixtures/backend/function-protocol.json @@ -532,7 +532,15 @@ {"name": "an invocation's function ID is well formed", "version": 0, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "Not-Valid", "context": {"contextID": "w1", "generation": 1}}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, {"name": "an invocation's params are an object", "version": 0, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "params": [1]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, {"name": "an invocation's timeout is positive", "version": 0, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "timeoutMilliseconds": 0}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, - {"name": "a caller cannot choose who the callee thinks called", "version": 0, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "caller": {"pluginID": "dev.lithe.fixture.other"}}, "expected": {"rpcCode": -32018, "code": "plugin.host.unsupportedOption", "details": {"option": "caller"}}} + {"name": "a caller cannot choose who the callee thinks called", "version": 0, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "caller": {"pluginID": "dev.lithe.fixture.other"}}, "expected": {"rpcCode": -32018, "code": "plugin.host.unsupportedOption", "details": {"option": "caller"}}}, + {"name": "a remote context's host paths are forwarded when workspace.metadata grants the method", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}}, "expected": {"forward": "workspace"}}, + {"name": "host paths may be asked for some root folders", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}, "rootIDs": ["r0c1d2e3f4a5b6c7d", "r1a2b3c4d5e6f7a8b"]}, "expected": {"forward": "workspace"}}, + {"name": "the workspace service alone does not grant host paths", "version": 0, "hostServices": ["workspace"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "host paths name a context", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"rootIDs": ["r0c1d2e3f4a5b6c7d"]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "an empty root ID list is invalid", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}, "rootIDs": []}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a root ID named twice is invalid", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}, "rootIDs": ["r0c1d2e3f4a5b6c7d", "r0c1d2e3f4a5b6c7d"]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a root ID outside the alphabet is invalid", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}, "rootIDs": ["/home/me/orders"]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "host paths name the option they do not support", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}, "path": "/home/me/orders"}, "expected": {"rpcCode": -32018, "code": "plugin.host.unsupportedOption", "details": {"option": "path"}}} ], "invocationCallers": [ { @@ -584,8 +592,7 @@ { "name": "the provider answered without a result Core can pass on", "code": "plugin.function.invalidResult", "rpcCode": -32071 }, { "name": "the relay's own deadline passed", "code": "plugin.host.timeout", "rpcCode": -32015 }, { "name": "the caller or an upstream caller cancelled", "code": "plugin.host.cancelled", "rpcCode": -32800 }, - { "name": "the workspace context is unknown or replaced", "code": "plugin.host.contextExpired", "rpcCode": -32011 }, - { "name": "the workspace is remote", "code": "plugin.host.authorityUnsupported", "rpcCode": -32012 } + { "name": "the workspace context is unknown or replaced", "code": "plugin.host.contextExpired", "rpcCode": -32011 } ], "invocationContexts": [ { @@ -634,7 +641,9 @@ {"name": "the plugin's language server is not running", "code": "plugin.host.languageServerUnavailable", "expected": {"code": "plugin.host.languageServerUnavailable", "rpcCode": -32022}}, {"name": "the language server answered with an error", "code": "plugin.host.languageServerError", "expected": {"code": "plugin.host.languageServerError", "rpcCode": -32023}}, {"name": "the method is not in the language server's declared session", "code": "plugin.host.methodNotDeclared", "expected": {"code": "plugin.host.methodNotDeclared", "rpcCode": -32024}}, - {"name": "the server belongs to another plugin", "code": "plugin.host.foreignContribution", "expected": {"code": "plugin.host.foreignContribution", "rpcCode": -32026}} + {"name": "the server belongs to another plugin", "code": "plugin.host.foreignContribution", "expected": {"code": "plugin.host.foreignContribution", "rpcCode": -32026}}, + {"name": "the connection to the remote host was lost", "code": "plugin.host.remoteDisconnected", "expected": {"code": "plugin.host.remoteDisconnected", "rpcCode": -32078}}, + {"name": "the plugin has nothing that runs on the remote host's platform", "code": "plugin.host.platformUnavailable", "expected": {"code": "plugin.host.platformUnavailable", "rpcCode": -32079}} ], "hostNotifications": [ { "name": "changed contexts reach a workspace session", "version": 0, "hostServices": ["workspace"], "method": "lithe/host/workspace/didChangeContexts", "params": { "revision": 4 }, "expected": { "delivered": true } }, diff --git a/shared/plugins/guides/plugin-backend-remote-workspaces.md b/shared/plugins/guides/plugin-backend-remote-workspaces.md new file mode 100644 index 00000000..9e14efab --- /dev/null +++ b/shared/plugins/guides/plugin-backend-remote-workspaces.md @@ -0,0 +1,299 @@ +# 插件后端:远程工作区 / Plugin backend: remote workspaces + +[中文](#中文) · [English](#english) + +## 中文 + +工作区在远端主机上时,插件后端仍然运行在运行 Lithe 的这台机器上:每个插件只有一个后端进程,所有窗口和工作区共用。本页说明后端怎样认出远程上下文、怎样取得根目录在远端主机上的路径,以及现在哪些宿主服务能用于远程上下文。规则以[契约](../contract/v1/README.md#public-document-file-and-window-methods)为准;上下文的通用字段见[插件后端:工作区](plugin-backend-workspace.md)。 + +本页的 SDK 封装(`getHostPaths`、`processRoots` 和独立的远端路径类型)还没有发布,会随 Node.js、Java、Rust SDK 的下一个版本和 Go SDK 的下一个标签提供。 + +### 认出远程上下文 + +`listContexts`、`getContext` 返回的上下文里,`authority` 说明工作区在哪里: + +```json +"authority": { "kind": "remote", "id": "c-7d41", "platform": { "os": "linux", "arch": "x86_64" } } +``` + +| 字段 | 含义 | +| --- | --- | +| `kind` | `local` 或 `remote` | +| `id` | 只有 `remote` 有;不透明的连接 ID,后端不要解析它 | +| `platform` | 只有 `remote` 有;远端主机的系统和 CPU 架构,取值同[受管运行时](../contract/v1/README.md#managed-runtimes):`os` 为 `linux`,`arch` 为 `arm64` 或 `x86_64`。后端用它选择在远端运行的进程需要的包或运行时;遇到不认识的 `os`、`arch` 时忽略,因为以后的宿主可能连接其他系统 | + +远程上下文的 `folders` 只有 `rootID` 和 `name`,没有 `path`。宿主在本机为远程工作区保留的目录只是空占位,不是工作区本身,后端不要读写它。 + +### 用 getHostPaths 取远端路径 + +根目录在远端主机上的路径不放在上下文里,要单独请求 `lithe/host/workspace/getHostPaths`。这样不需要它的后端看不到远端用户名和目录结构,远程工作区出现之前写的后端也不会把它当成本地路径。 + +| 请求 | 结果 | +| --- | --- | +| `{ context: { contextID, generation }, rootIDs?: [] }` | `{ folders: [{ rootID, hostPath }] }` | + +- 权限:manifest 声明 `workspace.metadata`。它是这个方法自己的授权,不随 `workspace` 服务给出;宿主不提供这个方法时,`getCapabilities` 里没有它。所以调用前先用 `supports("lithe/host/workspace/getHostPaths")` 探测。 +- 不带 `rootIDs` 时返回全部根目录,顺序同 `getFolders`;带 `rootIDs` 时它必须是 1 到 256 个互不相同、符合键字母表(ASCII 字母、数字、`.`、`_`、`:`、`-`,1 到 128 个字符)的根 ID,结果按给出的顺序返回。SDK 在本地拒绝不合规的 `rootIDs`(`sdk.host.invalidParams`),不发请求。 +- 失败: + +| 代码 | 什么时候 | 后端怎么做 | +| --- | --- | --- | +| `plugin.host.authorityUnsupported` | 上下文是 `local` | 本地根目录已经带 `path`,直接用 | +| `plugin.host.notFound` | 上下文没有这个根 ID | 重新读取 `getFolders` | +| `plugin.host.contextExpired` | 上下文已关闭或 `generation` 变了 | 之前取得的路径全部作废,重新解析原来的目标,不要改用当前聚焦的窗口 | +| `plugin.host.permissionDenied` | 没有这个方法的授权:manifest 没有声明 `workspace.metadata`,或宿主不提供这个方法 | 补上权限;宿主不提供时 `supports` 为 false,不要调用 | +| `plugin.host.unsupportedOption` | 带了契约没有的参数 | `details.option` 指出是哪个参数 | + +### path 与 hostPath + +`hostPath` 是远端主机上的 POSIX 绝对路径,只用于在远端主机上运行的东西:进程参数和工作目录、调试配置的 `program` 和 `cwd`、语言服务器的 `initializationOptions`。它在运行 Lithe 的这台机器上不对应任何文件,后端永远不在本地读写它;工作区文件按 `{ rootID, path }` 通过文件服务读取。 + +为了不把两者混用,官方 SDK 给 `hostPath` 一个单独的类型,不能直接交给本地文件或进程接口: + +| SDK | 远端路径类型 | 取出字符串 | +| --- | --- | --- | +| Node.js | `HostPath`(不是字符串,`fs`、`path` 会拒绝它) | `.value` | +| Go | `lithe.HostPath` | `.String()` | +| Rust | `HostPath`(不能转换成 `Path`) | `.as_str()` | +| Java | `Host.HostPath`(不是 `String`) | `.value()` | + +写进 JSON 时,四个 SDK 都把它写成那个字符串。 + +后端要为每个根目录决定进程用哪个路径时,用 `processRoots`。它接收 `listContexts` 或 `getContext` 返回的完整上下文:`local` 上下文直接返回各根目录的 `path`,不请求宿主;其他 authority 调用 `getHostPaths` 返回 `hostPath`。只传 `{ contextID, generation }` 时看不出 authority,SDK 在本地失败为 `sdk.host.invalidContext`。 + +### 远程上下文现在能用哪些服务 + +| 服务 | 对远程上下文 | +| --- | --- | +| `listContexts`、`getContext`、`getFolders` | 可用,返回上面的 `authority` 和不带 `path` 的根目录 | +| `getHostPaths` | 契约已定义;Lithe 桌面端还没有注册,`supports` 返回 false | +| 工作区文件、搜索、监听(`readDirectory`、`stat`、`readFile`、`findFiles`、`findText`、`watch`) | `plugin.host.authorityUnsupported`;宿主不会读取本地占位目录,也不会改在本地执行 | +| 原生终端(`terminal/create`、`reopen`) | 首个实现只支持本地,远程上下文为 `plugin.host.authorityUnsupported`,不会在本地启动任何东西 | +| 插件函数中转(`functions/invoke`) | 和本地上下文一样转发;被调用的插件用 `getContext` 得知 authority,中转不读也不改参数和结果里的路径 | + +契约目前没有定义在远端主机上启动插件进程(语言服务器、构建、运行、调试)的规则。后端不要假定这些进程会在远端运行,也不要在本地替远程工作区运行它们。 + +### 两个与远端有关的错误码 + +| 代码 | 数值 | 含义 | 后端怎么做 | +| --- | --- | --- | --- | +| `plugin.host.remoteDisconnected` | `-32078` | 操作进行中和远端主机断开,不知道它是否已在远端生效 | 上下文恢复后先重新读取状态再决定,不要自动重放修改 | +| `plugin.host.platformUnavailable` | `-32079` | 插件没有适用于远端 `platform` 的包或受管运行时,请求需要的进程不能在那里运行 | 告诉用户缺少哪个平台;不要退回到在本地运行 | + +### Node.js 示例 + +```js +const host = context.host; +const workspace = context.workspaceContext; +if (workspace && await host.supports('lithe/host/workspace/getHostPaths')) { + const full = await host.workspace.getContext(workspace); + const { folders } = await host.workspace.processRoots(full); + for (const root of folders) { + // 本地根目录有 path;远程根目录有 hostPath(HostPath)。 + const cwd = root.path ?? root.hostPath.value; + // ... + } + // 只要部分根目录: + const some = await host.workspace.getHostPaths(workspace, { rootIDs: [full.folders[0].rootID] }); +} +``` + +### Go 示例 + +```go +full, err := host.Workspace().GetContext(*workspace) +if err != nil { + return nil, err +} +roots, err := host.Workspace().ProcessRoots(full) +if err != nil { + return nil, err +} +for _, root := range roots { + cwd := root.Path + if cwd == "" { + cwd = root.HostPath.String() + } + // ... +} +// 只要部分根目录:host.Workspace().GetHostPaths(*workspace, rootID) +``` + +### Rust 示例 + +```rust +use lithe_plugin_sdk::ProcessRoot; + +let full = host.workspace().get_context(&workspace)?; +for root in host.workspace().process_roots(&full)? { + match root { + ProcessRoot::Local { root_id, path } => { /* 本机路径 */ } + ProcessRoot::Remote { root_id, host_path } => { /* 远端路径:host_path.as_str() */ } + } +} +// 全部根目录:host.workspace().get_host_paths(&workspace, None) +// 部分根目录:host.workspace().get_host_paths(&workspace, Some(&[root_id])) +``` + +### Java 示例 + +```java +Map full = context.host().workspace().getContext(workspace).get(); +for (Host.ProcessRoot root : context.host().workspace().processRoots(full).get()) { + if (root.isRemote()) { + Host.HostPath hostPath = root.hostPath(); // 远端路径:hostPath.value() + } else { + String path = root.path(); // 本机路径 + } +} +// 全部根目录:workspace().getHostPaths(context) +// 部分根目录:workspace().getHostPaths(context, Arrays.asList(rootId)) +``` + +## English + +When a workspace is on a remote host, the plugin backend still runs on the machine that runs Lithe: a plugin has one backend process, shared by every window and workspace. This page says how a backend recognises a remote context, how it gets the paths of the roots on the remote host, and which host services serve a remote context today. The [contract](../contract/v1/README.md#public-document-file-and-window-methods) is authoritative; the common fields of a context are in [Plugin backend: workspace](plugin-backend-workspace.md). + +The SDK wrappers on this page (`getHostPaths`, `processRoots`, and a type of its own for remote paths) are not released yet. They ship with the next release of the Node.js, Java, and Rust SDKs and the next tag of the Go SDK. + +### Recognising a remote context + +In a context from `listContexts` or `getContext`, `authority` says where the workspace is: + +```json +"authority": { "kind": "remote", "id": "c-7d41", "platform": { "os": "linux", "arch": "x86_64" } } +``` + +| Field | Meaning | +| --- | --- | +| `kind` | `local` or `remote` | +| `id` | `remote` only; an opaque connection ID that a backend does not parse | +| `platform` | `remote` only; the remote host's operating system and CPU architecture, with the values of [managed runtimes](../contract/v1/README.md#managed-runtimes): `os` is `linux` and `arch` is `arm64` or `x86_64`. A backend uses it to choose the package or runtime a process on the host needs, and ignores an `os` or `arch` it does not know, as a later host may connect to other systems | + +The `folders` of a remote context have `rootID` and `name` but no `path`. The local directory the host keeps for a remote workspace is an empty placeholder, not the workspace, and a backend neither reads nor writes it. + +### Remote paths with getHostPaths + +The paths of the roots on the remote host are not part of the context; a backend asks for them with `lithe/host/workspace/getHostPaths`. A backend that does not need them never sees the remote user name or directory layout, and a backend written before remote workspaces cannot take one for a local path. + +| Request | Result | +| --- | --- | +| `{ context: { contextID, generation }, rootIDs?: [] }` | `{ folders: [{ rootID, hostPath }] }` | + +- Permission: the manifest declares `workspace.metadata`. It grants this method on its own, not with the `workspace` service, and a host that does not serve the method leaves it out of `getCapabilities`. Probe `supports("lithe/host/workspace/getHostPaths")` before calling it. +- Without `rootIDs`, `folders` holds every root in `getFolders` order. With it, `rootIDs` is 1 to 256 distinct root IDs in the key alphabet (ASCII letters, digits, `.`, `_`, `:`, `-`; 1 to 128 characters), and `folders` holds those roots in that order. The SDKs refuse other `rootIDs` locally with `sdk.host.invalidParams` and send nothing. +- Failures: + +| Code | When | What the backend does | +| --- | --- | --- | +| `plugin.host.authorityUnsupported` | The context is `local` | Use the `path` its roots already carry | +| `plugin.host.notFound` | The context has no such root ID | Read `getFolders` again | +| `plugin.host.contextExpired` | The context closed, or its `generation` changed | Every path obtained before is void; resolve the original target again, never the focused window | +| `plugin.host.permissionDenied` | No grant for the method: the manifest does not declare `workspace.metadata`, or the host does not serve the method | Declare the permission; when the host does not serve it, `supports` is false, so do not call it | +| `plugin.host.unsupportedOption` | A param the contract does not have | `details.option` names it | + +### path and hostPath + +`hostPath` is an absolute POSIX path on the remote host. A backend uses it only in what runs on that host: process arguments and working directories, a debug configuration's `program` and `cwd`, a language server's `initializationOptions`. It names no file on the machine that runs Lithe, so a backend never reads or writes it locally; files of the workspace are read through the file services by `{ rootID, path }`. + +So that the two are not mixed up, the official SDKs give `hostPath` a type of its own that local file and process APIs do not take: + +| SDK | Remote path type | As a string | +| --- | --- | --- | +| Node.js | `HostPath` (not a string; `fs` and `path` refuse it) | `.value` | +| Go | `lithe.HostPath` | `.String()` | +| Rust | `HostPath` (converts to no `Path`) | `.as_str()` | +| Java | `Host.HostPath` (not a `String`) | `.value()` | + +All four SDKs write it into JSON as that string. + +When a backend needs, for each root, the path a process uses, it calls `processRoots` with a full context from `listContexts` or `getContext`. For a `local` context it returns the roots' `path` without asking the host; for any other authority it calls `getHostPaths` and returns `hostPath`. A bare `{ contextID, generation }` does not say the authority, and the SDK fails it locally with `sdk.host.invalidContext`. + +### Which services serve a remote context today + +| Service | For a remote context | +| --- | --- | +| `listContexts`, `getContext`, `getFolders` | Served, with the `authority` above and roots without `path` | +| `getHostPaths` | Defined by the contract; the Lithe desktop does not register it yet, so `supports` is false | +| Workspace files, search, and watching (`readDirectory`, `stat`, `readFile`, `findFiles`, `findText`, `watch`) | `plugin.host.authorityUnsupported`; the host never reads the local placeholder or runs the operation locally instead | +| Native terminals (`terminal/create`, `reopen`) | The first release is local only; a remote context is `plugin.host.authorityUnsupported`, and nothing starts locally | +| The function relay (`functions/invoke`) | Relayed as for a local context; the callee learns the authority from `getContext`, and the relay neither reads nor rewrites paths in the params or the result | + +The contract does not yet define how a plugin's processes (language servers, builds, runs, debugging) start on a remote host. A backend does not assume they run there, and does not run them locally for a remote workspace instead. + +### Two codes for remote hosts + +| Code | Number | Meaning | What the backend does | +| --- | --- | --- | --- | +| `plugin.host.remoteDisconnected` | `-32078` | The connection to the remote host was lost while the operation ran; whether it took effect on the host is unknown | Once the context is current again, read the state before deciding; never replay a change on its own | +| `plugin.host.platformUnavailable` | `-32079` | The plugin has no package or managed runtime for the remote host's `platform`, so the process the request needs cannot run there | Tell the user which platform is missing; never fall back to running locally | + +### Node.js + +```js +const host = context.host; +const workspace = context.workspaceContext; +if (workspace && await host.supports('lithe/host/workspace/getHostPaths')) { + const full = await host.workspace.getContext(workspace); + const { folders } = await host.workspace.processRoots(full); + for (const root of folders) { + // A local root has `path`; a remote one has `hostPath`, a HostPath. + const cwd = root.path ?? root.hostPath.value; + // ... + } + // Some roots only: + const some = await host.workspace.getHostPaths(workspace, { rootIDs: [full.folders[0].rootID] }); +} +``` + +### Go + +```go +full, err := host.Workspace().GetContext(*workspace) +if err != nil { + return nil, err +} +roots, err := host.Workspace().ProcessRoots(full) +if err != nil { + return nil, err +} +for _, root := range roots { + cwd := root.Path + if cwd == "" { + cwd = root.HostPath.String() + } + // ... +} +// Some roots only: host.Workspace().GetHostPaths(*workspace, rootID) +``` + +### Rust + +```rust +use lithe_plugin_sdk::ProcessRoot; + +let full = host.workspace().get_context(&workspace)?; +for root in host.workspace().process_roots(&full)? { + match root { + ProcessRoot::Local { root_id, path } => { /* a path on this machine */ } + ProcessRoot::Remote { root_id, host_path } => { /* on the remote host: host_path.as_str() */ } + } +} +// Every root: host.workspace().get_host_paths(&workspace, None) +// Some roots: host.workspace().get_host_paths(&workspace, Some(&[root_id])) +``` + +### Java + +```java +Map full = context.host().workspace().getContext(workspace).get(); +for (Host.ProcessRoot root : context.host().workspace().processRoots(full).get()) { + if (root.isRemote()) { + Host.HostPath hostPath = root.hostPath(); // on the remote host: hostPath.value() + } else { + String path = root.path(); // a path on this machine + } +} +// Every root: workspace().getHostPaths(context) +// Some roots: workspace().getHostPaths(context, Arrays.asList(rootId)) +``` diff --git a/shared/plugins/guides/plugin-backend-workspace.md b/shared/plugins/guides/plugin-backend-workspace.md index d24961a4..2210367a 100644 --- a/shared/plugins/guides/plugin-backend-workspace.md +++ b/shared/plugins/guides/plugin-backend-workspace.md @@ -136,7 +136,7 @@ | `contextID` | 窗口显示这个工作区期间不变。窗口切到别的工作区时,旧上下文关闭、新上下文换新 ID,所以按 ID 缓存的状态不会串到别的工作区 | | `generation` | 从 1 起;同一工作区的根目录或来源变化时加一。请求里带旧的 `generation`,或上下文已关闭,会得到 `plugin.host.contextExpired`,重新 `listContexts` 即可 | | `rootID` | 同一位置跨重启稳定,不暴露路径;按插件加密派生,两个插件对同一目录看到的 ID 不同 | -| `path` | 只有本地工作区有。远程工作区(`authority.kind` 为 `remote`,另有不透明的 `authority.id`)没有 `path`,宿主在本地为它保留的目录只是空占位 | +| `path` | 只有本地工作区有。远程工作区(`authority.kind` 为 `remote`,另有不透明的 `authority.id` 和远端主机的 `authority.platform`)没有 `path`,宿主在本地为它保留的目录只是空占位;根目录在远端主机上的路径另用 `getHostPaths` 获取,见[远程工作区](plugin-backend-remote-workspaces.md) | | `stateDirectory` | 插件与工作区私有,在插件包和应用包之外,插件被禁用或更新后保留、卸载时删除。只有 `getContext` 返回它并在那时创建;`listContexts` 不创建目录 | 常用请求: @@ -146,6 +146,7 @@ | `lithe/host/workspace/listContexts` | 无 | `{ revision, contexts }`,条目不含 `stateDirectory`;`revision` 在上下文打开、关闭或变化时增长 | | `lithe/host/workspace/getContext` | `{ context: { contextID, generation } }` | 完整上下文 | | `lithe/host/workspace/getFolders` | `{ context: { contextID, generation } }` | `{ folders }` | +| `lithe/host/workspace/getHostPaths` | `{ context: { contextID, generation }, rootIDs? }` | `{ folders: [{ rootID, hostPath }] }`;只对远程上下文,单独授权 | 页面调用后端函数时,宿主会按页面所在窗口填好上下文:后端在 `lithe/function/invoke` 的 `params.context` 里收到 `{ contextID, generation }`,直接拿它调 `getContext`。 @@ -250,6 +251,8 @@ | `plugin.host.methodNotDeclared` | `-32024` | 方法或 `workspace/executeCommand` 的命令不在服务器声明的会话范围内 | | `plugin.host.toolUnresolved` | `-32025` | 请求里的工具定义在这个工作区解析不到可执行文件;`details` 是 `{ tool, reason }` | | `plugin.host.foreignContribution` | `-32026` | 指名的服务器或贡献属于别的插件 | +| `plugin.host.remoteDisconnected` | `-32078` | 操作进行中和远端主机断开,不知道它是否已在远端生效;上下文恢复后先重新读取状态再决定,不要自动重放修改 | +| `plugin.host.platformUnavailable` | `-32079` | 插件没有适合远端主机 `platform` 的程序包或托管运行时,所需进程无法在那里运行;告诉用户缺什么 | `-32000` 到 `-32009` 留给后端自己的失败,宿主号码从 `-32010` 起。跨插件调用另有 `plugin.function.failed`(`-32070`)和 `plugin.function.invalidResult`(`-32071`),见第 11 节。 @@ -280,7 +283,7 @@ - **被调方收到的 `caller`。** 中转的 `lithe/function/invoke` 顶层多一个 `caller: { pluginID }`,由 Core 按调用方会话写入;没有这个字段就表示宿主发起的调用。要按调用方判断的被调方只读这个顶层字段,不读 `params` 里自称的插件 ID。 - **嵌套调用。** 被调方在处理中转调用时再发起调用,要把这次调用顶层的 `operationID` 填进 `parentOperationID`,Core 才知道嵌套调用属于哪条调用链;调用链最长 4 次,调用链上已有的插件不能再被调用(`plugin.function.callCycle`)。 - **信任不传递。** 被调方不得接受调用方给的可执行路径或命令行去启动进程。 -- 远程工作区的上下文被拒绝(`plugin.host.authorityUnsupported`)。 +- 远程工作区的上下文照常中转:后端都在运行 Lithe 的机器上,被调方用 `getContext` 得知来源,它对这个上下文的宿主请求按各服务的规则处理;Core 不改写路径。 官方 SDK 封装了 `functions/providers`、`functions/invoke`,被调函数能读到 `caller`;`parentOperationID` 不传时,SDK 取正在处理的 `lithe/function/invoke` 的 `operationID`。 下面以 Node.js 为例,[Java](../sdk/java/README.md#calling-other-plugins) 和 [Rust](../sdk/rust/README.md#calling-other-plugins) 的对应方法见各自 README: @@ -459,7 +462,7 @@ A context is "one workspace open in one window": | `contextID` | Stable while the window shows this workspace. When the window switches to another workspace, the old context closes and the new one gets a new ID, so state cached by ID never leaks into another workspace | | `generation` | Starts at 1 and increments when the same workspace's roots or authority change. A request with a stale `generation`, or for a closed context, gets `plugin.host.contextExpired`; call `listContexts` again | | `rootID` | Stable for the same location across restarts and does not reveal the path; derived cryptographically per plugin, so two plugins see different IDs for the same folder | -| `path` | Present only for local workspaces. A remote workspace (`authority.kind` is `remote`, with an opaque `authority.id`) has no `path`, and the local directory the host keeps for it is only an empty placeholder | +| `path` | Present only for local workspaces. A remote workspace (`authority.kind` is `remote`, with an opaque `authority.id` and the remote host's `authority.platform`) has no `path`, and the local directory the host keeps for it is only an empty placeholder; the roots' paths on the remote host come from `getHostPaths`, see [remote workspaces](plugin-backend-remote-workspaces.md) | | `stateDirectory` | Private to the plugin and the workspace, outside the plugin package and the app bundle; it survives disabling and updating the plugin and is deleted on uninstall. Only `getContext` returns it, creating it at that moment; `listContexts` creates no directory | Common requests: @@ -469,6 +472,7 @@ Common requests: | `lithe/host/workspace/listContexts` | none | `{ revision, contexts }`; entries have no `stateDirectory`; `revision` grows whenever a context opens, closes, or changes | | `lithe/host/workspace/getContext` | `{ context: { contextID, generation } }` | The full context | | `lithe/host/workspace/getFolders` | `{ context: { contextID, generation } }` | `{ folders }` | +| `lithe/host/workspace/getHostPaths` | `{ context: { contextID, generation }, rootIDs? }` | `{ folders: [{ rootID, hostPath }] }`; remote contexts only, granted on its own | When a page calls a backend function, the host fills in the context of the page's window: the backend receives `{ contextID, generation }` in `params.context` of `lithe/function/invoke` and can pass it straight to `getContext`. @@ -573,6 +577,8 @@ Host failures are typed: each JSON-RPC number maps one-to-one to an `error.data. | `plugin.host.methodNotDeclared` | `-32024` | The method, or the `workspace/executeCommand` command, is not in the server's declared session | | `plugin.host.toolUnresolved` | `-32025` | A tool definition the request names resolves to no executable for this workspace; `details` is `{ tool, reason }` | | `plugin.host.foreignContribution` | `-32026` | The named server or contribution belongs to another plugin | +| `plugin.host.remoteDisconnected` | `-32078` | The connection to the remote host was lost while the operation ran, so whether it took effect there is unknown; once the context is current, read the state again before deciding, and do not replay a change automatically | +| `plugin.host.platformUnavailable` | `-32079` | The plugin has no package or managed runtime for the remote host's `platform`, so the process it needs cannot run there; tell the user what is missing | `-32000` through `-32009` are reserved for the backend's own failures; host numbers start at `-32010`. Cross-plugin calls add `plugin.function.failed` (`-32070`) and `plugin.function.invalidResult` (`-32071`); see section 11. @@ -603,7 +609,7 @@ A plugin function is private to its plugin unless the plugin exports it. An expo - **`caller` in a relayed call.** The `lithe/function/invoke` a provider receives has one more top-level field, `caller: { pluginID }`, which Core writes from the calling session; its absence means the host started the call. A provider that decides by who is asking reads only this top-level field, never a plugin ID that `params` claims. - **Nested calls.** When a provider makes a call while serving a relayed call, it puts that call's top-level `operationID` in `parentOperationID`, so Core knows which call chain the new call belongs to. A chain has at most 4 calls, and a plugin already on the chain cannot be called again (`plugin.function.callCycle`). - **Trust is not transitive.** A provider must not accept an executable path or command line from its caller and start a process with it. -- A call whose context is a remote workspace is refused (`plugin.host.authorityUnsupported`). +- A call for a remote workspace's context is relayed like any other: every backend runs on the machine that runs Lithe, the provider learns the authority from `getContext`, and its own host requests for that context follow the rules of each service; Core rewrites no path. The official SDKs wrap `functions/providers` and `functions/invoke` and expose `caller` to the called function; when `parentOperationID` is omitted, the SDK uses the `operationID` of the `lithe/function/invoke` being handled. The example below uses Node.js; for the matching methods in [Java](../sdk/java/README.md#calling-other-plugins) and [Rust](../sdk/rust/README.md#calling-other-plugins), see their READMEs: diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 060c198d..ce1a5463 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -54,9 +54,9 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-30 | 调试适配器 | 部分完成 | [`debugAdapters`](../contract/v1/README.md#debug-adapters) 与宿主的 DAP 会话;[`features`、`defaults`](../contract/v1/README.md#adapter-features-and-defaults)(热代码替换、步进过滤器);后端发起的 [`debug/start`](../contract/v1/README.md#run-and-debug-sessions)(权限 `debug.start`) | 后端只能在本插件自己声明的适配器上启动会话,不能使用其他插件的适配器 | [调试适配器](domains/debug-adapters.md) | | API-31 | VCS 提供者 | 既有能力 | [`vcsProviders`](../contract/v1/README.md#vcs-providers) | 不含内置 Git 的公共读取(见 API-42);Lithe 桌面端未声明 `vcsProviders` | [VCS](domains/vcs.md) | | API-33 | 项目生成器 | 既有能力 | [`projectGenerators`](../contract/v1/README.md#project-generators) | — | [项目生成器](domains/project-generators.md) | -| API-35 | 插件间调用与依赖 | 部分完成 | 第一阶段:[`pluginFunctions`](../contract/v1/README.md#cross-plugin-calls)(清单 `exports`、`calls` 声明,不授予清单权限)与 [`functions/providers`、`functions/invoke`](../contract/v1/README.md#discovery-and-invocation):经 Core 中转,调用另一个已启用插件导出的函数;信任不传递,不是安装依赖(本机工作区) | 依赖与导出的安装闭包、版本求解、远程 Provider;在只于启动时注册后端插件的宿主上,新安装或更新的后端插件要重启 Lithe 后才会出现在 `providers` 里(见 [Hot activation](../contract/v1/README.md#hot-activation)) | [插件后端](domains/backend.md) | +| API-35 | 插件间调用与依赖 | 部分完成 | 第一阶段:[`pluginFunctions`](../contract/v1/README.md#cross-plugin-calls)(清单 `exports`、`calls` 声明,不授予清单权限)与 [`functions/providers`、`functions/invoke`](../contract/v1/README.md#discovery-and-invocation):经 Core 中转,调用另一个已启用插件导出的函数;信任不传递,不是安装依赖;远程工作区的上下文同样中转 | 依赖与导出的安装闭包、版本求解、远程 Provider;在只于启动时注册后端插件的宿主上,新安装或更新的后端插件要重启 Lithe 后才会出现在 `providers` 里(见 [Hot activation](../contract/v1/README.md#hot-activation)) | [插件后端](domains/backend.md) | | API-37 | 环境信息与语言包 | 部分完成 | `getCapabilities` 返回协议版本、可用方法、限制和后端运行位置(`backendAuthority`);插件设置文字的[包内翻译 `l10n/<语言>.json`](../contract/v1/README.md#translations),按界面语言挑选,缺的回退到清单原文;翻译可为设置区域追加其他语言的搜索关键词;插件视图事件带界面语言,后端按它返回文字 | 设置以外插件文字的翻译、环境信息、语言和主题变化事件 | [插件后端](domains/backend.md)、[设置](domains/settings.md) | -| API-40 | 工作区 authority | 部分完成 | 工作区上下文带 `local` 或 `remote`;文件和编辑器方法对远程上下文明确返回 `plugin.host.authorityUnsupported` | 远程执行 | [插件后端](domains/backend.md) | +| API-40 | 工作区 authority | 部分完成 | [工作区上下文](../contract/v1/README.md#workspace-contexts-and-capability-discovery)带 `local` 或 `remote`,远程的另带远端主机的 `platform`(`os`、`arch`);`workspace/getHostPaths` 单独给出根目录在远端主机上的路径;文件和编辑器方法对远程上下文明确返回 `plugin.host.authorityUnsupported`;远程专用的失败码 `remoteDisconnected`、`platformUnavailable` | 远程执行(进程、语言服务器、调试器在远端主机上运行)、贡献的运行位置 `placement` | [插件后端](domains/backend.md)、[远程工作区](../guides/plugin-backend-remote-workspaces.md) | | API-41 | 激活事件与启动预算 | 部分完成 | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation)、`onCommand`、后台两路并发启动、`initialize` 超时、有界通知队列 | 按工作区内容匹配激活、全局冷启动预算 | [插件后端](domains/backend.md) | ### 计划中的 API @@ -134,6 +134,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-30 | `debug/start` | 在本插件自己声明的调试适配器上启动 launch 或 attach 调试会话,返回 `sessionID` | `debug.start` | 0 | | API-35 | `functions/providers` | 列出导出某函数、已启用、且不是调用方自己的插件及其导出版本 | 无清单权限,需在 `pluginFunctions.calls` 声明该函数 | 0 | | API-35 | `functions/invoke` | 经 Core 调用另一个插件导出的函数,可带 `parentOperationID` 标明所属调用链,返回 `{value}` | 无清单权限,需在 `pluginFunctions.calls` 声明该函数 | 0 | +| API-40 | `workspace/getHostPaths` | 远程上下文的根目录在远端主机上的绝对路径 `hostPath`,可用 `rootIDs` 指定根目录和顺序;只用在远端运行的进程参数、工作目录和语言服务器、调试器配置里;本地上下文返回 `plugin.host.authorityUnsupported` | `workspace.metadata`,单独的方法授权(只有服务授权得到 `permissionDenied`) | 0 | 快捷键导入提供者另有 `lithe/host/keymapImport/listInputs`、`lithe/host/keymapImport/readChunk` 两个方法,属于 `litheKeymapImport` 协议,不在 API-01–44 内,见[快捷键导入](domains/keymap-import.md)。 @@ -227,9 +228,9 @@ Status meanings: | API-30 | Debug adapters | Partial | [`debugAdapters`](../contract/v1/README.md#debug-adapters) and the host's DAP sessions; [`features` and `defaults`](../contract/v1/README.md#adapter-features-and-defaults) (hot code replace, step filters); backend-started [`debug/start`](../contract/v1/README.md#run-and-debug-sessions) (permission `debug.start`) | A backend can start sessions only on adapters its own plugin declares, not on another plugin's adapters | [Debug adapters](domains/debug-adapters.md) | | API-31 | VCS providers | Existing | [`vcsProviders`](../contract/v1/README.md#vcs-providers) | Public reads of built-in Git are not included (see API-42); the Lithe desktop client does not declare `vcsProviders` | [VCS](domains/vcs.md) | | API-33 | Project generators | Existing | [`projectGenerators`](../contract/v1/README.md#project-generators) | — | [Project generators](domains/project-generators.md) | -| API-35 | Cross-plugin calls and dependencies | Partial | Phase one: [`pluginFunctions`](../contract/v1/README.md#cross-plugin-calls) (`exports` and `calls` in the manifest, granting no manifest permission) and [`functions/providers` and `functions/invoke`](../contract/v1/README.md#discovery-and-invocation): Core relays a call to a function another enabled plugin exports; trust is not transitive and this is not an install dependency (local workspaces) | The install closure of dependencies and exports, version solving, remote providers; on a host that registers backend plugins only when it launches, a newly installed or updated backend plugin appears in `providers` only after Lithe restarts (see [Hot activation](../contract/v1/README.md#hot-activation)) | [Plugin backend](domains/backend.md) | +| API-35 | Cross-plugin calls and dependencies | Partial | Phase one: [`pluginFunctions`](../contract/v1/README.md#cross-plugin-calls) (`exports` and `calls` in the manifest, granting no manifest permission) and [`functions/providers` and `functions/invoke`](../contract/v1/README.md#discovery-and-invocation): Core relays a call to a function another enabled plugin exports; trust is not transitive and this is not an install dependency; calls for a remote workspace's context are relayed too | The install closure of dependencies and exports, version solving, remote providers; on a host that registers backend plugins only when it launches, a newly installed or updated backend plugin appears in `providers` only after Lithe restarts (see [Hot activation](../contract/v1/README.md#hot-activation)) | [Plugin backend](domains/backend.md) | | API-37 | Environment info and l10n | Partial | `getCapabilities` returns the protocol version, usable methods, limits, and where the backend runs (`backendAuthority`); [packaged translations `l10n/.json`](../contract/v1/README.md#translations) of plugin settings text, chosen by interface language and falling back to the manifest text; translations may add search keywords in other languages to settings regions; plugin view events carry the interface language, and the backend returns text in it | Translations of plugin text beyond settings, environment info, language and theme change events | [Plugin backend](domains/backend.md), [Settings](domains/settings.md) | -| API-40 | Workspace authority | Partial | Workspace contexts carry `local` or `remote`; file and editor methods refuse a remote context with `plugin.host.authorityUnsupported` | Remote execution | [Plugin backend](domains/backend.md) | +| API-40 | Workspace authority | Partial | [Workspace contexts](../contract/v1/README.md#workspace-contexts-and-capability-discovery) carry `local` or `remote`, and a remote one also the remote host's `platform` (`os`, `arch`); `workspace/getHostPaths` gives the roots' paths on the remote host on its own; file and editor methods refuse a remote context with `plugin.host.authorityUnsupported`; the remote failure codes `remoteDisconnected` and `platformUnavailable` | Remote execution (processes, language servers, and debuggers running on the remote host), the `placement` of contributions | [Plugin backend](domains/backend.md), [Remote workspaces](../guides/plugin-backend-remote-workspaces.md) | | API-41 | Activation events and startup budget | Partial | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation), `onCommand`, two concurrent background starts, `initialize` timeout, bounded notification queues | Activation by workspace content, a global cold-start budget | [Plugin backend](domains/backend.md) | ### Planned APIs @@ -307,6 +308,7 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | API-30 | `debug/start` | Starts a launch or attach debug session on a debug adapter the plugin itself declares, and returns a `sessionID` | `debug.start` | 0 | | API-35 | `functions/providers` | Lists the enabled plugins, other than the caller, that export a function, with their exported versions | No manifest permission; the function must be declared in `pluginFunctions.calls` | 0 | | API-35 | `functions/invoke` | Calls a function another plugin exports, relayed by Core; can carry `parentOperationID` to name the call chain it belongs to, and returns `{value}` | No manifest permission; the function must be declared in `pluginFunctions.calls` | 0 | +| API-40 | `workspace/getHostPaths` | Gives the absolute paths `hostPath` of a remote context's root folders on the remote host, optionally for the roots `rootIDs` names, in that order; used only in the arguments, working directories, and language server or debugger configuration of what runs on that host; a local context gets `plugin.host.authorityUnsupported` | `workspace.metadata`, as a method grant of its own (the service grant alone gets `permissionDenied`) | 0 | Shortcut import providers also have two methods, `lithe/host/keymapImport/listInputs` and `lithe/host/keymapImport/readChunk`. They belong to the `litheKeymapImport` protocol, outside API-01–44; see [Shortcut import](domains/keymap-import.md). diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 86cc63ec..b2ac6d54 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -80,7 +80,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https - 插件声明的运行配置类型只能运行,不能调试。 - 不属于任何工具窗口的 `ui` 命令。 - VCS 提供者的逐行追溯(annotation)、文件历史、文件操作、元数据监听、认证、历史提交差异、项目树与编辑器行号栏状态,以及 `lithe/vcs/execution` 控制台输出。 -- 后端宿主服务:工作区文件与搜索(`workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText`)和 `preview/openHTML` 尚未注册,请求这些权限的插件被拒绝。运行期以 `lithe/host/getCapabilities` 的返回为准,见 [API 总表](api-catalog.md)。 +- 后端宿主服务:工作区文件与搜索(`workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText`)和 `preview/openHTML` 尚未注册,请求这些权限的插件被拒绝。`workspace/getHostPaths` 也尚未注册,`supports` 返回 false;它和 `listContexts` 共用 `workspace.metadata`,所以声明该权限的插件不会因此被拒绝,见[远程工作区](../guides/plugin-backend-remote-workspaces.md)。运行期以 `lithe/host/getCapabilities` 的返回为准,见 [API 总表](api-catalog.md)。 ### 进程协议版本 @@ -198,7 +198,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani - Run configuration types a plugin declares run but cannot be debugged. - `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). +- 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. `workspace/getHostPaths` is not registered either, so `supports` is false for it; it shares `workspace.metadata` with `listContexts`, so a plugin that declares that permission is not refused for it, see [remote workspaces](../guides/plugin-backend-remote-workspaces.md). At runtime, the reply of `lithe/host/getCapabilities` is authoritative; see the [API catalog](api-catalog.md). ### Process protocol versions diff --git a/shared/plugins/reference/domains/backend.md b/shared/plugins/reference/domains/backend.md index 0f8a6685..6b0d07ef 100644 --- a/shared/plugins/reference/domains/backend.md +++ b/shared/plugins/reference/domains/backend.md @@ -113,7 +113,7 @@ Core 把中转的调用以 `lithe/function/invoke` 转给被调方。和任何 - 被调方用自己的权限、状态目录和凭据运行;调用方不获得被调方的任何权限,被调方也不获得调用方的。调用方的插件 ID 只出现在 `caller` 字段里,不写进被调方的会话。 - 导出的函数不得接受调用方给的可执行路径、命令行或脚本去启动进程,也不得读写调用方指定的路径而不核对自己的访问范围。调用方需要被调方运行什么,函数应当接收一个由被调方自己解释的请求(任务名、文档),由被调方决定可执行文件。 -- 这不是安装依赖:安装调用方不会连带安装被调方,停用被调方只会让调用找不到提供者;不参与安装闭包,不做版本求解。远程工作区的上下文被拒绝,`plugin.host.authorityUnsupported`;导出的 `context: "workspace"` 只指本地工作区,后端仍在运行 Lithe 的机器上。 +- 这不是安装依赖:安装调用方不会连带安装被调方,停用被调方只会让调用找不到提供者;不参与安装闭包,不做版本求解。导出的 `context: "workspace"` 指本地或远程的工作区:后端都在运行 Lithe 的机器上,所以远程工作区的上下文照常中转。被调方用 `getContext` 得知来源,它对这个上下文的宿主请求按各服务的规则送到远端主机或得到 `plugin.host.authorityUnsupported`;Core 不读也不改写参数和结果里的路径。 - 停用、启用、替换和卸载插件对中转立即生效,不需要重启;宿主用 Core 命令 `lsp.configureFunctionRelay` 发送插件和工作区上下文的快照。只在启动时注册后端插件的宿主上,新安装或更新的后端插件要重启 Lithe 后才会出现在 `providers` 里。 #### 错误码 @@ -217,6 +217,7 @@ Core 把中转的调用以 `lithe/function/invoke` 转给被调方。和任何 ### 相关指南 - [插件后端:工作区上下文与宿主服务](../../guides/plugin-backend-workspace.md) +- [插件后端:远程工作区](../../guides/plugin-backend-remote-workspaces.md) - [从插件打开原生终端](../../guides/native-terminals.md) - [插件接入统一日志](../../guides/plugin-logging.md) @@ -333,7 +334,7 @@ Core forwards a relayed call to the provider as `lithe/function/invoke`. As for - The provider runs with its own permissions, state directory, and credentials. The caller gains none of the provider's, and the provider gains none of the caller's. The caller's plugin ID appears only in the `caller` field, never in the provider's session. - An exported function must not accept an executable path, command line, or script from its caller and start a process with it, nor read or write a path the caller chose without checking it against what the provider itself may access. If a caller needs the provider to run something, the function takes a request the provider interprets (a task name, a document) and the provider decides the executable. -- This is not an install dependency: installing the caller does not install a provider, and disabling a provider only leaves calls without one; it takes no part in the install closure and does no version solving. A call whose context is a remote workspace is refused with `plugin.host.authorityUnsupported`; the exported `context: "workspace"` means a local workspace only, and backends still run on the machine that runs Lithe. +- This is not an install dependency: installing the caller does not install a provider, and disabling a provider only leaves calls without one; it takes no part in the install closure and does no version solving. The exported `context: "workspace"` means a local or a remote workspace: every backend runs on the machine that runs Lithe, so a call for a remote workspace's context is relayed like any other. The provider learns the authority from `getContext`, and its own host requests for that context reach the remote host or get `plugin.host.authorityUnsupported` by the rules of each service; Core neither reads nor rewrites paths in the params or the result. - Disabling, enabling, replacing, and uninstalling a plugin take effect for the relay at once, with no restart; the host sends the snapshot of plugins and workspace contexts with the Core command `lsp.configureFunctionRelay`. On a host that registers backend plugins only when it launches, a newly installed or updated backend plugin appears in `providers` only after Lithe restarts. #### Error codes @@ -437,5 +438,6 @@ Backend rejections are in [`manifest/invalid-manifests.json`](../../contract/v1/ ### Related guides - [Plugin backend: workspace contexts and host services](../../guides/plugin-backend-workspace.md) +- [Plugin backend: remote workspaces](../../guides/plugin-backend-remote-workspaces.md) - [Open a native Lithe terminal from a plugin](../../guides/native-terminals.md) - [Plugin logging](../../guides/plugin-logging.md) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 44ff5c5e..9ce86726 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,9 +14,7 @@ ## 待合入 -- [#141](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/141),[@1lck](https://github.com/1lck),**`languageServers` 1**(API-25、API-29、API-31):语言服务器新增可选 `executesProjectCode`(不写按 `true`),启动请求新增 `projectCodeAllowed`(不写按未信任,[1lck/Lithe-IDEA#2208](https://github.com/1lck/Lithe-IDEA/issues/2208))。未信任的工作区里,`plugins.declarative.languageServerLaunchPlan` 和 `plugins.languageServers.decodeLaunch` 只给声明 `executesProjectCode: false` 的语言服务器计划;自带进程的构建提供者按 `buildSystems[].provider.executesProjectCode` 判断,共用语言服务器的跟随该服务器;VCS 提供者一律不给计划。拒绝码是新的 `plugin.launch.untrustedWorkspace`。插件后端和独立调试适配器不受影响。用 `executesProjectCode` 要声明 `requires.languageServers: 1`。没有新增宿主方法、通知或 SDK 版本。 -- [#139](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/139),[@1lck](https://github.com/1lck),**`buildSystems` 2**(API-29):构建提供者的 `application` 运行声明(含 `entrypoints: true`)可以通过 `debug.configurationType` 复用已注册的连接调试器。`lithe/build/prepareRun` 复用原有 `launchOptions.debug`,入口运行仍不带 `target`。已有服务运行声明继续适用旧版本。没有新增 RPC 方法、通知或 SDK 版本。 -- [#135](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/135),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`toolDefinitions` 0 内的行为修正(API-23):外部安装的 `executableLayouts` 文件链接到另一个文件名时,`toolchains.candidates` 的待探针路径和 `toolchains.resolve` 的 `executable` 改为规范主目录下的布局路径,不再是链接目标。rustup 把 `cargo`、`rust-analyzer` 链接到自身、按启动时的名字决定运行哪个工具,以前 Core 返回 `rustup`,版本探针失败。链接目标的类型、可执行位和越界检查不变;同名链接仍返回规范路径。没有新增字段、版本号、宿主方法、通知或 SDK 版本。 +- [#151](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/151),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-05、API-35、API-40):远程工作区上下文的 `authority` 新增 `platform: { os, arch }`,取值同托管运行时(`os` 为 `linux`,`arch` 为 `arm64` 或 `x86_64`),本地上下文没有这个字段。新增宿主方法 `workspace/getHostPaths`:返回远程上下文的根目录在远端主机上的绝对 POSIX 路径 `hostPath`,可选的 `rootIDs`(1–256 个不重复的根目录 ID)决定返回哪些根目录和顺序;它是 `workspace.metadata` 下单独的方法授权,本地上下文返回 `plugin.host.authorityUnsupported`,未知根目录返回 `plugin.host.notFound`;声明 `workspace.metadata` 的插件,启动计划的 `backend.hostServices` 因此多出 `lithe/host/workspace/getHostPaths`,宿主传给 `lsp.startServer` 时去掉自己没有注册处理器的方法授权,后端调用它们得到 `plugin.host.permissionDenied`。新增失败码 `plugin.host.remoteDisconnected`(`-32078`,操作进行中与远端主机断开)和 `plugin.host.platformUnavailable`(`-32079`,插件没有适合远端平台的程序包或托管运行时)。插件函数中转不再拒绝远程工作区的上下文,导出的 `context: "workspace"` 指两种来源的工作区,Core 不读也不改写参数和结果里的路径。四个官方 SDK 新增远端平台读取、`getHostPaths`、按来源选择进程所用路径的辅助方法和两个失败码,`path` 与 `hostPath` 是不同类型。没有新增能力版本、通知或 SDK 版本。 ## 按协议查首次出现 @@ -49,14 +47,14 @@ | `buildProviders` | 1 | 2026-11-18 | [#89](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/89) | | `buildSystems` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildSystems` | 1 | 2026-11-19 | [#112](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/112) | -| `buildSystems` | 2 | 待合入 | [#139](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/139) | +| `buildSystems` | 2 | 2026-11-20 | [#139](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/139) | | `commandInstallers` | 0 | 2026-11-15 | [#53](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/53) | | `commandInstallers` | 1 | 2026-11-20 | [#133](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/133) | | `debugAdapters` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `executionProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `keymapImportProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `languageServers` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | -| `languageServers` | 1 | 待合入 | [#141](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/141) | +| `languageServers` | 1 | 2026-11-20 | [#141](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/141) | | `languages` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `outputLinkMatchers` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `packageTrust` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | @@ -151,6 +149,7 @@ | API-23 | `run/start`:`temporaryFiles` 增加 `{name, base64}` 字节文件 | 0 | 2026-11-13 | [#23](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/23) | | API-23 | `run/start`:`process.outputEncoding` 可选声明 | 0 | 2026-11-20 | [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128) | | API-29 | `lithe/build/prepareRun`:返回值 `outputEncoding` 可选声明(提供者方法) | `litheBuild` 0、1 | 2026-11-20 | [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128) | +| API-40 | `workspace/getHostPaths` | 0 | 待合入 | [#151](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/151) | ## 时间线(新的在上) @@ -158,6 +157,9 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#141](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/141) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-25、API-29、API-31 | **`languageServers` 1** | 语言服务器新增可选 `executesProjectCode`(不写按 `true`),启动请求新增 `projectCodeAllowed`(不写按未信任,[1lck/Lithe-IDEA#2208](https://github.com/1lck/Lithe-IDEA/issues/2208))。未信任的工作区里,`plugins.declarative.languageServerLaunchPlan` 和 `plugins.languageServers.decodeLaunch` 只给声明 `executesProjectCode: false` 的语言服务器计划;自带进程的构建提供者按 `buildSystems[].provider.executesProjectCode` 判断,共用语言服务器的跟随该服务器;VCS 提供者一律不给计划。拒绝码是新的 `plugin.launch.untrustedWorkspace`。插件后端和独立调试适配器不受影响。用 `executesProjectCode` 要声明 `requires.languageServers: 1`。没有新增宿主方法、通知或 SDK 版本。 | +| [#139](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/139) | [@1lck](https://github.com/1lck) | API-29 | **`buildSystems` 2** | 构建提供者的 `application` 运行声明(含 `entrypoints: true`)可以通过 `debug.configurationType` 复用已注册的连接调试器。`lithe/build/prepareRun` 复用原有 `launchOptions.debug`,入口运行仍不带 `target`。已有服务运行声明继续适用旧版本。没有新增 RPC 方法、通知或 SDK 版本。 | +| [#135](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/135) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23 | `toolDefinitions` 0 内的行为修正 | 外部安装的 `executableLayouts` 文件链接到另一个文件名时,`toolchains.candidates` 的待探针路径和 `toolchains.resolve` 的 `executable` 改为规范主目录下的布局路径,不再是链接目标。rustup 把 `cargo`、`rust-analyzer` 链接到自身、按启动时的名字决定运行哪个工具,以前 Core 返回 `rustup`,版本探针失败。链接目标的类型、可执行位和越界检查不变;同名链接仍返回规范路径。没有新增字段、版本号、宿主方法、通知或 SDK 版本。 | | [#133](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/133) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23 | **`commandInstallers` 1** | 命令安装新增[下载安装](../contract/v1/README.md#download-installers):安装声明 `download`(与 `tool`、`minimumVersion`、`arguments` 互斥),固定上游 `version` 和 1–6 个平台归档,每个归档有 `os`、`arch`、HTTPS `url`、可选 `mirrors`(最多 8 个)、完整 `sha256`、`archive`(`zip`/`tar.gz`)和可选 `stripPrefix`,规则与 `managedRuntimes` 归档相同;只能用 `managed` 目标,不带 `arguments`、`environment`,`commandDirectory` 相对解压根目录,`mayUseNetwork` 必须为 `true`。`plugins.commandInstallers.requirements` 和 `plan` 新增可选 `platform: {os, arch}`:带上时没有该平台归档的下载安装不提供;安装条目新增 `download: null | {version}`;计划新增 `download`(工具安装为 `null`,下载安装为选中平台的归档、`cacheKey` 和 `commandDirectory`)。新增 Core 错误码 `plugin.commandInstaller.platformInvalid`、`unavailable`,宿主错误码 `plugin.commandInstaller.downloadFailed`、`checksumMismatch`、`archiveInvalid`;`failed` 只指工具安装失败。下载安装的审查程序列出全部归档,改地址、镜像、摘要或版本需要重新批准;只声明 `commandInstallers` 0 的宿主拒绝安装带下载安装的插件。没有新增宿主方法、通知或 SDK 版本。用于 Rust Support 插件按需下载 CodeLLDB。 | | [#130](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/130) | [@1lck](https://github.com/1lck) | — | **市场推荐索引 `schemaVersion` 0** | 市场契约新增同级推荐索引格式 `plugin-recommendations.schema.json`(`schemaVersion: 0`,独立于只增不破旧版的 `lithe-plugin-index.json`);`plugins.marketplace.resolveSource` 额外返回 `recommendationsURL`,并新增宿主内部 Core 命令 `plugins.marketplace.recommendForWorkspace`(不是插件 RPC),基于工作区采集文件名与已有市场索引匹配可安装的缺失插件。见 [1lck/Lithe-IDEA#2228](https://github.com/1lck/Lithe-IDEA/issues/2228)。 | | [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23、API-29 | `pluginAPIVersion` 0 内的补充 | `run/start` 的 `process` 和提供者 `lithe/build/prepareRun` 的返回值新增可选 `outputEncoding`,用稳定编码 ID 或别名声明进程写入管道的编码;Core 校验并规范化,拒绝未知或不兼容 ASCII 的编码。用户固定编码优先;自动模式逐行尝试声明、UTF-8,以及仅 Windows 的 GBK。省略字段时所有平台默认 UTF-8,Windows 兼容 GBK;不修改进程环境或终端代码页。新增宿主内部 Core 命令 `outputEncoding.resolve`,返回同一解析规则的候选与可选编码列表,不是插件 RPC。见 [1lck/Lithe-IDEA#2186](https://github.com/1lck/Lithe-IDEA/issues/2186)。 | diff --git a/shared/plugins/sdk/e2e/plugin_sdk/backend.rs b/shared/plugins/sdk/e2e/plugin_sdk/backend.rs index 40bc6c9d..3787b6d8 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/backend.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/backend.rs @@ -47,6 +47,7 @@ pub fn run_backend_scenario(package: &Path) { "lithe/host/window/showError", "lithe/host/window/showInformation", "lithe/host/window/showWarning", + "lithe/host/workspace/getHostPaths", "lithe/host/workspace/watch", "workspace" ]) diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index b2134b91..8656c7fb 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -271,6 +271,7 @@ must(backend.OnCommand("db.refresh", func(_ string, workspace *lithe.WorkspaceCo | `Credentials().Get(key)`, `.Set(key, secret)`, `.Delete(key)` | Secrets in the platform's store; see [Credentials](#credentials). | | `Capabilities()`, `Supports(method)` | What this session may call, from `lithe/host/getCapabilities` (asked once). | | `Workspace().ListContexts()`, `.GetContext(context)`, `.GetFolders(context)` | Workspace contexts; only `GetContext` returns, and creates, the context's `stateDirectory`. | +| `Workspace().GetHostPaths(context, rootIDs...)`, `.ProcessRoots(context)` | Root paths on the remote host of a remote context; see [Remote workspaces](#remote-workspaces). | | `Workspace().ReadDirectory`, `.Stat`, `.ReadFile`, `.FindFiles`, `.FindText`, `.Watch` | Files of a local context, addressed as `{ rootID, path }` from `GetFolders`. | | `Documents().List`, `.GetSnapshot`; `Editor().GetActive`, `.GetSelections`, `.ApplyEdits`, `.ReplaceSelections`, `.InsertText`, `.Open`, `.Reveal`, `.RegisterActions` | Live documents and editors. Edits name the `expectedVersion` they were computed against. | | `Preview().OpenHTML`, `Browser().OpenExternal`, `Window().ShowInformation`, `.ShowWarning`, `.ShowError` | Preview, browser, and messages. | @@ -346,6 +347,51 @@ package. `Get` returns `"", false, nil` when nothing is stored. | `sdk.call.cancelled` | The call was cancelled while waiting; returning it answers as cancelled. | | `sdk.session.notReady`, `sdk.session.closed` | The session has not finished `initialize`, or it ended while waiting. | +### Remote workspaces + +A backend runs on the machine that runs Lithe also when the workspace is on a +remote host. Such a context has `authority.kind` `remote` and +`authority.platform` `{ os, arch }`, and its folders carry no `path`. +`GetHostPaths` gives their paths on the host. It needs the +`workspace.metadata` permission, and only a host that serves it lists it, so +check `Supports("lithe/host/workspace/getHostPaths")` first. + +```go +full, err := host.Workspace().GetContext(*workspace) +if err != nil { + return nil, err +} +roots, err := host.Workspace().ProcessRoots(full) +if err != nil { + return nil, err +} +for _, root := range roots { + // A local root has Path; a remote one has HostPath. + cwd := root.Path + if cwd == "" { + cwd = root.HostPath.String() + } + // ... +} +``` + +- `lithe.HostPath` is its own type, so it is not passed to `os`, `filepath` + or `exec` by mistake: the machine that runs the backend has no file there. + Give `String()` only to what runs on the host, such as process arguments or + a debug configuration; it marshals to JSON as that string. +- `ProcessRoots` takes a full context. For a `local` one it reads the folders + without asking the host; otherwise it calls `GetHostPaths`. +- `GetHostPaths` without root IDs asks for every root; with them it takes + 1–256 distinct root IDs, and others fail locally with + `sdk.host.invalidParams`. An answer without absolute paths is + `sdk.host.invalidResult`. +- `plugin.host.remoteDisconnected` means the connection was lost while the + request ran, so whether it took effect is unknown; + `plugin.host.platformUnavailable` means the plugin has nothing for the + host's platform. The + [remote workspaces guide](../../guides/plugin-backend-remote-workspaces.md) + says which services serve a remote context. + ### Calling other plugins A backend may call a function another plugin exports; Core relays the call and @@ -456,7 +502,7 @@ must(backend.Function("project.describe", func(params json.RawMessage, call *lit | `plugin.function.callCycle`, `.depthExceeded`, `.tooManyCalls`, `.payloadTooLarge` | The chain, the caller's running calls, or a payload exceeded a limit. | | `plugin.function.providerUnavailable`, `.invalidResult` | The provider's backend stopped or did not start in time, or answered with no result or one over 1 MiB. | | `plugin.function.failed` | The provider's function returned an error. The `pluginErrorCode` entry of `Details()` is the provider's own `PluginError` code, and `Message()` is its message. | -| `plugin.host.contextExpired`, `plugin.host.authorityUnsupported`, `plugin.host.timeout`, `plugin.host.cancelled` | The context was closed or replaced, is not a local workspace, the deadline passed, or the call (or its parent) was cancelled. | +| `plugin.host.contextExpired`, `plugin.host.timeout`, `plugin.host.cancelled` | The context was closed or replaced, the deadline passed, or the call (or its parent) was cancelled. A remote workspace's context is relayed like a local one. | | `sdk.host.invalidResult` | The host answered with something other than an object. | ## Results and errors diff --git a/shared/plugins/sdk/go/lithe/errors.go b/shared/plugins/sdk/go/lithe/errors.go index 2e06b155..e437ad27 100644 --- a/shared/plugins/sdk/go/lithe/errors.go +++ b/shared/plugins/sdk/go/lithe/errors.go @@ -42,6 +42,8 @@ var HostErrorCodes = []ErrorCode{ {"plugin.host.methodNotDeclared", -32024}, {"plugin.host.toolUnresolved", -32025}, {"plugin.host.foreignContribution", -32026}, + {"plugin.host.remoteDisconnected", -32078}, + {"plugin.host.platformUnavailable", -32079}, } // RelayErrorCodes are the codes a cross-plugin call fails with. diff --git a/shared/plugins/sdk/go/lithe/errors_test.go b/shared/plugins/sdk/go/lithe/errors_test.go index bb25ba35..cf8df428 100644 --- a/shared/plugins/sdk/go/lithe/errors_test.go +++ b/shared/plugins/sdk/go/lithe/errors_test.go @@ -68,7 +68,7 @@ func TestHostFailuresKeepTheirCodeOrTakeItFromTheNumber(t *testing.T) { } func TestTheHostAndRelayTablesHoldEveryDocumentedCodeOnce(t *testing.T) { - if len(HostErrorCodes) != 21 || len(RelayErrorCodes) != 11 { + if len(HostErrorCodes) != 23 || len(RelayErrorCodes) != 11 { t.Fatalf("tables hold %d and %d codes", len(HostErrorCodes), len(RelayErrorCodes)) } codes := map[string]bool{} diff --git a/shared/plugins/sdk/go/lithe/host.go b/shared/plugins/sdk/go/lithe/host.go index 96ef1edf..7bffe747 100644 --- a/shared/plugins/sdk/go/lithe/host.go +++ b/shared/plugins/sdk/go/lithe/host.go @@ -878,6 +878,142 @@ func (w *Workspace) GetFolders(context WorkspaceContext) (json.RawMessage, error return w.host.scoped(methodGetFolders, context, nil) } +// HostPath is an absolute path on the remote host of a remote context, read +// with [Workspace.GetHostPaths]. It is not a path on this machine: give it +// only to a process that runs on that host, never to os, filepath or exec +// here. It is its own type so it is not passed as a local path by mistake. +type HostPath string + +// String is the path as text. +func (p HostPath) String() string { return string(p) } + +// HostFolder is a root of a remote context and its path on the remote host. +type HostFolder struct { + RootID string `json:"rootID"` + HostPath HostPath `json:"hostPath"` +} + +// GetHostPaths answers the path on the remote host of each root of a remote +// context, or of rootIDs only: 1-256 distinct root IDs from GetFolders. It +// needs the workspace.metadata permission, and only a host that serves it +// lists it, so check Supports("lithe/host/workspace/getHostPaths") first. A +// local context, or a host that cannot answer, fails with +// plugin.host.authorityUnsupported. +func (w *Workspace) GetHostPaths(context WorkspaceContext, rootIDs ...string) ([]HostFolder, error) { + params := map[string]any{"context": context.toValue()} + if len(rootIDs) > 0 { + if !distinctRootIDs(rootIDs) { + return nil, newSdkError("sdk.host.invalidParams", "rootIDs is 1-256 distinct root IDs of 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\".") + } + ids := make([]any, len(rootIDs)) + for i, id := range rootIDs { + ids[i] = id + } + params["rootIDs"] = ids + } + result, err := w.host.request(methodGetHostPaths, params) + if err != nil { + return nil, err + } + return hostFolders(result) +} + +// ProcessRoot is a root of a context as a process started for it names its +// working directory: Path for a local context, HostPath for a remote one. +// The other one is empty. +type ProcessRoot struct { + RootID string `json:"rootID"` + Path string `json:"path,omitempty"` + HostPath HostPath `json:"hostPath,omitempty"` +} + +// ProcessRoots answers the roots of a full context from ListContexts or +// GetContext -- a json.RawMessage, a map, or any value that serializes to +// one. A local context's folders are read without asking the host; for any +// other authority it calls GetHostPaths. +func (w *Workspace) ProcessRoots(context any) ([]ProcessRoot, error) { + value, err := toValue(context) + kind, ok := pointer(value, "authority", "kind").(string) + if err != nil || !ok { + return nil, newSdkError("sdk.host.invalidContext", "ProcessRoots takes a full context, with its authority and folders, from ListContexts or GetContext.") + } + if kind == "local" { + return localFolders(field(value, "folders")) + } + reference, err := workspaceContextFromValue(value) + if err != nil { + return nil, err + } + folders, err := w.GetHostPaths(reference) + if err != nil { + return nil, err + } + roots := make([]ProcessRoot, len(folders)) + for i, folder := range folders { + roots[i] = ProcessRoot{RootID: folder.RootID, HostPath: folder.HostPath} + } + return roots, nil +} + +func distinctRootIDs(rootIDs []string) bool { + if len(rootIDs) > maxHostPathRoots { + return false + } + seen := make(map[string]bool, len(rootIDs)) + for _, id := range rootIDs { + if !IsCredentialKey(id) || seen[id] { + return false + } + seen[id] = true + } + return true +} + +// hostFolders reads { folders: [{ rootID, hostPath }] } of a GetHostPaths +// answer. +func hostFolders(result any) ([]HostFolder, error) { + items, ok := field(result, "folders").([]any) + if !ok { + return nil, invalidHostPaths() + } + folders := make([]HostFolder, len(items)) + for i, item := range items { + rootID, _ := field(item, "rootID").(string) + path, _ := field(item, "hostPath").(string) + if !IsCredentialKey(rootID) || !strings.HasPrefix(path, "/") { + return nil, invalidHostPaths() + } + folders[i] = HostFolder{RootID: rootID, HostPath: HostPath(path)} + } + return folders, nil +} + +func invalidHostPaths() *SdkError { + return newSdkError("sdk.host.invalidResult", "The host answered getHostPaths without folders of a root ID and an absolute host path.") +} + +// localFolders reads [{ rootID, path }] of a local context's folders. +func localFolders(value any) ([]ProcessRoot, error) { + items, ok := value.([]any) + if !ok { + return nil, invalidLocalFolders() + } + roots := make([]ProcessRoot, len(items)) + for i, item := range items { + rootID, _ := field(item, "rootID").(string) + path, ok := field(item, "path").(string) + if !IsCredentialKey(rootID) || !ok { + return nil, invalidLocalFolders() + } + roots[i] = ProcessRoot{RootID: rootID, Path: path} + } + return roots, nil +} + +func invalidLocalFolders() *SdkError { + return newSdkError("sdk.host.invalidContext", "A local context's folders each carry a rootID and a path.") +} + // ReadDirectory takes resource, cursor?, limit?. func (w *Workspace) ReadDirectory(context WorkspaceContext, params any) (json.RawMessage, error) { return w.host.scoped(methodReadDirectory, context, params) diff --git a/shared/plugins/sdk/go/lithe/host_services_test.go b/shared/plugins/sdk/go/lithe/host_services_test.go index f93e9aa9..d11535aa 100644 --- a/shared/plugins/sdk/go/lithe/host_services_test.go +++ b/shared/plugins/sdk/go/lithe/host_services_test.go @@ -803,6 +803,114 @@ func TestNativeTerminalMethodsKeepContextAndLiteralArguments(t *testing.T) { s.close() } +func TestHostPathRootIDsCoreRefusesFailLocallyAndTheAnswerHoldsHostPaths(t *testing.T) { + backend := lithe.NewBackend("test-backend") + workspace := backend.Handle().Host().Workspace() + s := startSession(t, backend, []any{0}) + checked := 0 + for _, c := range cases(t, fixture(t), "hostRequests") { + params, _ := c["params"].(map[string]any) + if c["method"] != "lithe/host/workspace/getHostPaths" || params["context"] == nil || params["path"] != nil { + continue + } + name, _ := c["name"].(string) + context, err := lithe.ParseWorkspaceContext(params["context"]) + must(t, err) + var rootIDs []string + list, _ := params["rootIDs"].([]any) + for _, id := range list { + rootIDs = append(rootIDs, id.(string)) + } + expected, _ := c["expected"].(map[string]any) + switch { + case expected["forward"] != nil: + asking := background(func() ([]lithe.HostFolder, error) { return workspace.GetHostPaths(context, rootIDs...) }) + request := s.take("lithe/host/workspace/getHostPaths") + eq(t, request["params"], encode(t, params)) + roots := rootIDs + if len(roots) == 0 { + roots = []string{"r0c1d2e3f4a5b6c7d"} + } + folders := make([]any, len(roots)) + for i, id := range roots { + folders[i] = map[string]any{"rootID": id, "hostPath": fmt.Sprintf("/srv/root%d", i)} + } + s.reply(request, map[string]any{"folders": folders}) + result := done(t, asking) + must(t, result.err) + if len(result.value) != len(roots) || result.value[0].RootID != roots[0] || result.value[0].HostPath != "/srv/root0" { + t.Errorf("%s: %v", name, result.value) + } + checked++ + case expected["code"] == "plugin.host.invalidParams" && len(rootIDs) > 0: + // An empty list cannot be written: no root IDs asks for every root. + if _, err := workspace.GetHostPaths(context, rootIDs...); code(err) != "sdk.host.invalidParams" { + t.Errorf("%s: %v", name, err) + } + checked++ + } + } + if checked != 4 { + t.Errorf("checked %d cases, want 4", checked) + } + tooMany := make([]string, 257) + for i := range tooMany { + tooMany[i] = fmt.Sprintf("r%d", i) + } + if _, err := workspace.GetHostPaths(testContext(), tooMany...); code(err) != "sdk.host.invalidParams" { + t.Errorf("257 root IDs: %v", err) + } + s.assertQuiet() + + // An answer that is not root IDs with absolute paths is refused. + for _, answer := range []string{`{}`, `{"folders": [{"rootID": "r0", "hostPath": "srv/root0"}]}`, `{"folders": [{"hostPath": "/srv/root0"}]}`} { + asking := background(func() ([]lithe.HostFolder, error) { return workspace.GetHostPaths(testContext()) }) + s.reply(s.take("lithe/host/workspace/getHostPaths"), j(t, answer)) + if err := done(t, asking).err; code(err) != "sdk.host.invalidResult" { + t.Errorf("%s: %v", answer, err) + } + } + s.close() +} + +func TestProcessRootsReadsALocalContextAndAsksTheHostOnlyForARemoteOne(t *testing.T) { + backend := lithe.NewBackend("test-backend") + workspace := backend.Handle().Host().Workspace() + s := startSession(t, backend, []any{0}) + local, err := workspace.ProcessRoots(json.RawMessage(`{ + "contextID": "w1", "generation": 2, "name": "orders", "authority": {"kind": "local"}, + "folders": [{"rootID": "r0", "name": "orders", "path": "/Users/me/orders"}] + }`)) + must(t, err) + eq(t, local, `[{"rootID": "r0", "path": "/Users/me/orders"}]`) + s.assertQuiet() + + remote := j(t, `{ + "contextID": "w1", "generation": 2, "name": "orders", + "authority": {"kind": "remote", "id": "c-7d41", "platform": {"os": "linux", "arch": "x86_64"}}, + "folders": [{"rootID": "r0", "name": "orders"}] + }`) + asking := background(func() ([]lithe.ProcessRoot, error) { return workspace.ProcessRoots(remote) }) + request := s.take("lithe/host/workspace/getHostPaths") + eq(t, request["params"], `{"context": {"contextID": "w1", "generation": 2}}`) + s.reply(request, j(t, `{"folders": [{"rootID": "r0", "hostPath": "/home/me/orders"}]}`)) + result := done(t, asking) + must(t, result.err) + eq(t, result.value, `[{"rootID": "r0", "hostPath": "/home/me/orders"}]`) + if result.value[0].Path != "" || result.value[0].HostPath.String() != "/home/me/orders" { + t.Errorf("a remote root: %+v", result.value[0]) + } + + // A reference alone does not say the authority, and a local folder names its path. + for _, context := range []any{testContext(), j(t, `{"contextID": "w1", "generation": 2, "authority": {"kind": "local"}, "folders": [{"rootID": "r0"}]}`)} { + if _, err := workspace.ProcessRoots(context); code(err) != "sdk.host.invalidContext" { + t.Errorf("%s: %v", encode(t, context), err) + } + } + s.assertQuiet() + s.close() +} + func TestARelayedCallNamesThePluginThatCalledItAndAHostCallNamesNone(t *testing.T) { checked := 0 for _, c := range cases(t, fixture(t), "invocationCallers") { @@ -978,8 +1086,8 @@ func TestRelayRefusalsKeepTheCodeNumberAndTheProvidersOwnCode(t *testing.T) { return refusal(t, pending) } relayErrors := cases(t, fixture(t), "relayErrors") - if len(relayErrors) != 15 { - t.Errorf("%d relay errors, want 15", len(relayErrors)) + if len(relayErrors) != 14 { + t.Errorf("%d relay errors, want 14", len(relayErrors)) } for _, c := range relayErrors { expected := c["code"].(string) diff --git a/shared/plugins/sdk/go/lithe/protocol.go b/shared/plugins/sdk/go/lithe/protocol.go index c2b7938f..785a2da3 100644 --- a/shared/plugins/sdk/go/lithe/protocol.go +++ b/shared/plugins/sdk/go/lithe/protocol.go @@ -39,6 +39,7 @@ const ( methodListContexts = "lithe/host/workspace/listContexts" methodGetContext = "lithe/host/workspace/getContext" methodGetFolders = "lithe/host/workspace/getFolders" + methodGetHostPaths = "lithe/host/workspace/getHostPaths" methodReadDirectory = "lithe/host/workspace/readDirectory" methodStat = "lithe/host/workspace/stat" methodReadFile = "lithe/host/workspace/readFile" @@ -99,6 +100,7 @@ const ( maxEarlyEvents = 128 maxCommandIDBytes = 128 maxParentOperation = 128 + maxHostPathRoots = 256 maxSafeInteger = 1<<53 - 1 ) diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 119c00d5..6dcdbb05 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -260,6 +260,7 @@ backend.onCommand("db.refresh", (commandId, workspaceContext) -> { | `capabilities()`, `supports(method)` | What this session may call, from `lithe/host/getCapabilities` (asked once). `supports` is false when the host offered no plugin functions. | | `workspace().listContexts()`, `.getContext(context)`, `.getFolders(context)` | Workspace contexts; only `getContext` returns, and creates, the context's `stateDirectory`. | | `workspace().readDirectory`, `.stat`, `.readFile`, `.findFiles`, `.findText`, `.watch` | Files of a local context, addressed as `{ rootID, path }` from `getFolders`. | +| `workspace().getHostPaths(context, rootIds)`, `.processRoots(fullContext)` | Root paths on the remote host of a remote context; see [Remote workspaces](#remote-workspaces). | | `documents().list`, `.getSnapshot`; `editor().getActive`, `.getSelections`, `.applyEdits`, `.replaceSelections`, `.insertText`, `.open`, `.reveal`, `.registerActions` | Live documents and editors. Edits name the `expectedVersion` they were computed against. | | `preview().openHtml`, `browser().openExternal`, `window().showInformation`, `.showWarning`, `.showError` | Preview, browser, and messages. | | `functions().providers(functionId)`, `.invoke(context, call)` | [Calls to other plugins' functions](#calling-other-plugins), relayed by Core. | @@ -304,6 +305,45 @@ What the SDK does for you, and what it leaves to you: plugin's commands; the host waits for no result. A stopped backend is started for it only when the manifest declares `onCommand:`. +## Remote workspaces + +A backend runs on the machine that runs Lithe also when the workspace is on a +remote host. Such a context has `authority.kind` `remote` and +`authority.platform` `{ os, arch }`, and its folders carry no `path`. +`getHostPaths` gives their paths on the host. It needs the +`workspace.metadata` permission, and only a host that serves it lists it, so +check `supports("lithe/host/workspace/getHostPaths")` first. + +```java +Map full = context.host().workspace().getContext(workspace).get(); +for (Host.ProcessRoot root : context.host().workspace().processRoots(full).get()) { + if (root.isRemote()) { + Host.HostPath hostPath = root.hostPath(); // a path on the remote host + } else { + String path = root.path(); // a path on this machine + } +} +``` + +- `Host.HostPath` is its own type, not a `String`, so it is not passed to + `java.io.File`, `java.nio.file.Paths` or `ProcessBuilder` by mistake: the + machine that runs the backend has no file there. Give `value()` only to + what runs on the host, such as process arguments or a debug configuration; + the SDK writes it into JSON as that string. `HostPath.of` takes only an + absolute POSIX path. +- `processRoots` takes a full context. For a `local` one it reads the + folders without asking the host; otherwise it calls `getHostPaths`. +- `getHostPaths(context)` asks for every root; `getHostPaths(context, + rootIds)` takes 1–256 distinct root IDs, and others fail locally with + `sdk.host.invalidParams`. An answer without absolute paths is + `sdk.host.invalidResult`. +- `plugin.host.remoteDisconnected` means the connection was lost while the + request ran, so whether it took effect is unknown; + `plugin.host.platformUnavailable` means the plugin has nothing for the + host's platform. The + [remote workspaces guide](../../guides/plugin-backend-remote-workspaces.md) + says which services serve a remote context. + ## Calling other plugins A backend may call a function that another plugin exports. The plugin must @@ -367,8 +407,8 @@ What the SDK does for you, and what it leaves to you: `.payloadTooLarge`, `.providerUnavailable`, `.failed` and `.invalidResult`. `plugin.function.failed` carries the provider's own code in `pluginErrorCode()`. A call to a context the host closed fails with - `plugin.host.contextExpired`; a remote workspace with - `plugin.host.authorityUnsupported`; a deadline with `plugin.host.timeout`. + `plugin.host.contextExpired`, and a deadline with `plugin.host.timeout`; a + remote workspace's context is relayed like a local one. Core never retries a call, and neither does the SDK. - **Calls end with their caller.** Ending or cancelling the function call that made a relayed call, or cancelling the token given to `withCancellation`, diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java index fb0e9887..3c582a1c 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java @@ -3,9 +3,11 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.BooleanSupplier; @@ -95,6 +97,110 @@ public CompletableFuture dispose() { } } + /** + * A path on the remote host of a {@code remote} workspace context, from + * {@link Workspace#getHostPaths}. It is not a {@code String} or a + * {@code java.nio.file.Path}, so it cannot reach {@code Files} or + * {@code ProcessBuilder.directory} by mistake: the machine that runs the + * backend has no file there. {@link #value()} is the absolute POSIX path, + * for what runs on that host -- process arguments and working + * directories, a debug configuration's {@code program} or {@code cwd}, a + * language server's {@code initializationOptions}. In request params it is + * written as that string. + */ + public static final class HostPath { + private final String value; + + private HostPath(String value) { + this.value = value; + } + + /** + * @throws IllegalArgumentException unless {@code value} is an absolute + * POSIX path, a string starting with {@code /} + */ + public static HostPath of(String value) { + if (!isHostPath(value)) { + throw new IllegalArgumentException("A host path is an absolute POSIX path, a string starting with \"/\"."); + } + return new HostPath(value); + } + + public String value() { + return value; + } + + @Override + public String toString() { + return value; + } + + @Override + public boolean equals(Object other) { + return other instanceof HostPath && value.equals(((HostPath) other).value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + } + + /** One root of a {@link Workspace#getHostPaths} answer. */ + public static final class HostFolder { + private final String rootId; + private final HostPath hostPath; + + HostFolder(String rootId, HostPath hostPath) { + this.rootId = rootId; + this.hostPath = hostPath; + } + + public String rootId() { + return rootId; + } + + public HostPath hostPath() { + return hostPath; + } + } + + /** + * A root of a context as a process started for it names its working + * directory, from {@link Workspace#processRoots}: {@link #path()} for a + * {@code local} context, {@link #hostPath()} for a {@code remote} one. The + * other one is null. + */ + public static final class ProcessRoot { + private final String rootId; + private final String path; + private final HostPath hostPath; + + ProcessRoot(String rootId, String path, HostPath hostPath) { + this.rootId = rootId; + this.path = path; + this.hostPath = hostPath; + } + + public String rootId() { + return rootId; + } + + /** The root on the machine that runs the backend, or null for a remote root. */ + public String path() { + return path; + } + + /** The root on the remote host, or null for a local root. */ + public HostPath hostPath() { + return hostPath; + } + + public boolean isRemote() { + return hostPath != null; + } + } + private final HostChannel channel; private final List scope; /** The wire operation ID of the function call this Host belongs to, or null; the default parent of {@link Functions#invoke}. */ @@ -299,6 +405,65 @@ public CompletableFuture> getFolders(Map context) return scoped(Protocol.HOST_WORKSPACE_GET_FOLDERS, context, null); } + /** Every root of a {@code remote} context on its remote host; see {@link #getHostPaths(Map, List)}. */ + public CompletableFuture> getHostPaths(Map context) { + return getHostPaths(context, null); + } + + /** + * The roots of a {@code remote} context on its remote host: + * {@code rootIds} null for every root, or 1-256 distinct root IDs. + * It needs the {@code workspace.metadata} permission; a local context + * fails with {@code plugin.host.authorityUnsupported}, an unknown root + * ID with {@code plugin.host.notFound}. + */ + public CompletableFuture> getHostPaths(Map context, List rootIds) { + Map params = new LinkedHashMap<>(); + if (rootIds != null) { + if (!distinctRootIds(rootIds)) { + return failed(new PluginSdkError("sdk.host.invalidParams", + "rootIDs is 1-256 distinct root IDs of 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\".")); + } + params.put("rootIDs", new ArrayList<>(rootIds)); + } + Map message; + try { + message = withContext(context, params); + } catch (PluginSdkError error) { + return failed(error); + } + return channel.request(Protocol.HOST_WORKSPACE_GET_HOST_PATHS, message, scope).thenApply(Host::hostFolders); + } + + /** + * The roots of a full context from {@link #listContexts} or + * {@link #getContext} as a process started for it names its working + * directory. A {@code local} context's folders are read without asking + * the host; for any other authority it calls {@link #getHostPaths(Map)}. + */ + public CompletableFuture> processRoots(Map context) { + Object authority = context == null ? null : context.get("authority"); + Object kind = authority instanceof Map ? ((Map) authority).get("kind") : null; + if (!(kind instanceof String)) { + return failed(new PluginSdkError("sdk.host.invalidContext", + "processRoots takes a full context, with its authority and folders, from listContexts or getContext.")); + } + if ("local".equals(kind)) { + try { + return CompletableFuture.completedFuture(localFolders(context.get("folders"))); + } catch (PluginSdkError error) { + return failed(error); + } + } + return getHostPaths(context).thenApply(folders -> { + List roots = new ArrayList<>(folders.size()); + for (HostFolder folder : folders) { + roots.add(new ProcessRoot(folder.rootId(), null, folder.hostPath())); + } + return Collections.unmodifiableList(roots); + }); + } + /** {@code params}: {@code resource, cursor?, limit?}. */ public CompletableFuture> readDirectory(Map context, Map params) { return scoped(Protocol.HOST_WORKSPACE_READ_DIRECTORY, context, params); @@ -618,6 +783,67 @@ private static CompletableFuture> object(String method, Comp }); } + private static boolean isHostPath(Object value) { + return value instanceof String && ((String) value).startsWith("/"); + } + + private static boolean distinctRootIds(List rootIds) { + if (rootIds.isEmpty() || rootIds.size() > Protocol.MAX_HOST_PATH_ROOTS) { + return false; + } + Set seen = new HashSet<>(); + for (String id : rootIds) { + if (!Protocol.isCredentialKey(id) || !seen.add(id)) { + return false; + } + } + return true; + } + + /** {@code [{ rootID, hostPath }]} of a {@code getHostPaths} answer's {@code folders}. */ + private static List hostFolders(Object result) { + Object folders = result instanceof Map ? ((Map) result).get("folders") : null; + if (!(folders instanceof List)) { + throw invalidHostPaths(); + } + List answer = new ArrayList<>(); + for (Object folder : (List) folders) { + Object rootId = folder instanceof Map ? ((Map) folder).get("rootID") : null; + Object hostPath = folder instanceof Map ? ((Map) folder).get("hostPath") : null; + if (!(rootId instanceof String) || !Protocol.isCredentialKey((String) rootId) || !isHostPath(hostPath)) { + throw invalidHostPaths(); + } + answer.add(new HostFolder((String) rootId, new HostPath((String) hostPath))); + } + return Collections.unmodifiableList(answer); + } + + private static PluginSdkError invalidHostPaths() { + return new PluginSdkError("sdk.host.invalidResult", + "The host answered getHostPaths without folders of a root ID and an absolute host path."); + } + + /** {@code [{ rootID, path }]} of a {@code local} context's folders. */ + private static List localFolders(Object folders) { + if (!(folders instanceof List)) { + throw invalidLocalFolders(); + } + List roots = new ArrayList<>(); + for (Object folder : (List) folders) { + Object rootId = folder instanceof Map ? ((Map) folder).get("rootID") : null; + Object path = folder instanceof Map ? ((Map) folder).get("path") : null; + if (!(rootId instanceof String) || !Protocol.isCredentialKey((String) rootId) || !(path instanceof String)) { + throw invalidLocalFolders(); + } + roots.add(new ProcessRoot((String) rootId, (String) path, null)); + } + return Collections.unmodifiableList(roots); + } + + private static PluginSdkError invalidLocalFolders() { + return new PluginSdkError("sdk.host.invalidContext", "A local context's folders each carry a rootID and a path."); + } + private static Map params(String key, Object value) { Map params = new LinkedHashMap<>(); params.put(key, value); diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java index 3730a020..327a6c5c 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java @@ -18,7 +18,7 @@ public final class HostError extends PluginSdkError { /** * Stable host failure codes and their JSON-RPC numbers, including the * {@code plugin.function.*} codes of cross-plugin calls. A later host adds - * codes after the highest number here. + * codes at numbers no code here uses yet. */ public static final Map CODES; private static final Map BY_RPC_CODE; @@ -57,6 +57,8 @@ public final class HostError extends PluginSdkError { codes.put("plugin.function.providerUnavailable", -32069); codes.put("plugin.function.failed", -32070); codes.put("plugin.function.invalidResult", -32071); + codes.put("plugin.host.remoteDisconnected", -32078); + codes.put("plugin.host.platformUnavailable", -32079); CODES = Collections.unmodifiableMap(codes); Map byNumber = new HashMap<>(); for (Map.Entry entry : codes.entrySet()) { diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Json.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Json.java index 64ff3f59..cde909b0 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Json.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Json.java @@ -79,7 +79,7 @@ private static void write(StringBuilder output, Object value, int depth) { } if (value == null) { output.append("null"); - } else if (value instanceof String || value instanceof Character) { + } else if (value instanceof String || value instanceof Character || value instanceof Host.HostPath) { quote(output, value.toString()); } else if (value instanceof Boolean) { output.append(value.toString()); diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java index 66f57caa..53ac7dc4 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java @@ -62,6 +62,7 @@ public final class Protocol { public static final String HOST_WORKSPACE_LIST_CONTEXTS = "lithe/host/workspace/listContexts"; public static final String HOST_WORKSPACE_GET_CONTEXT = "lithe/host/workspace/getContext"; public static final String HOST_WORKSPACE_GET_FOLDERS = "lithe/host/workspace/getFolders"; + public static final String HOST_WORKSPACE_GET_HOST_PATHS = "lithe/host/workspace/getHostPaths"; public static final String HOST_WORKSPACE_READ_DIRECTORY = "lithe/host/workspace/readDirectory"; public static final String HOST_WORKSPACE_STAT = "lithe/host/workspace/stat"; public static final String HOST_WORKSPACE_READ_FILE = "lithe/host/workspace/readFile"; @@ -114,6 +115,8 @@ public final class Protocol { /** Unanswered host requests Core allows a session; the SDK queues the rest. */ public static final int MAX_PENDING_HOST_REQUESTS = 16; public static final int MAX_CREDENTIAL_SECRET_BYTES = 16 * 1024; + /** The most root IDs one {@code getHostPaths} request names. */ + public static final int MAX_HOST_PATH_ROOTS = 256; /** Timeout Core gives a relayed call that names none. */ public static final int RELAY_DEFAULT_TIMEOUT_MILLISECONDS = 60000; /** Longest timeout of a relayed call; the SDK sends a longer one unchanged and leaves the cap to Core. */ diff --git a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/HostTest.java b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/HostTest.java index 8b51dd00..6ef915a5 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/HostTest.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/HostTest.java @@ -548,6 +548,115 @@ void commandsContextChangesAndLaterHostNotificationsReachTheirHandlers() { host.close(); } + @Test + void hostPathRootIdsCoreRefusesFailLocallyAndTheAnswerHoldsHostPaths() { + Backend backend = Backend.create(null, null); + TestHost host = session(backend); + Host.Workspace workspace = backend.host().workspace(); + Set taken = new HashSet<>(); + int checked = 0; + for (Map testCase : cases("hostRequests")) { + if (!Protocol.HOST_WORKSPACE_GET_HOST_PATHS.equals(testCase.get("method"))) { + continue; + } + Map params = object(testCase.get("params")); + if (params.get("context") == null || params.get("path") != null) { + continue; + } + String name = (String) testCase.get("name"); + Map context = object(params.get("context")); + List rootIds = null; + if (params.get("rootIDs") != null) { + rootIds = new ArrayList<>(); + for (Object id : (List) params.get("rootIDs")) { + rootIds.add((String) id); + } + } + Map expected = object(testCase.get("expected")); + if (expected.get("forward") != null) { + CompletableFuture> asking = workspace.getHostPaths(context, rootIds); + Map request = nextRequest(host, Protocol.HOST_WORKSPACE_GET_HOST_PATHS, taken); + assertEquals(params, request.get("params"), name); + List roots = rootIds == null ? Arrays.asList("r0c1d2e3f4a5b6c7d") : rootIds; + List folders = new ArrayList<>(); + for (int index = 0; index < roots.size(); index++) { + folders.add(map("rootID", roots.get(index), "hostPath", "/srv/root" + index)); + } + host.send(map("id", request.get("id"), "result", map("folders", folders))); + List answer = value(asking); + assertEquals(roots.size(), answer.size(), name); + assertEquals(roots.get(0), answer.get(0).rootId(), name); + assertEquals(Host.HostPath.of("/srv/root0"), answer.get(0).hostPath(), name); + checked++; + } else if ("plugin.host.invalidParams".equals(expected.get("code"))) { + assertEquals("sdk.host.invalidParams", code(workspace.getHostPaths(context, rootIds)), name); + checked++; + } + } + assertEquals(5, checked); + int before = host.messages().size(); + List tooMany = new ArrayList<>(); + for (int index = 0; index < 257; index++) { + tooMany.add("r" + index); + } + assertEquals("sdk.host.invalidParams", code(workspace.getHostPaths(CONTEXT, tooMany))); + assertEquals(before, host.messages().size()); + + // An answer that is not root IDs with absolute paths is refused. + for (Object answer : Arrays.asList(map(), + map("folders", Arrays.asList(map("rootID", "r0", "hostPath", "srv/root0"))), + map("folders", Arrays.asList(map("hostPath", "/srv/root0"))))) { + CompletableFuture> asking = workspace.getHostPaths(CONTEXT); + Map request = nextRequest(host, Protocol.HOST_WORKSPACE_GET_HOST_PATHS, taken); + host.send(map("id", request.get("id"), "result", answer)); + assertEquals("sdk.host.invalidResult", code(asking), String.valueOf(answer)); + } + host.close(); + } + + @Test + void processRootsReadsALocalContextAndAsksTheHostOnlyForARemoteOne() { + Backend backend = Backend.create(null, null); + TestHost host = session(backend); + Host.Workspace workspace = backend.host().workspace(); + int before = host.messages().size(); + List local = value(workspace.processRoots(map("contextID", "w1", "generation", 2L, + "name", "orders", "authority", map("kind", "local"), + "folders", Arrays.asList(map("rootID", "r0", "name", "orders", "path", "/Users/me/orders"))))); + assertEquals(1, local.size()); + assertEquals("r0", local.get(0).rootId()); + assertEquals("/Users/me/orders", local.get(0).path()); + assertFalse(local.get(0).isRemote()); + assertNull(local.get(0).hostPath()); + assertEquals(before, host.messages().size()); + + CompletableFuture> asking = workspace.processRoots(map("contextID", "w1", "generation", 2L, + "name", "orders", + "authority", map("kind", "remote", "id", "c-7d41", "platform", map("os", "linux", "arch", "x86_64")), + "folders", Arrays.asList(map("rootID", "r0", "name", "orders")))); + Map request = nextRequest(host, Protocol.HOST_WORKSPACE_GET_HOST_PATHS); + assertEquals(map("context", CONTEXT), request.get("params")); + host.send(map("id", request.get("id"), "result", + map("folders", Arrays.asList(map("rootID", "r0", "hostPath", "/home/me/orders"))))); + List remote = value(asking); + assertEquals(1, remote.size()); + assertTrue(remote.get(0).isRemote()); + assertNull(remote.get(0).path()); + Host.HostPath hostPath = remote.get(0).hostPath(); + assertEquals("/home/me/orders", hostPath.value()); + // It is written as the path, for what runs on the remote host. + assertEquals("{\"cwd\":\"/home/me/orders\"}", Json.stringify(map("cwd", hostPath))); + assertThrows(IllegalArgumentException.class, () -> Host.HostPath.of("home/me/orders")); + + // A reference alone does not say the authority, and a local folder names its path. + before = host.messages().size(); + assertEquals("sdk.host.invalidContext", code(workspace.processRoots(CONTEXT))); + assertEquals("sdk.host.invalidContext", code(workspace.processRoots(map("contextID", "w1", "generation", 2L, + "authority", map("kind", "local"), "folders", Arrays.asList(map("rootID", "r0")))))); + assertEquals(before, host.messages().size()); + host.close(); + } + /** {@code base} as a new map, with {@code overrides} (alternating keys and values) replacing or adding entries. */ private static Map with(Map base, Object... overrides) { Map copy = map(); diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 14886c06..180e9d97 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -287,6 +287,7 @@ backend.onCommand('db.refresh', async ({ workspaceContext }) => { | `credentials.get(key)`, `.set(key, secret)`, `.delete(key)` | Secrets in the platform's store. `get` returns `null` when nothing is stored. A key is 1–128 of `[A-Za-z0-9._:-]`, a secret at most 16 KiB; others fail locally. | | `capabilities()`, `supports(method)` | What this session may call, from `lithe/host/getCapabilities` (asked once). | | `workspace.listContexts()`, `.getContext(context)`, `.getFolders(context)` | Workspace contexts; only `getContext` returns, and creates, the context's `stateDirectory`. | +| `workspace.getHostPaths(context, { rootIDs? })`, `.processRoots(context)` | The root folders of a remote context on the remote host, as `HostPath` values; `processRoots` gives the path a process uses for either authority. See [Remote workspaces](#remote-workspaces). | | `workspace.readDirectory`, `.stat`, `.readFile`, `.findFiles`, `.findText`, `.watch` | Files of a local context, addressed as `{ rootID, path }` from `getFolders`. | | `documents.list`, `.getSnapshot`; `editor.getActive`, `.getSelections`, `.applyEdits`, `.replaceSelections`, `.insertText`, `.open`, `.reveal`, `.registerActions` | Live documents and editors. Edits name the `expectedVersion` they were computed against. | | `preview.openHTML`, `browser.openExternal`, `window.showInformation`, `.showWarning`, `.showError` | Preview, browser, and messages. | @@ -332,6 +333,41 @@ What the SDK does for you, and what it leaves to you: plugin's commands; the host waits for no result. A stopped backend is started for it only when the manifest declares `onCommand:`. +### Remote workspaces + +A backend runs on the machine that runs Lithe also when the workspace is on a +remote host. Such a context has `authority.kind` `remote` and +`authority.platform` `{ os, arch }`, and its folders carry no `path`. +`getHostPaths` gives their paths on the host. It needs the +`workspace.metadata` permission, and only a host that serves it lists it, so +check `supports('lithe/host/workspace/getHostPaths')` first. + +```js +const full = await context.host.workspace.getContext(workspace); +const { folders } = await context.host.workspace.processRoots(full); +for (const root of folders) { + // A local root has `path`; a remote one has `hostPath`, a HostPath. + const cwd = root.path ?? root.hostPath.value; + // ... +} +``` + +- `HostPath` is not a string, so `fs` and `path` refuse it: the machine that + runs the backend has no file there. Pass `value` only to what runs on the + host, such as process arguments or a debug configuration; `JSON.stringify` + writes it as that string. +- `processRoots` takes a full context. For a `local` one it reads the + folders without asking the host; otherwise it calls `getHostPaths`. +- `rootIDs` names 1–256 distinct root IDs; others fail locally with + `sdk.host.invalidParams`. An answer without absolute paths is + `sdk.host.invalidResult`. +- `plugin.host.remoteDisconnected` means the connection was lost while the + request ran, so whether it took effect is unknown; + `plugin.host.platformUnavailable` means the plugin has nothing for the + host's platform. The + [remote workspaces guide](../../guides/plugin-backend-remote-workspaces.md) + says which services serve a remote context. + ### Calling other plugins A plugin can call a function another enabled plugin exports. Core relays @@ -424,8 +460,9 @@ A failed relayed call rejects with a `HostError` whose `code` is one of these | `plugin.function.invalidResult` | -32071 | The provider answered without a result, or with one over 1 MiB. | The host codes `plugin.host.timeout`, `plugin.host.cancelled`, -`plugin.host.contextExpired`, `plugin.host.authorityUnsupported`, -`plugin.host.permissionDenied` and `plugin.host.invalidParams` also occur. On +`plugin.host.contextExpired`, `plugin.host.permissionDenied` and +`plugin.host.invalidParams` also occur; a remote workspace's context is +relayed like a local one. On `plugin.function.failed`, `error.message` is the provider's message and `error.details.pluginErrorCode` is the code the provider's function threw; only branch on a code its provider documents. diff --git a/shared/plugins/sdk/node/src/host.mjs b/shared/plugins/sdk/node/src/host.mjs index 962644f4..ff45a7ca 100644 --- a/shared/plugins/sdk/node/src/host.mjs +++ b/shared/plugins/sdk/node/src/host.mjs @@ -239,6 +239,11 @@ export function createHost(channel, callSignal, parentOperationId) { /** A method whose params name a workspace context. */ const scoped = (method) => async (context, params = {}, options) => request(method, { ...params, context: contextReference(context) }, options); + const getHostPaths = async (context, params = {}, options) => { + const wire = { ...params, context: contextReference(context) }; + if (params?.rootIDs !== undefined) checkRootIds(params.rootIDs); + return hostFolders(await request(HOST_METHODS.workspaceGetHostPaths, wire, options)); + }; return Object.freeze({ get negotiated() { @@ -279,6 +284,18 @@ export function createHost(channel, callSignal, parentOperationId) { request(HOST_METHODS.workspaceGetContext, { context: contextReference(context) }, options), getFolders: async (context, options) => request(HOST_METHODS.workspaceGetFolders, { context: contextReference(context) }, options), + getHostPaths, + processRoots: async (context, options) => { + const kind = context?.authority?.kind; + if (kind === 'local') return { folders: localFolders(context.folders) }; + if (typeof kind !== 'string') { + throw new PluginSdkError( + 'sdk.host.invalidContext', + 'processRoots takes a full context, with its authority and folders, from listContexts or getContext.', + ); + } + return getHostPaths(context, {}, options); + }, readDirectory: scoped(HOST_METHODS.workspaceReadDirectory), stat: scoped(HOST_METHODS.workspaceStat), readFile: scoped(HOST_METHODS.workspaceReadFile), @@ -348,6 +365,77 @@ export function contextReference(value) { return reference; } +/** + * A path on the remote host of a `remote` workspace context, from + * `workspace.getHostPaths`. It is not a string, so it cannot reach `fs` or + * `path` by mistake: the machine that runs the backend has no file there. + * `value` is the absolute POSIX path, for what runs on that host -- process + * arguments and working directories, a debug configuration's `program` or + * `cwd`, a language server's `initializationOptions`. `JSON.stringify` + * writes it as that string. + */ +export class HostPath { + #value; + + constructor(value) { + if (!isHostPath(value)) { + throw new TypeError('A host path is an absolute POSIX path, a string starting with "/".'); + } + this.#value = value; + } + + get value() { + return this.#value; + } + + toString() { + return this.#value; + } + + toJSON() { + return this.#value; + } +} + +function isHostPath(value) { + return typeof value === 'string' && value.startsWith('/'); +} + +function checkRootIds(rootIDs) { + if ( + !Array.isArray(rootIDs) || + rootIDs.length === 0 || + rootIDs.length > LIMITS.maxHostPathRoots || + !rootIDs.every(isCredentialKey) || + new Set(rootIDs).size !== rootIDs.length + ) { + throw new PluginSdkError( + 'sdk.host.invalidParams', + 'rootIDs is 1-256 distinct root IDs of 1-128 ASCII letters, digits, ".", "_", ":" or "-".', + ); + } +} + +/** `{ folders: [{ rootID, hostPath }] }` of a `getHostPaths` answer, each `hostPath` a `HostPath`. */ +function hostFolders(result) { + const folders = result?.folders; + if (!Array.isArray(folders) || !folders.every((folder) => isCredentialKey(folder?.rootID) && isHostPath(folder?.hostPath))) { + throw new PluginSdkError( + 'sdk.host.invalidResult', + 'The host answered getHostPaths without folders of a root ID and an absolute host path.', + ); + } + return { folders: folders.map(({ rootID, hostPath }) => ({ rootID, hostPath: new HostPath(hostPath) })) }; +} + +/** `[{ rootID, path }]` of a `local` context's folders, read without asking the host. */ +function localFolders(folders) { + if (!Array.isArray(folders) || !folders.every((folder) => isCredentialKey(folder?.rootID) && typeof folder?.path === 'string')) { + throw new PluginSdkError('sdk.host.invalidContext', "A local context's folders each carry a rootID and a path."); + } + return folders.map(({ rootID, path }) => ({ rootID, path })); +} + function checkCredentialKey(key) { if (!isCredentialKey(key)) { throw new PluginSdkError( diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 614deebd..1d2ed692 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -62,10 +62,48 @@ export interface WorkspaceFolder { path?: string; } +/** + * The remote host's operating system and CPU architecture: `os` is `linux` + * and `arch` is `arm64` or `x86_64`. Ignore a value you do not know; a later + * host may connect to other systems. + */ +export interface RemotePlatform { + os: string; + arch: string; +} + +/** + * A path on the remote host of a `remote` context, from `getHostPaths`. It + * is not a string, so `fs` and `path` refuse it: the machine that runs the + * backend has no file there. Pass `value` only to what runs on that host. + * `JSON.stringify` writes it as that string. + */ +export class HostPath { + /** Throws `TypeError` unless `value` is an absolute POSIX path. */ + constructor(value: string); + /** The absolute POSIX path on the remote host. */ + readonly value: string; + toString(): string; + toJSON(): string; +} + +/** One root folder of a `remote` context and its path on the remote host. */ +export interface HostFolder { + rootID: string; + hostPath: HostPath; +} + +/** One root folder of a `local` context and its local path. */ +export interface LocalFolder { + rootID: string; + path: string; +} + /** One open workspace in one window. */ export interface WorkspaceContext extends ContextReference { name: string; - authority: { kind: 'local' | 'remote'; id?: string }; + /** `platform` is present only for a remote authority. */ + authority: { kind: 'local' | 'remote'; id?: string; platform?: RemotePlatform }; folders: WorkspaceFolder[]; /** Private to the plugin and the workspace; only `getContext` returns, and creates, it. */ stateDirectory?: string; @@ -238,6 +276,25 @@ export interface Host { listContexts(options?: HostRequestOptions): Promise<{ revision: number; contexts: WorkspaceContext[] }>; getContext(context: ContextReference, options?: HostRequestOptions): Promise; getFolders(context: ContextReference, options?: HostRequestOptions): Promise<{ folders: WorkspaceFolder[] }>; + /** + * The root folders of a `remote` context on the remote host, every root or + * the `rootIDs` named, in that order. Permission `workspace.metadata`, as a + * method grant of its own. A `local` context is `plugin.host.authorityUnsupported`. + */ + getHostPaths( + context: ContextReference, + params?: { rootIDs?: string[] }, + options?: HostRequestOptions, + ): Promise<{ folders: HostFolder[] }>; + /** + * The path a process uses for each root of a full context: `path` of a + * `local` context, without asking the host, or `hostPath` from + * `getHostPaths` for any other authority. + */ + processRoots( + context: WorkspaceContext, + options?: HostRequestOptions, + ): Promise<{ folders: LocalFolder[] } | { folders: HostFolder[] }>; /** Permission `workspace.files.read`. */ readDirectory: Scoped<{ resource: WorkspaceResource; cursor?: string; limit?: number }, { entries: { name: string; resource: WorkspaceResource; kind: string }[]; @@ -844,17 +901,21 @@ export const HOST_ERRORS: Readonly<{ 'plugin.function.providerUnavailable': -32069; 'plugin.function.failed': -32070; 'plugin.function.invalidResult': -32071; + 'plugin.host.remoteDisconnected': -32078; + 'plugin.host.platformUnavailable': -32079; }>; /** Host request method names. */ export const HOST_METHODS: Readonly>; @@ -885,6 +946,7 @@ export const LIMITS: Readonly<{ maxCredentialKeyBytes: number; maxCredentialSecretBytes: number; maxPendingHostRequests: number; + maxHostPathRoots: number; relayDefaultTimeoutMilliseconds: number; relayMaxTimeoutMilliseconds: number; maxParentOperationIdBytes: number; diff --git a/shared/plugins/sdk/node/src/index.mjs b/shared/plugins/sdk/node/src/index.mjs index 6c1d1dd9..1753daef 100644 --- a/shared/plugins/sdk/node/src/index.mjs +++ b/shared/plugins/sdk/node/src/index.mjs @@ -3,6 +3,7 @@ export { createBackend } from './backend.mjs'; export { HostError, PluginError, PluginSdkError } from './errors.mjs'; +export { HostPath } from './host.mjs'; export { runProcess } from './process.mjs'; export { openStateStore } from './state.mjs'; export { HOST_ERRORS, HOST_METHODS, isFunctionId, isVcsId, LIMITS, VCS_ERRORS } from './protocol.mjs'; diff --git a/shared/plugins/sdk/node/src/protocol.mjs b/shared/plugins/sdk/node/src/protocol.mjs index e28303c0..59e9d66d 100644 --- a/shared/plugins/sdk/node/src/protocol.mjs +++ b/shared/plugins/sdk/node/src/protocol.mjs @@ -48,6 +48,7 @@ export const HOST_METHODS = Object.freeze({ workspaceListContexts: 'lithe/host/workspace/listContexts', workspaceGetContext: 'lithe/host/workspace/getContext', workspaceGetFolders: 'lithe/host/workspace/getFolders', + workspaceGetHostPaths: 'lithe/host/workspace/getHostPaths', workspaceReadDirectory: 'lithe/host/workspace/readDirectory', workspaceStat: 'lithe/host/workspace/stat', workspaceReadFile: 'lithe/host/workspace/readFile', @@ -125,6 +126,8 @@ export const HOST_ERRORS = Object.freeze({ 'plugin.function.providerUnavailable': -32069, 'plugin.function.failed': -32070, 'plugin.function.invalidResult': -32071, + 'plugin.host.remoteDisconnected': -32078, + 'plugin.host.platformUnavailable': -32079, }); /** @@ -189,6 +192,7 @@ export const LIMITS = Object.freeze({ maxCredentialKeyBytes: 128, maxCredentialSecretBytes: 16 * 1024, maxPendingHostRequests: 16, + maxHostPathRoots: 256, // The relay's bounds are Core's to enforce; the SDK only names them. relayDefaultTimeoutMilliseconds: 60000, relayMaxTimeoutMilliseconds: 600000, diff --git a/shared/plugins/sdk/node/test/host.test.mjs b/shared/plugins/sdk/node/test/host.test.mjs index 5f80be02..857110e7 100644 --- a/shared/plugins/sdk/node/test/host.test.mjs +++ b/shared/plugins/sdk/node/test/host.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { test } from 'node:test'; -import { createBackend, HOST_ERRORS, HostError, LIMITS, PluginSdkError } from '../src/index.mjs'; +import { createBackend, HOST_ERRORS, HostError, HostPath, LIMITS, PluginSdkError } from '../src/index.mjs'; import { gate, TestHost, withTimeout } from './harness.mjs'; const fixture = JSON.parse( @@ -117,6 +117,86 @@ test('local key and context checks agree with the fixture cases Core refuses or await host.close(); }); +test('host paths: root IDs Core refuses fail locally, and the answer holds HostPath values', async () => { + const { backend, host } = await session(); + const taken = new Set(); + const cases = fixture.hostRequests.filter((testCase) => testCase.method === 'lithe/host/workspace/getHostPaths'); + for (const testCase of cases.filter(({ params }) => params.context && params.path === undefined)) { + const { context, rootIDs } = testCase.params; + const params = rootIDs === undefined ? undefined : { rootIDs }; + if (testCase.expected.forward) { + const asking = backend.host.workspace.getHostPaths(context, params); + const request = await nextRequest(host, 'lithe/host/workspace/getHostPaths', taken); + assert.deepEqual(request.params, testCase.params, testCase.name); + const roots = rootIDs ?? ['r0c1d2e3f4a5b6c7d']; + host.send({ id: request.id, result: { folders: roots.map((rootID, index) => ({ rootID, hostPath: `/srv/root${index}` })) } }); + const { folders } = await asking; + assert.deepEqual(folders.map(({ rootID }) => rootID), roots, testCase.name); + assert.ok(folders.every(({ hostPath }) => hostPath instanceof HostPath), testCase.name); + assert.equal(folders[0].hostPath.value, '/srv/root0', testCase.name); + } else if (testCase.expected.code === 'plugin.host.invalidParams') { + const before = host.messages.length; + await assert.rejects( + backend.host.workspace.getHostPaths(context, params), + (error) => error.code === 'sdk.host.invalidParams', + testCase.name, + ); + assert.equal(host.messages.length, before, testCase.name); + } + } + const missingContext = cases.find(({ params }) => !params.context); + await assert.rejects( + backend.host.workspace.getHostPaths(missingContext.params.context, { rootIDs: missingContext.params.rootIDs }), + (error) => error.code === 'sdk.host.invalidContext', + ); + await assert.rejects( + backend.host.workspace.getHostPaths(CONTEXT, { rootIDs: Array.from({ length: LIMITS.maxHostPathRoots + 1 }, (_, i) => `r${i}`) }), + (error) => error.code === 'sdk.host.invalidParams', + ); + + // An answer that is not root IDs with absolute paths is refused. + for (const result of [{}, { folders: [{ rootID: 'r0', hostPath: 'srv/root0' }] }, { folders: [{ hostPath: '/srv/root0' }] }]) { + const asking = backend.host.workspace.getHostPaths(CONTEXT); + host.send({ id: (await nextRequest(host, 'lithe/host/workspace/getHostPaths', taken)).id, result }); + await assert.rejects(asking, (error) => error.code === 'sdk.host.invalidResult', JSON.stringify(result)); + } + await host.close(); +}); + +test('processRoots reads a local context and asks the host only for a remote one', async () => { + const { backend, host } = await session(); + const before = host.messages.length; + const local = { + ...CONTEXT, + name: 'orders', + authority: { kind: 'local' }, + folders: [{ rootID: 'r0', name: 'orders', path: '/Users/me/orders' }], + }; + assert.deepEqual(await backend.host.workspace.processRoots(local), { folders: [{ rootID: 'r0', path: '/Users/me/orders' }] }); + assert.equal(host.messages.length, before); + + const remote = { + ...CONTEXT, + name: 'orders', + authority: { kind: 'remote', id: 'c-7d41', platform: { os: 'linux', arch: 'x86_64' } }, + folders: [{ rootID: 'r0', name: 'orders' }], + }; + const asking = backend.host.workspace.processRoots(remote); + const request = await nextRequest(host, 'lithe/host/workspace/getHostPaths'); + assert.deepEqual(request.params, { context: CONTEXT }); + host.send({ id: request.id, result: { folders: [{ rootID: 'r0', hostPath: '/home/me/orders' }] } }); + const { folders } = await asking; + assert.equal(folders[0].hostPath.value, '/home/me/orders'); + // A host path goes on the wire as its string, and never passes for a local path. + assert.equal(JSON.stringify({ cwd: folders[0].hostPath }), '{"cwd":"/home/me/orders"}'); + assert.notEqual(typeof folders[0].hostPath, 'string'); + assert.throws(() => new HostPath('home/me/orders'), TypeError); + + // A reference alone does not say the authority. + await assert.rejects(backend.host.workspace.processRoots(CONTEXT), (error) => error.code === 'sdk.host.invalidContext'); + await host.close(); +}); + test('host refusals become HostError with the code, number, and details Core sent', async () => { const { backend, host } = await session(); const taken = new Set(); diff --git a/shared/plugins/sdk/node/test/types/host.mts b/shared/plugins/sdk/node/test/types/host.mts index 2d91a997..d0a5dd36 100644 --- a/shared/plugins/sdk/node/test/types/host.mts +++ b/shared/plugins/sdk/node/test/types/host.mts @@ -1,5 +1,15 @@ // Check the host-service declarations the way a plugin uses them. -import { createBackend, HOST_ERRORS, HostError, type ContextReference, type JsonValue, type Subscription } from '@lithe/plugin-sdk'; +import { + createBackend, + HOST_ERRORS, + HostError, + HostPath, + type ContextReference, + type JsonValue, + type RemotePlatform, + type Subscription, + type WorkspaceContext, +} from '@lithe/plugin-sdk'; const backend = createBackend(); const version: number | null = backend.functionsVersion; @@ -137,3 +147,27 @@ async function nativeTerminal(context: ContextReference) { await backend.host.terminal.dispose(context, { terminalID: created.terminalID }); } void nativeTerminal; + +async function remoteRoots(context: WorkspaceContext) { + const platform: RemotePlatform | undefined = context.authority.platform; + const os: string | undefined = platform?.os; + void os; + const { folders } = await backend.host.workspace.getHostPaths(context, { rootIDs: [context.folders[0]!.rootID] }); + const hostPath: HostPath = folders[0]!.hostPath; + const value: string = hostPath.value; + void value; + // @ts-expect-error A host path is not a local path string. + const local: string = hostPath; + void local; + // @ts-expect-error Root IDs are strings. + await backend.host.workspace.getHostPaths(context, { rootIDs: [1] }); + const roots = await backend.host.workspace.processRoots(context); + for (const root of roots.folders) { + const cwd: string = 'path' in root ? root.path : root.hostPath.value; + void cwd; + } + const failure: -32078 = HOST_ERRORS['plugin.host.remoteDisconnected']; + const unavailable: -32079 = HOST_ERRORS['plugin.host.platformUnavailable']; + void failure; void unavailable; +} +void remoteRoots; diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 13cfa7ca..b3081f72 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -371,6 +371,7 @@ backend | `capabilities()`, `supports(method)` | What this session may call, from `lithe/host/getCapabilities` (asked once). | | `workspace().list_contexts()`, `.get_context(&context)`, `.get_folders(&context)` | Workspace contexts; only `get_context` returns, and creates, the context's `stateDirectory`. | | `workspace().read_directory`, `.stat`, `.read_file`, `.find_files`, `.find_text`, `.watch` | Files of a local context, addressed as `{ rootID, path }` from `get_folders`. | +| `workspace().get_host_paths(&context, root_ids)`, `.process_roots(&full_context)` | Root paths on the remote host of a remote context; see [Remote workspaces](#remote-workspaces). | | `documents().list`, `.get_snapshot`; `editor().get_active`, `.get_selections`, `.apply_edits`, `.replace_selections`, `.insert_text`, `.open`, `.reveal`, `.register_actions` | Live documents and editors. Edits name the `expectedVersion` they were computed against. | | `preview().open_html`, `browser().open_external`, `window().show_information`, `.show_warning`, `.show_error` | Preview, browser, and messages. | | `functions().providers(function_id)`, `.invoke(&context, call)` | The plugins that export a function, and a call to one of them; see [Calling other plugins](#calling-other-plugins). | @@ -440,6 +441,45 @@ nothing is stored. | `sdk.call.cancelled` | The call was cancelled while waiting; `?` answers as cancelled. | | `sdk.session.notReady`, `sdk.session.closed` | The session has not finished `initialize`, or it ended while waiting. | +### Remote workspaces + +A backend runs on the machine that runs Lithe also when the workspace is on a +remote host. Such a context has `authority.kind` `remote` and +`authority.platform` `{ os, arch }`, and its folders carry no `path`. +`get_host_paths` gives their paths on the host. It needs the +`workspace.metadata` permission, and only a host that serves it lists it, so +check `supports("lithe/host/workspace/getHostPaths")` first. + +```rust +use lithe_plugin_sdk::ProcessRoot; + +let full = host.workspace().get_context(&workspace)?; +for root in host.workspace().process_roots(&full)? { + match root { + ProcessRoot::Local { root_id, path } => { /* a path on this machine */ } + ProcessRoot::Remote { root_id, host_path } => { /* a path on the remote host */ } + } +} +``` + +- `HostPath` is its own type and converts to no `Path`, so it is not + passed to `std::fs` or `std::process` by mistake: the machine that runs + the backend has no file there. Give `as_str()` only to what runs on the + host, such as process arguments or a debug configuration; it serializes as + that string. +- `process_roots` takes a full context. For a `local` one it reads the + folders without asking the host; otherwise it calls `get_host_paths`. +- `get_host_paths(&context, None)` asks for every root; `Some(ids)` takes + 1–256 distinct root IDs, and others fail locally with + `sdk.host.invalidParams`. An answer without absolute paths is + `sdk.host.invalidResult`. +- `plugin.host.remoteDisconnected` means the connection was lost while the + request ran, so whether it took effect is unknown; + `plugin.host.platformUnavailable` means the plugin has nothing for the + host's platform. The + [remote workspaces guide](../../guides/plugin-backend-remote-workspaces.md) + says which services serve a remote context. + ### Calling other plugins A backend may call a function another plugin exports; Core relays the call and @@ -543,7 +583,7 @@ backend | `plugin.function.callCycle`, `.depthExceeded`, `.tooManyCalls`, `.payloadTooLarge` | The chain, the caller's running calls, or a payload exceeded a limit. | | `plugin.function.providerUnavailable`, `.invalidResult` | The provider's backend stopped or did not start in time, or answered with no result or one over 1 MiB. | | `plugin.function.failed` | The provider's function returned an error. The `pluginErrorCode` entry of `details()` is the provider's own `PluginError` code, and `message()` is its message. | -| `plugin.host.contextExpired`, `plugin.host.authorityUnsupported`, `plugin.host.timeout`, `plugin.host.cancelled` | The context was closed or replaced, is not a local workspace, the deadline passed, or the call (or its parent) was cancelled. | +| `plugin.host.contextExpired`, `plugin.host.timeout`, `plugin.host.cancelled` | The context was closed or replaced, the deadline passed, or the call (or its parent) was cancelled. A remote workspace's context is relayed like a local one. | | `sdk.host.invalidResult` | The host answered with something other than an object. | ## Results and errors diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/error.rs b/shared/plugins/sdk/rust/plugin-sdk/src/error.rs index 15ecd543..7fa049b0 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/error.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/error.rs @@ -90,8 +90,8 @@ pub mod sdk_codes { } /// Stable `plugin.host.*` failure codes and their JSON-RPC numbers. A later -/// host adds codes after `-32026`. -pub const HOST_ERROR_CODES: [(&str, i64); 21] = [ +/// host adds codes at numbers no code of the contract uses yet. +pub const HOST_ERROR_CODES: [(&str, i64); 23] = [ ("plugin.host.unavailable", -32601), ("plugin.host.invalidParams", -32602), ("plugin.host.failed", -32603), @@ -113,12 +113,14 @@ pub const HOST_ERROR_CODES: [(&str, i64); 21] = [ ("plugin.host.methodNotDeclared", -32024), ("plugin.host.toolUnresolved", -32025), ("plugin.host.foreignContribution", -32026), + ("plugin.host.remoteDisconnected", -32078), + ("plugin.host.platformUnavailable", -32079), ]; /// The `plugin.function.*` failures a relayed call from another plugin may /// end with, and their JSON-RPC numbers. The -/// relay's `plugin.host.*` outcomes (`timeout`, `cancelled`, `contextExpired`, -/// `authorityUnsupported`) are in [`HOST_ERROR_CODES`]. A +/// relay's `plugin.host.*` outcomes (`timeout`, `cancelled`, `contextExpired`) +/// are in [`HOST_ERROR_CODES`]. A /// `plugin.function.failed` answer names the provider's own code in its /// `pluginErrorCode` detail. pub const RELAY_ERROR_CODES: [(&str, i64); 11] = [ @@ -335,7 +337,7 @@ mod tests { #[test] fn the_host_and_relay_tables_hold_every_documented_code_once() { - assert_eq!(HOST_ERROR_CODES.len(), 21); + assert_eq!(HOST_ERROR_CODES.len(), 23); assert_eq!(RELAY_ERROR_CODES.len(), 11); let mut codes = std::collections::BTreeSet::new(); let mut numbers = std::collections::BTreeSet::new(); diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs index 94b688e6..15067e54 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs @@ -12,10 +12,13 @@ use crate::backend::{lock, Cancellation, Phase, Shared, State}; use crate::error::{sdk_codes, SdkError}; use crate::protocol::{ generation, is_credential_key, is_function_id, is_parent_operation_id, methods, - MAX_CREDENTIAL_SECRET_BYTES, MAX_EARLY_EVENTS, MAX_PENDING_HOST_REQUESTS, + MAX_CREDENTIAL_SECRET_BYTES, MAX_EARLY_EVENTS, MAX_HOST_PATH_ROOTS, MAX_PENDING_HOST_REQUESTS, }; +use serde::{Serialize, Serializer}; use serde_json::{json, Map, Value}; -use std::collections::{HashMap, VecDeque}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::fmt; +use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, RecvTimeoutError}; use std::sync::{Arc, Mutex, PoisonError, Weak}; @@ -820,6 +823,56 @@ impl Workspace { .scoped(methods::WORKSPACE_GET_FOLDERS, context, Value::Null) } + /// The roots of a `remote` context on its remote host: `None` for every + /// root, or 1-256 distinct root IDs. It needs the `workspace.metadata` + /// permission; a local context fails with + /// `plugin.host.authorityUnsupported`, an unknown root ID with + /// `plugin.host.notFound`. + pub fn get_host_paths( + &self, + context: &WorkspaceContext, + root_ids: Option<&[&str]>, + ) -> Result, SdkError> { + let params = match root_ids { + None => Value::Null, + Some(root_ids) if distinct_root_ids(root_ids) => json!({ "rootIDs": root_ids }), + Some(_) => { + return Err(SdkError::new( + "sdk.host.invalidParams", + "rootIDs is 1-256 distinct root IDs of 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\".", + )) + } + }; + let params = with_context(context, params)?; + host_folders( + &self + .host + .request(methods::WORKSPACE_GET_HOST_PATHS, params)?, + ) + } + + /// The roots of a full context from `list_contexts` or `get_context` as + /// a process started for it names its working directory. A `local` + /// context's folders are read without asking the host; for any other + /// authority it calls [`get_host_paths`](Self::get_host_paths). + pub fn process_roots(&self, context: &Value) -> Result, SdkError> { + match context["authority"]["kind"].as_str() { + Some("local") => local_folders(&context["folders"]), + Some(_) => Ok(self + .get_host_paths(&WorkspaceContext::from_value(context)?, None)? + .into_iter() + .map(|folder| ProcessRoot::Remote { + root_id: folder.root_id, + host_path: folder.host_path, + }) + .collect()), + None => Err(SdkError::new( + "sdk.host.invalidContext", + "process_roots takes a full context, with its authority and folders, from list_contexts or get_context.", + )), + } + } + /// `params`: `resource, cursor?, limit?`. pub fn read_directory( &self, @@ -865,6 +918,140 @@ impl Workspace { } } +/// A path on the remote host of a `remote` workspace context, from +/// [`Workspace::get_host_paths`]. It is not a [`Path`](std::path::Path) and +/// converts to none, so it cannot reach `std::fs` by mistake: the machine +/// that runs the backend has no file there. [`as_str`](Self::as_str) is the +/// absolute POSIX path, for what runs on that host -- process arguments and +/// working directories, a debug configuration's `program` or `cwd`, a +/// language server's `initializationOptions`. It serializes as that string. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct HostPath(String); + +impl HostPath { + /// `None` unless `value` is an absolute POSIX path, a string starting + /// with `/`. + pub fn new(value: impl Into) -> Option { + let value = value.into(); + value.starts_with('/').then_some(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn into_string(self) -> String { + self.0 + } +} + +impl fmt::Display for HostPath { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } +} + +impl Serialize for HostPath { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.0) + } +} + +/// One root of a [`Workspace::get_host_paths`] answer. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HostFolder { + root_id: String, + host_path: HostPath, +} + +impl HostFolder { + pub fn root_id(&self) -> &str { + &self.root_id + } + + pub fn host_path(&self) -> &HostPath { + &self.host_path + } +} + +/// A root of a context as a process started for it names its working +/// directory, from [`Workspace::process_roots`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ProcessRoot { + /// A root of a `local` context, on the machine that runs the backend. + Local { root_id: String, path: PathBuf }, + /// A root of a `remote` context, on its remote host. + Remote { + root_id: String, + host_path: HostPath, + }, +} + +impl ProcessRoot { + pub fn root_id(&self) -> &str { + match self { + Self::Local { root_id, .. } | Self::Remote { root_id, .. } => root_id, + } + } +} + +fn distinct_root_ids(root_ids: &[&str]) -> bool { + let mut seen = HashSet::new(); + (1..=MAX_HOST_PATH_ROOTS).contains(&root_ids.len()) + && root_ids + .iter() + .all(|id| is_credential_key(id) && seen.insert(*id)) +} + +/// `[{ rootID, hostPath }]` of a `getHostPaths` answer's `folders`. +fn host_folders(result: &Value) -> Result, SdkError> { + let invalid = || { + SdkError::new( + "sdk.host.invalidResult", + "The host answered getHostPaths without folders of a root ID and an absolute host path.", + ) + }; + let folders = result["folders"].as_array().ok_or_else(invalid)?; + folders + .iter() + .map(|folder| { + let root_id = folder["rootID"].as_str().filter(|id| is_credential_key(id)); + let host_path = folder["hostPath"].as_str().and_then(HostPath::new); + match (root_id, host_path) { + (Some(root_id), Some(host_path)) => Ok(HostFolder { + root_id: root_id.to_string(), + host_path, + }), + _ => Err(invalid()), + } + }) + .collect() +} + +/// `[{ rootID, path }]` of a `local` context's folders. +fn local_folders(folders: &Value) -> Result, SdkError> { + let invalid = || { + SdkError::new( + "sdk.host.invalidContext", + "A local context's folders each carry a rootID and a path.", + ) + }; + let folders = folders.as_array().ok_or_else(invalid)?; + folders + .iter() + .map(|folder| { + let root_id = folder["rootID"].as_str().filter(|id| is_credential_key(id)); + match (root_id, folder["path"].as_str()) { + (Some(root_id), Some(path)) => Ok(ProcessRoot::Local { + root_id: root_id.to_string(), + path: PathBuf::from(path), + }), + _ => Err(invalid()), + } + }) + .collect() +} + impl Host { fn scoped_without_context(&self, method: &str) -> Outcome { match self.request(method, json!({}))? { diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs index 78b896e1..f3b97c7d 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs @@ -55,8 +55,8 @@ pub use error::{ sdk_codes, Cancelled, FunctionError, PluginError, SdkError, HOST_ERROR_CODES, RELAY_ERROR_CODES, }; pub use host::{ - Browser, Credentials, Documents, Editor, Event, Functions, Host, Preview, Subscription, - Subscriptions, Terminal, Window, Workspace, WorkspaceContext, + Browser, Credentials, Documents, Editor, Event, Functions, Host, HostFolder, HostPath, Preview, + ProcessRoot, Subscription, Subscriptions, Terminal, Window, Workspace, WorkspaceContext, }; pub use protocol::{is_command_id, is_credential_key, is_function_id, is_plugin_error_code}; pub use serde_json::Value; diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs index 78ef2599..84383352 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs @@ -51,6 +51,7 @@ pub(crate) mod methods { pub const WORKSPACE_LIST_CONTEXTS: &str = "lithe/host/workspace/listContexts"; pub const WORKSPACE_GET_CONTEXT: &str = "lithe/host/workspace/getContext"; pub const WORKSPACE_GET_FOLDERS: &str = "lithe/host/workspace/getFolders"; + pub const WORKSPACE_GET_HOST_PATHS: &str = "lithe/host/workspace/getHostPaths"; pub const WORKSPACE_READ_DIRECTORY: &str = "lithe/host/workspace/readDirectory"; pub const WORKSPACE_STAT: &str = "lithe/host/workspace/stat"; pub const WORKSPACE_READ_FILE: &str = "lithe/host/workspace/readFile"; @@ -120,6 +121,8 @@ pub(crate) const MAX_EARLY_EVENTS: usize = 128; const MAX_COMMAND_ID_BYTES: usize = 128; /// The longest `parentOperationID` Core accepts on a relayed call. const MAX_PARENT_OPERATION_ID_BYTES: usize = 128; +/// The most root IDs one `getHostPaths` request names. +pub(crate) const MAX_HOST_PATH_ROOTS: usize = 256; /// The largest integer JSON carries exactly. const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1; diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/host_services.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/host_services.rs index baf876b2..a40f76c3 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/tests/host_services.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/host_services.rs @@ -5,13 +5,13 @@ mod common; use common::{Host, WAIT}; use lithe_plugin_sdk::{ - is_credential_key, Backend, Cancellation, FunctionError, SdkError, WorkspaceContext, - HOST_ERROR_CODES, + is_credential_key, Backend, Cancellation, FunctionError, HostPath, ProcessRoot, SdkError, + WorkspaceContext, HOST_ERROR_CODES, }; use serde_json::{json, Value}; use std::collections::{BTreeSet, VecDeque}; use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::mpsc::{self, RecvTimeoutError}; use std::sync::Arc; use std::thread; @@ -783,6 +783,170 @@ fn native_terminal_methods_keep_context_and_literal_arguments() { session.close(); } +#[test] +fn host_path_root_ids_core_refuses_fail_locally_and_the_answer_holds_host_paths() { + let backend = Backend::new("test-backend"); + let host = backend.handle().host(); + let mut session = Session::start(backend); + let mut checked = 0; + for case in cases(&fixture(), "hostRequests") { + let params = &case["params"]; + if case["method"] != "lithe/host/workspace/getHostPaths" + || params["context"].is_null() + || !params["path"].is_null() + { + continue; + } + let name = case["name"].as_str().unwrap().to_string(); + let workspace = WorkspaceContext::from_value(¶ms["context"]).unwrap(); + let root_ids: Option> = params["rootIDs"].as_array().map(|ids| { + ids.iter() + .map(|id| id.as_str().unwrap().to_string()) + .collect() + }); + let expected = &case["expected"]; + if expected.get("forward").is_some() { + let asking = { + let (host, workspace, root_ids) = + (host.clone(), workspace.clone(), root_ids.clone()); + background(move || { + let ids: Option> = root_ids + .as_ref() + .map(|ids| ids.iter().map(String::as_str).collect()); + host.workspace().get_host_paths(&workspace, ids.as_deref()) + }) + }; + let request = session.take("lithe/host/workspace/getHostPaths"); + assert_eq!(&request["params"], params, "{name}"); + let roots = root_ids.unwrap_or_else(|| vec!["r0c1d2e3f4a5b6c7d".to_string()]); + let folders: Vec = roots + .iter() + .enumerate() + .map(|(index, id)| json!({ "rootID": id, "hostPath": format!("/srv/root{index}") })) + .collect(); + session.reply(&request, json!({ "folders": folders })); + let answer = done(&asking).unwrap(); + assert_eq!(answer.len(), roots.len(), "{name}"); + assert_eq!(answer[0].root_id(), roots[0], "{name}"); + assert_eq!(answer[0].host_path().as_str(), "/srv/root0", "{name}"); + checked += 1; + } else if expected["code"] == "plugin.host.invalidParams" { + let ids: Vec<&str> = root_ids + .as_ref() + .expect("an invalid case names root IDs") + .iter() + .map(String::as_str) + .collect(); + assert_eq!( + code(host.workspace().get_host_paths(&workspace, Some(&ids))), + "sdk.host.invalidParams", + "{name}" + ); + checked += 1; + } + } + assert_eq!(checked, 5); + let too_many: Vec = (0..257).map(|index| format!("r{index}")).collect(); + let too_many: Vec<&str> = too_many.iter().map(String::as_str).collect(); + assert_eq!( + code(host.workspace().get_host_paths(&context(), Some(&too_many))), + "sdk.host.invalidParams" + ); + session.host.assert_quiet(); + + // An answer that is not root IDs with absolute paths is refused. + for answer in [ + json!({}), + json!({ "folders": [{ "rootID": "r0", "hostPath": "srv/root0" }] }), + json!({ "folders": [{ "hostPath": "/srv/root0" }] }), + ] { + let asking = { + let host = host.clone(); + background(move || host.workspace().get_host_paths(&context(), None)) + }; + let request = session.take("lithe/host/workspace/getHostPaths"); + session.reply(&request, answer.clone()); + assert_eq!(code(done(&asking)), "sdk.host.invalidResult", "{answer}"); + } + session.close(); +} + +#[test] +fn process_roots_reads_a_local_context_and_asks_the_host_only_for_a_remote_one() { + let backend = Backend::new("test-backend"); + let host = backend.handle().host(); + let mut session = Session::start(backend); + let local = host + .workspace() + .process_roots(&json!({ + "contextID": "w1", "generation": 2, "name": "orders", "authority": { "kind": "local" }, + "folders": [{ "rootID": "r0", "name": "orders", "path": "/Users/me/orders" }] + })) + .unwrap(); + assert_eq!( + local, + [ProcessRoot::Local { + root_id: "r0".into(), + path: PathBuf::from("/Users/me/orders") + }] + ); + session.host.assert_quiet(); + + let asking = { + let host = host.clone(); + background(move || { + host.workspace().process_roots(&json!({ + "contextID": "w1", "generation": 2, "name": "orders", + "authority": { "kind": "remote", "id": "c-7d41", "platform": { "os": "linux", "arch": "x86_64" } }, + "folders": [{ "rootID": "r0", "name": "orders" }] + })) + }) + }; + let request = session.take("lithe/host/workspace/getHostPaths"); + assert_eq!( + request["params"], + json!({ "context": { "contextID": "w1", "generation": 2 } }) + ); + session.reply( + &request, + json!({ "folders": [{ "rootID": "r0", "hostPath": "/home/me/orders" }] }), + ); + let remote = done(&asking).unwrap(); + let host_path = HostPath::new("/home/me/orders").unwrap(); + assert_eq!( + remote, + [ProcessRoot::Remote { + root_id: "r0".into(), + host_path: host_path.clone() + }] + ); + assert_eq!(remote[0].root_id(), "r0"); + // It is written as the path, for what runs on the remote host. + assert_eq!( + json!({ "cwd": host_path }), + json!({ "cwd": "/home/me/orders" }) + ); + assert_eq!(host_path.to_string(), "/home/me/orders"); + assert_eq!(HostPath::new("home/me/orders"), None); + + // A reference alone does not say the authority, and a local folder names its path. + for context in [ + context().to_value(), + json!({ + "contextID": "w1", "generation": 2, "authority": { "kind": "local" }, + "folders": [{ "rootID": "r0" }] + }), + ] { + assert_eq!( + code(host.workspace().process_roots(&context)), + "sdk.host.invalidContext", + "{context}" + ); + } + session.host.assert_quiet(); + session.close(); +} + #[test] fn a_relayed_call_names_the_plugin_that_called_it_and_a_host_call_names_none() { let mut checked = 0; @@ -969,7 +1133,7 @@ fn relay_refusals_keep_the_code_number_and_the_providers_own_code() { done(&pending).expect_err("a refusal") }; let relay_errors = cases(&fixture(), "relayErrors"); - assert_eq!(relay_errors.len(), 15); + assert_eq!(relay_errors.len(), 14); for case in relay_errors { let expected = case["code"].as_str().unwrap(); let number = case["rpcCode"].as_i64().unwrap();