From 87be12195c4cf17d8a38d38e4d9fc37e1c0221ed Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 19 Nov 2026 18:50:00 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(plugins):=20Rust=20SDK=20=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E6=9E=84=E5=BB=BA=E6=8F=90=E4=BE=9B=E8=80=85=EF=BC=88?= =?UTF-8?q?litheBuild=200/1=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rust SDK 新增 build_model、build_dependencies、build_execute、build_test、 build_discover_tests、build_run_entrypoints、build_prepare_run、 build_prepare_debug 注册方法和 BuildContext,对齐 Node.js SDK 的 build.*: 协商 litheBuild(只在有处理函数时应答 ≤1 的最新版本),每个请求在自己的 线程里运行,检查 operationID、发送有界的 lithe/build/progress,给结果文档 补 format/version 并检查结果形状,映射 PluginError、取消和 panic。 文档同步:Rust SDK README 新增“Build providers”一节;契约 README、插件总览、 原生构建指南、能力与版本、构建提供者参考写明 main 上的 Rust SDK 源码已支持、 随下一次 Rust SDK 发布提供;Node.js SDK README 按桌面端 Declared() 更正 桌面端声明的能力。 --- shared/plugins/README.md | 4 +- shared/plugins/contract/v1/README.md | 9 +- .../plugins/guides/native-build-workflows.md | 44 +-- .../reference/capabilities-and-versions.md | 4 +- .../reference/domains/build-providers.md | 4 +- shared/plugins/sdk/node/README.md | 10 +- shared/plugins/sdk/rust/README.md | 103 +++++- .../sdk/rust/plugin-sdk/src/backend.rs | 276 ++++++++++++++- .../plugins/sdk/rust/plugin-sdk/src/build.rs | 290 ++++++++++++++++ shared/plugins/sdk/rust/plugin-sdk/src/lib.rs | 7 +- .../sdk/rust/plugin-sdk/src/protocol.rs | 24 ++ .../sdk/rust/plugin-sdk/tests/build.rs | 327 ++++++++++++++++++ 12 files changed, 1041 insertions(+), 61 deletions(-) create mode 100644 shared/plugins/sdk/rust/plugin-sdk/src/build.rs create mode 100644 shared/plugins/sdk/rust/plugin-sdk/tests/build.rs diff --git a/shared/plugins/README.md b/shared/plugins/README.md index cf1c5821..aee5f29e 100644 --- a/shared/plugins/README.md +++ b/shared/plugins/README.md @@ -104,7 +104,7 @@ Schema 只检查 JSON 结构。ID 引用、权限、激活事件、模板变量 只用语言服务器、运行和测试的插件不需要后端。需要构建后端(`buildProviders`)、插件函数,或给插件自己的网页配一个后端进程(`backend`)时,用官方 SDK 写:协议、取消、进程清理和错误处理由 SDK 负责,你只写处理函数。 -**新插件优先用 Rust 或 Go SDK。** 两者把后端编译成每个平台各一份的原生可执行文件,用户机器上不需要 Node.js 或 Java 运行时,常驻的后端也不会多占一份 JVM 的内存和启动时间。插件管理的是 JVM 工具(例如 Maven、Gradle、Tomcat)时也一样:后端用 Rust 或 Go 启动这些工具的进程即可。只有后端必须在 JVM 里直接调用 Java 库时,才用 Java SDK。构建后端(`buildProviders`)目前只有 Node.js 和 Java SDK 支持,VCS 后端只有 Node.js SDK 支持,这两类后端照旧用它们。 +**新插件优先用 Rust 或 Go SDK。** 两者把后端编译成每个平台各一份的原生可执行文件,用户机器上不需要 Node.js 或 Java 运行时,常驻的后端也不会多占一份 JVM 的内存和启动时间。插件管理的是 JVM 工具(例如 Maven、Gradle、Tomcat)时也一样:后端用 Rust 或 Go 启动这些工具的进程即可。只有后端必须在 JVM 里直接调用 Java 库时,才用 Java SDK。构建后端(`buildProviders`)的发布版目前只有 Node.js 和 Java SDK 支持;`main` 上的 Rust SDK 源码也支持,随下一次 Rust SDK 发布提供,在那之前可以用 Git 依赖锁定包含它的 commit。VCS 后端只有 Node.js SDK 支持,照旧用它。 | SDK | 版本 | 运行时 | Release | 怎么放进插件 | | --- | --- | --- | --- | --- | @@ -324,7 +324,7 @@ A schema checks only JSON structure. Rules such as ID references, permissions, a A plugin that uses only language servers, run, and test needs no backend. When you need a build backend (`buildProviders`), plugin functions, or a backend process for the plugin's own web page (`backend`), write it with an official SDK: the SDK handles the protocol, cancellation, process cleanup, and errors, and you write only the handlers. -**New plugins should prefer the Rust or Go SDK.** Both compile the backend to one native executable per platform, so users need no Node.js or Java runtime, and a long-running backend does not cost an extra JVM heap and startup. The same holds when the plugin manages JVM tools such as Maven, Gradle, or Tomcat: a Rust or Go backend starts those tools as processes. Use the Java SDK only when the backend must call Java libraries inside the JVM. Build backends (`buildProviders`) are supported only by the Node.js and Java SDKs today, and VCS backends only by the Node.js SDK, so keep using those for them. +**New plugins should prefer the Rust or Go SDK.** Both compile the backend to one native executable per platform, so users need no Node.js or Java runtime, and a long-running backend does not cost an extra JVM heap and startup. The same holds when the plugin manages JVM tools such as Maven, Gradle, or Tomcat: a Rust or Go backend starts those tools as processes. Use the Java SDK only when the backend must call Java libraries inside the JVM. Among released SDKs, build backends (`buildProviders`) are supported only by the Node.js and Java SDKs; the Rust SDK source on `main` supports them too and ships in the next Rust SDK release, and until then a Git dependency can pin a commit that contains it. VCS backends are supported only by the Node.js SDK, so keep using it for them. | SDK | Version | Runtime | Release | How it goes into the plugin | | --- | --- | --- | --- | --- | diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index c980fb27..492fc644 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4766,10 +4766,11 @@ mapping, with one difference: on Java 8 it stops only a cancelled tool's direct child, and the host's process scope ends the rest. [`sdk/rust`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/sdk/rust/README.md) is the SDK for -[plugin backends](#plugin-backend), which ship as packaged executables. It -implements this protocol with its host services, but neither build nor VCS -providers. It needs Rust 1.87 or newer, depends only on `serde_json`, and is -released (`sdk-rust-v`) as a `.crate` archive with its SHA-256, or +[plugin backends](#plugin-backend) and own-process +[build providers](#build-providers), which ship as packaged executables. It +implements this protocol with its host services and `litheBuild`, but not VCS +providers. It needs Rust 1.87 or newer, depends only on `serde`, `serde_json` +and `base64`, and is released (`sdk-rust-v`) as a `.crate` archive with its SHA-256, or used as a Git dependency pinned by the tag. It enforces the same rules: on Unix it points stdout at stderr so only protocol frames reach the host, and a panic ends only its call, reported like any unexpected failure. diff --git a/shared/plugins/guides/native-build-workflows.md b/shared/plugins/guides/native-build-workflows.md index d74a8d21..2c062b45 100644 --- a/shared/plugins/guides/native-build-workflows.md +++ b/shared/plugins/guides/native-build-workflows.md @@ -6,22 +6,22 @@ 插件可以只提供工作区后端,不创建网页。用户从原生工具窗口执行构建、发现与运行测试、准备应用启动;宿主继续管理工作区、取消、输出和应用进程。 -这些入口都属于 `buildProviders`(版本 `0`):清单要求 `requires.buildProviders: 0`,进程协议 `litheBuild` 的版本就是 `buildProviders` 的版本。Node.js SDK 0.5.0 和 Java SDK 0.5.0 实现了全部入口;Rust SDK 0.4.0 和 Go SDK 没有构建提供者接口。能力定义见[构建提供者](../reference/domains/build-providers.md),字段和错误码以[契约](../contract/v1/README.md#build-providers)为准。 +这些入口都属于 `buildProviders`(版本 `0`):清单要求 `requires.buildProviders: 0`,进程协议 `litheBuild` 的版本就是 `buildProviders` 的版本。Node.js SDK 0.5.0 和 Java SDK 0.5.0 实现了全部入口;`main` 上的 Rust SDK 源码也实现了全部入口,随下一次 Rust SDK 发布提供(0.4.0 没有);Go SDK 没有构建提供者接口。能力定义见[构建提供者](../reference/domains/build-providers.md),字段和错误码以[契约](../contract/v1/README.md#build-providers)为准。 -> **宿主支持。** Lithe 桌面端声明 `buildSystems` 和 `buildProviders`:构建窗口发现构建实例、加载提供者模型、解析可执行文件候选并运行任务。构建提供者的运行准备、测试、调试准备、model inputs、原生配置、内联测试报告和运行时调试,桌面端尚未呈现,见 -> [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go) 中 `Declared()` 上方的注释。下文的入口因此由 Core 与 SDK 的端到端测试验证,插件作者在桌面端界面里暂时看不到测试、运行和调试这几类入口的效果。 +> **宿主支持。** Lithe 桌面端声明 `buildSystems` 和 `buildProviders`(版本 `0` 和 `1`):构建窗口发现构建实例、加载提供者模型、解析可执行文件候选、运行命令任务和提供者任务、准备应用启动,并发现和运行提供者测试;“运行当前文件”向版本 `1` 的提供者询问文件里的入口。构建提供者的调试准备、model inputs、原生配置、内联测试报告和运行时调试,桌面端尚未呈现,见 +> [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go) 中 `Declared()` 上方的注释。下文的调试准备入口因此只由 Core 与 SDK 的端到端测试验证,插件作者在桌面端界面里暂时看不到它的效果。 ### 选择入口 -| 工作 | Node.js SDK | Java SDK | 清单里的声明 | -| --- | --- | --- | --- | -| 执行有界任务 | `backend.build.execute` | `onExecute` | 任务 `source: "provider"` | -| 运行精确测试 | `backend.build.test` | `onTest` | `test.source: "provider"` | -| 发现可运行的用例 | `backend.build.discoverTests` | `onDiscoverTests` | `test.discovery: true` | -| 准备应用启动 | `backend.build.prepareRun` | `onPrepareRun` | `run[].source: "provider"` | -| 准备原生程序调试 | `backend.build.prepareDebug` | `onPrepareDebug` | `run[].debug: {"adapter": "native"}` | +| 工作 | Node.js SDK | Java SDK | Rust SDK | 清单里的声明 | +| --- | --- | --- | --- | --- | +| 执行有界任务 | `backend.build.execute` | `onExecute` | `build_execute` | 任务 `source: "provider"` | +| 运行精确测试 | `backend.build.test` | `onTest` | `build_test` | `test.source: "provider"` | +| 发现可运行的用例 | `backend.build.discoverTests` | `onDiscoverTests` | `build_discover_tests` | `test.discovery: true` | +| 准备应用启动 | `backend.build.prepareRun` | `onPrepareRun` | `build_prepare_run` | `run[].source: "provider"` | +| 准备原生程序调试 | `backend.build.prepareDebug` | `onPrepareDebug` | `build_prepare_debug` | `run[].debug: {"adapter": "native"}` | -安装时检查清单的能力版本;启动时 SDK 只在注册了构建处理器、且宿主提供了 `litheBuild` 版本 `0` 时才协商构建协议。没有协商成功时,构建方法在进入处理器之前被拒绝;不会改发私有函数,也不会展开成另一条宿主命令。Node.js 用 `backend.buildVersion` 查看结果(协商到为 `0`,否则为 `null`),Java 用 `backend.negotiated().buildVersion()`。 +安装时检查清单的能力版本;启动时 SDK 只在注册了构建处理器、且宿主提供了 `litheBuild` 版本 `0` 时才协商构建协议。没有协商成功时,构建方法在进入处理器之前被拒绝;不会改发私有函数,也不会展开成另一条宿主命令。Node.js 用 `backend.buildVersion` 查看结果(协商到为 `0`,否则为 `null`),Java 用 `backend.negotiated().buildVersion()`,Rust 用 `BackendHandle::build_version()` 或 `Initialize::build_version()`(协商到的版本,否则为 `None`)。 处理器必须在 `listen` 前注册。模型、依赖和测试发现回复由 SDK 补齐对应的 `format` 和 `version: 0`;执行回复是 `{ exitCode, output }`,启动准备回复是完整的可移植计划。Core 继续检查选择器、工作区路径和大小限制。 @@ -104,22 +104,22 @@ node shared/plugins/scripts/sdk-e2e.mjs A plugin can provide only a workspace backend and create no web page. Users build, discover and run tests, and prepare application launches from native tool windows; the host keeps managing the workspace, cancellation, output, and application processes. -These entry points all belong to `buildProviders` (version `0`): the manifest requires `requires.buildProviders: 0`, and the version of the `litheBuild` process protocol is the version of `buildProviders`. Node.js SDK 0.5.0 and Java SDK 0.5.0 implement every entry point; Rust SDK 0.4.0 and the Go SDK have no build-provider interface. For the capability see [Build providers](../reference/domains/build-providers.md); the [contract](../contract/v1/README.md#build-providers) is normative for fields and error codes. +These entry points all belong to `buildProviders` (version `0`): the manifest requires `requires.buildProviders: 0`, and the version of the `litheBuild` process protocol is the version of `buildProviders`. Node.js SDK 0.5.0 and Java SDK 0.5.0 implement every entry point; the Rust SDK source on `main` implements them too, shipping in the next Rust SDK release (0.4.0 does not); the Go SDK has no build-provider interface. For the capability see [Build providers](../reference/domains/build-providers.md); the [contract](../contract/v1/README.md#build-providers) is normative for fields and error codes. -> **Host support.** The Lithe desktop declares `buildSystems` and `buildProviders`: the Build window detects build instances, loads provider models, resolves executable candidates, and runs tasks. Build-provider run preparation, tests, debug preparation, model inputs, native configuration, inline test reports, and runtime debugging are not presented on the desktop yet; see the comment above `Declared()` in -> [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go). The entry points below are therefore verified by the Core and SDK end-to-end tests, and a plugin author cannot yet see the effect of the test, run, and debug entry points in the desktop UI. +> **Host support.** The Lithe desktop declares `buildSystems` and `buildProviders` (versions `0` and `1`): the Build window detects build instances, loads provider models, resolves executable candidates, runs command and provider tasks, prepares application launches, and discovers and runs provider tests; Run on Current File asks providers of version `1` for a file's entrypoints. Build-provider debug preparation, model inputs, native configuration, inline test reports, and runtime debugging are not presented on the desktop yet; see the comment above `Declared()` in +> [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go). The debug preparation entry point below is therefore verified only by the Core and SDK end-to-end tests, and a plugin author cannot yet see its effect in the desktop UI. ### Choosing an entry point -| Work | Node.js SDK | Java SDK | Manifest declaration | -| --- | --- | --- | --- | -| Execute a bounded task | `backend.build.execute` | `onExecute` | task `source: "provider"` | -| Run exact tests | `backend.build.test` | `onTest` | `test.source: "provider"` | -| Discover runnable cases | `backend.build.discoverTests` | `onDiscoverTests` | `test.discovery: true` | -| Prepare an application launch | `backend.build.prepareRun` | `onPrepareRun` | `run[].source: "provider"` | -| Prepare native program debugging | `backend.build.prepareDebug` | `onPrepareDebug` | `run[].debug: {"adapter": "native"}` | +| Work | Node.js SDK | Java SDK | Rust SDK | Manifest declaration | +| --- | --- | --- | --- | --- | +| Execute a bounded task | `backend.build.execute` | `onExecute` | `build_execute` | task `source: "provider"` | +| Run exact tests | `backend.build.test` | `onTest` | `build_test` | `test.source: "provider"` | +| Discover runnable cases | `backend.build.discoverTests` | `onDiscoverTests` | `build_discover_tests` | `test.discovery: true` | +| Prepare an application launch | `backend.build.prepareRun` | `onPrepareRun` | `build_prepare_run` | `run[].source: "provider"` | +| Prepare native program debugging | `backend.build.prepareDebug` | `onPrepareDebug` | `build_prepare_debug` | `run[].debug: {"adapter": "native"}` | -The manifest's capability versions are checked at install time; at startup the SDK negotiates the build protocol only when build handlers are registered and the host offers `litheBuild` version `0`. Without a negotiated protocol, a build method is rejected before it reaches the handler; it is never rerouted to a private function or expanded into a different host command. Read the result with `backend.buildVersion` in Node.js (`0` when negotiated, otherwise `null`) or `backend.negotiated().buildVersion()` in Java. +The manifest's capability versions are checked at install time; at startup the SDK negotiates the build protocol only when build handlers are registered and the host offers `litheBuild` version `0`. Without a negotiated protocol, a build method is rejected before it reaches the handler; it is never rerouted to a private function or expanded into a different host command. Read the result with `backend.buildVersion` in Node.js (`0` when negotiated, otherwise `null`), `backend.negotiated().buildVersion()` in Java, or `BackendHandle::build_version()` or `Initialize::build_version()` in Rust (the negotiated version, otherwise `None`). Register handlers before `listen`. For model, dependency, and test discovery replies, the SDK fills in the matching `format` and `version: 0`; an execution reply is `{ exitCode, output }`, and a launch preparation reply is a complete portable plan. Core still checks selectors, workspace paths, and size limits. diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index b6095d92..4b4db58c 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -113,7 +113,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https ### 官方 SDK -Node.js SDK 0.5.0、Java SDK 0.5.0、Rust SDK 0.4.0 和还没发布的 Go SDK 说的是版本 `0` 的协议;`main` 上的 Node.js 和 Java SDK 源码另外支持 `litheBuild` `1`(`lithe/build/runEntrypoints`),回答宿主提供的最新版本,随下一次 SDK 发布提供;各 SDK 封装哪些协议见契约的 [Official backend SDK](../contract/v1/README.md#official-backend-sdk) 和各自的 [Node.js](../sdk/node/README.md)、[Java](../sdk/java/README.md)、[Rust](../sdk/rust/README.md)、[Go](../sdk/go/README.md) README。Node.js、Java、Rust 的下载地址在 [Lithe-core-rust 的 Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases);Go SDK 不放 Releases,用 `go get` 按模块标签 `shared/plugins/sdk/go/v<版本>` 获取。新插件优先用 Rust 或 Go SDK,理由见[插件开发总览](../README.md)。 +Node.js SDK 0.5.0、Java SDK 0.5.0、Rust SDK 0.4.0 和还没发布的 Go SDK 说的是版本 `0` 的协议;`main` 上的 Node.js 和 Java SDK 源码另外支持 `litheBuild` `1`(`lithe/build/runEntrypoints`),`main` 上的 Rust SDK 源码新增了 `litheBuild` `0` 和 `1`,都回答宿主提供的最新版本,随下一次 SDK 发布提供;各 SDK 封装哪些协议见契约的 [Official backend SDK](../contract/v1/README.md#official-backend-sdk) 和各自的 [Node.js](../sdk/node/README.md)、[Java](../sdk/java/README.md)、[Rust](../sdk/rust/README.md)、[Go](../sdk/go/README.md) README。Node.js、Java、Rust 的下载地址在 [Lithe-core-rust 的 Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases);Go SDK 不放 Releases,用 `go get` 按模块标签 `shared/plugins/sdk/go/v<版本>` 获取。新插件优先用 Rust 或 Go SDK,理由见[插件开发总览](../README.md)。 --- @@ -228,4 +228,4 @@ The `version` of an exported or called plugin function (1 to 1000) is not a cont ### Official SDKs -Node.js SDK 0.5.0, Java SDK 0.5.0, Rust SDK 0.4.0, and the unreleased Go SDK speak the version `0` protocols; the Node.js and Java SDK sources on `main` also speak `litheBuild` `1` (`lithe/build/runEntrypoints`) and answer the newest version the host offers, which the next SDK release ships; which protocols each SDK wraps is in the contract's [Official backend SDK](../contract/v1/README.md#official-backend-sdk) and in the [Node.js](../sdk/node/README.md), [Java](../sdk/java/README.md), [Rust](../sdk/rust/README.md), and [Go](../sdk/go/README.md) READMEs. Node.js, Java, and Rust downloads are on the [Lithe-core-rust Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases) page; the Go SDK is not on Releases and is fetched with `go get` by module tag `shared/plugins/sdk/go/v`. New plugins should prefer the Rust or Go SDK; see the [plugin overview](../README.md) for why. +Node.js SDK 0.5.0, Java SDK 0.5.0, Rust SDK 0.4.0, and the unreleased Go SDK speak the version `0` protocols; the Node.js and Java SDK sources on `main` also speak `litheBuild` `1` (`lithe/build/runEntrypoints`), and the Rust SDK source on `main` adds `litheBuild` `0` and `1`; each answers the newest version the host offers, which the next SDK release ships; which protocols each SDK wraps is in the contract's [Official backend SDK](../contract/v1/README.md#official-backend-sdk) and in the [Node.js](../sdk/node/README.md), [Java](../sdk/java/README.md), [Rust](../sdk/rust/README.md), and [Go](../sdk/go/README.md) READMEs. Node.js, Java, and Rust downloads are on the [Lithe-core-rust Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases) page; the Go SDK is not on Releases and is fetched with `go get` by module tag `shared/plugins/sdk/go/v`. New plugins should prefer the Rust or Go SDK; see the [plugin overview](../README.md) for why. diff --git a/shared/plugins/reference/domains/build-providers.md b/shared/plugins/reference/domains/build-providers.md index 0d0ab61a..b8754cdf 100644 --- a/shared/plugins/reference/domains/build-providers.md +++ b/shared/plugins/reference/domains/build-providers.md @@ -19,7 +19,7 @@ | API 编号 | [API-29](../api-catalog.md#现在能用的-api):构建、任务、测试、运行准备 | | 权限 | `process.build`;自有进程的提供者加 `languageServer.launch`;原生调试准备加 `debug.launch` | | 激活事件 | `onBuildSystem:`;提供者在第一次由用户操作触发的构建请求时启动 | -| 官方 SDK | [Node.js 0.5.0](../../sdk/node/README.md) 和 [Java 0.5.0](../../sdk/java/README.md) 有 `litheBuild` 的类型化处理器:模型、依赖、任务执行、测试执行、测试发现、运行准备、调试准备;原生配置(`lithe/build/configuration`、`editConfiguration`)没有类型化处理器。[Rust 0.4.0](../../sdk/rust/README.md) 没有构建提供者接口。发布标签 `sdk-node-v0.5.0`、`sdk-java-v0.5.0`、`sdk-rust-v0.4.0`,见[官方 SDK](../capabilities-and-versions.md#官方-sdk) | +| 官方 SDK | [Node.js 0.5.0](../../sdk/node/README.md) 和 [Java 0.5.0](../../sdk/java/README.md) 有 `litheBuild` 的类型化处理器:模型、依赖、任务执行、测试执行、测试发现、运行准备、调试准备;原生配置(`lithe/build/configuration`、`editConfiguration`)没有类型化处理器。[Rust 0.4.0](../../sdk/rust/README.md) 没有构建提供者接口;`main` 上的 Rust SDK 源码有同样的类型化处理器(另含运行入口),随下一次 Rust SDK 发布提供。发布标签 `sdk-node-v0.5.0`、`sdk-java-v0.5.0`、`sdk-rust-v0.4.0`,见[官方 SDK](../capabilities-and-versions.md#官方-sdk) | ### 两种形式 @@ -139,7 +139,7 @@ Some build tools expose their project model only through their own API (the Grad | API IDs | [API-29](../api-catalog.md#apis-usable-now): build, tasks, tests, run preparation | | Permissions | `process.build`; `languageServer.launch` for an own-process provider; `debug.launch` for native debug preparation | | Activation events | `onBuildSystem:`; a provider starts on the first build request, which only a user action sends | -| Official SDKs | [Node.js 0.5.0](../../sdk/node/README.md) and [Java 0.5.0](../../sdk/java/README.md) have typed `litheBuild` handlers: model, dependencies, task execution, test execution, test discovery, run preparation, and debug preparation; native configuration (`lithe/build/configuration`, `editConfiguration`) has no typed handler. [Rust 0.4.0](../../sdk/rust/README.md) has no build-provider interface. Released as `sdk-node-v0.5.0`, `sdk-java-v0.5.0`, and `sdk-rust-v0.4.0`; see [official SDKs](../capabilities-and-versions.md#official-sdks) | +| Official SDKs | [Node.js 0.5.0](../../sdk/node/README.md) and [Java 0.5.0](../../sdk/java/README.md) have typed `litheBuild` handlers: model, dependencies, task execution, test execution, test discovery, run preparation, and debug preparation; native configuration (`lithe/build/configuration`, `editConfiguration`) has no typed handler. [Rust 0.4.0](../../sdk/rust/README.md) has no build-provider interface; the Rust SDK source on `main` has the same typed handlers (plus run entrypoints), shipping in the next Rust SDK release. Released as `sdk-node-v0.5.0`, `sdk-java-v0.5.0`, and `sdk-rust-v0.4.0`; see [official SDKs](../capabilities-and-versions.md#official-sdks) | ### Two forms diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index fa41829c..14886c06 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -33,11 +33,11 @@ required; declare it as the runtime's `minimumVersion`. ## What the Lithe desktop serves -The Lithe desktop declares `backend`, `pluginFunctions`, `buildProviders` and -`buildSystems` (all version 0), so the function, host-service and build -protocols below run there. It does not declare `vcsProviders`, -`keymapImportProviders` or `buildModelInputs`: a plugin whose manifest requires -one of them is not offered for installation there. The Core end-to-end tests +The Lithe desktop declares `backend`, `pluginFunctions`, `buildSystems` and +`vcsProviders` (version 0) and `buildProviders` (versions 0 and 1), so the +function, host-service, build and VCS protocols below run there. It does not +declare `keymapImportProviders` or `buildModelInputs`: a plugin whose manifest +requires one of them is not offered for installation there. The Core end-to-end tests still drive those protocols. Which host services a session may call is reported at run time; see [Host services](#host-services). diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 622d7c6a..98ca7156 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -20,6 +20,9 @@ next to the SDK and changes with it: relayed by Core, with the `Caller` a function called that way sees. - **`litheKeymapImport`**: independently negotiated shortcut import providers reading only explicitly selected source snapshots. +- **`litheBuild`**: [typed build provider requests](#build-providers) for a + build system whose model, dependencies, tasks, tests, or run and debug + preparation come from the plugin's own process. - **`litheToolchains`**: [typed toolchain discovery providers](#toolchain-providers). - **`litheLogging`**: typed diagnostics, required at initialization; see [Logging](#logging). @@ -28,19 +31,105 @@ The SDK owns the wire format, negotiation, cancellation, and error mapping. Your code supplies only handlers. It depends on `serde`, `serde_json` and `base64`, runs every call on a thread of its own, and needs Rust 1.87 or newer. -This SDK has no build provider or VCS provider API; write build providers with -the [Node.js](../node/README.md) or [Java](../java/README.md) SDK, and VCS -providers with the Node.js SDK. +This SDK has no VCS provider API; write VCS providers with the +[Node.js](../node/README.md) SDK. ## What the Lithe desktop serves -The Lithe desktop declares `backend` and `pluginFunctions` (both version 0), so -the function and host-service protocols below run there. It does not declare +The Lithe desktop declares `backend` and `pluginFunctions` (both version 0) and +`buildProviders` (versions 0 and 1), so the function, host-service and build +provider protocols below run there, except that the desktop does not present +build-provider debug preparation yet. It does not declare `keymapImportProviders`: a plugin whose manifest requires it is not offered for installation there, although the Core end-to-end tests still drive the protocol. Which host services a session may call is reported at run time; see [Host services](#host-services). +## Build providers + +A build system whose `model` or `dependencies` source is `provider` names a +[build provider](../../contract/v1/README.md#build-providers). Written with +this SDK, it is a packaged executable with a process of its own: the +language-server process fields plus `executesProjectCode` and `mayUseNetwork`, +under the `languageServer.launch` permission (and `process.build`, which every +build system needs). The host starts one process per +plugin, build system and workspace, and offers `litheBuild` at initialization. +The SDK answers the newest offered version it speaks (`0` or `1`) when at least +one build handler is declared, and does not answer `litheBuild` otherwise: + +```json +"requires": { "buildSystems": 0, "buildProviders": 0 }, +"permissions": ["languageServer.launch", "process.build"], +"buildSystems": [{ + "id": "example", "displayName": "Example", + "detection": { "markers": ["example.toml"] }, + "invocation": { "executables": [{ "kind": "command", "command": "example" }] }, + "model": { "source": "provider" }, + "provider": { + "launch": { "kind": "packaged", "path": "bin/example-build" }, + "executesProjectCode": true, "mayUseNetwork": false + } +}] +``` + +```rust +use lithe_plugin_sdk::{Backend, PluginError}; +use serde_json::json; + +fn main() { + let mut backend = Backend::new("example-build").version(env!("CARGO_PKG_VERSION")); + backend + .build_model(|params, context| { + context.check_cancelled()?; + let root = params["root"].as_str().unwrap_or("."); + Ok(json!({ "buildSystemID": "example", "root": root, "projects": [] })) + }) + .build_prepare_debug(|params, context| { + context.progress("Building", None); + // Build the target and stream the tool's output with context.output(…); + // stop the tool once context.cancellation() fires. + let target = params["target"]["name"].as_str().ok_or_else(|| { + PluginError::new("example.noTarget", "Select a target to debug.") + })?; + Ok(json!({ "program": format!("out/{target}"), "arguments": [], + "workingDirectory": ".", "environment": {} })) + }); + std::process::exit(backend.listen()); +} +``` + +| API | Request | +| --- | --- | +| `build_model(handler)`, `build_dependencies(handler)` | `lithe/build/model`, `lithe/build/dependencies` | +| `build_execute(handler)`, `build_test(handler)` | `lithe/build/execute`, `lithe/build/test`: `{ exitCode, output }` | +| `build_discover_tests(handler)` | `lithe/build/discoverTests` | +| `build_run_entrypoints(handler)` | `lithe/build/runEntrypoints`, routed only when the host negotiated `litheBuild` `1` | +| `build_prepare_run(handler)`, `build_prepare_debug(handler)` | `lithe/build/prepareRun` (a launch plan), `lithe/build/prepareDebug` (exactly `program`, `arguments`, `workingDirectory`, `environment`) | +| `handle.build_version()`, `Initialize::build_version()` | The negotiated `litheBuild` version, or `None` | + +A handler is `Fn(Value, &BuildContext) -> Result` and +runs on a thread of its own. The SDK stamps `format` and `version` on the +model, dependency, test discovery and run entrypoint documents, so a handler +may return the plain document; a document that names another format or +version, or a result of another shape, fails as an internal error before Core +sees it. Core still validates the document's content and workspace +containment. A result must serialize to at most 32 MiB of JSON. +`execute`, `test`, `prepareRun` and `prepareDebug` need the wire `operationID` +Core gives them; a request without it is refused before its handler runs. Only +they report progress: `progress(message, percentage)` cuts the message to +4 KiB and the percentage to 100, and `output(text)` streams the tool's output +in reports of at most 64 KiB, split at character boundaries. The result's +`output` still carries the complete text. Reports from the other requests, +after the request ended, or after cancellation are dropped. A build tool +failure is a result with its exit code. An `Err` fails the request, and for run +and debug preparation starts nothing: a `PluginError` answers a JSON-RPC error +with its message and code, which Core reports in the build's own error category +without forwarding a `pluginErrorCode`; any other error or a panic answers a +generic internal error, and a cancelled request answers `requestCancelled`. +Terminal diagnostics are automatic, as for functions. The SDK has no process runner: stop the build +tool's whole process tree when `cancellation()` fires. `host()` works only when +the host also negotiated plugin functions with the process. + ## Toolchain providers Declare the same provider ID in the manifest's @@ -220,6 +309,7 @@ fallback and no plugin-owned file writer. | `backend.on_contexts_changed(handler)`, `backend.on_host_notification(method, handler)` | Handle `lithe/host/workspace/didChangeContexts` and any other `lithe/host/*` notification a later host adds. | | `handle.host()`, `context.host()` | The [host services](#host-services). `handle.host()` is bound to no call. | | `handle.credentials()`, `context.credentials()` | Shorthand for `host().credentials()`. | +| `backend.build_model(handler)` and the other `build_*` methods | Declare the typed build requests; see [Build providers](#build-providers). | | `PluginError::new(code, message)` | A failure meant for your own UI. | A handler is `Fn(Value, &Context) -> Result`. Its @@ -491,7 +581,8 @@ panics on any other code. blocking driver calls. Lithe has already ended the call when it cancels; the SDK answers `requestCancelled` whatever the handler returns. 5. **No calls back into Lithe's dispatch.** The SDK never sends - `lithe/function/invoke` or `lithe/build/*`; Lithe would refuse them as + `lithe/function/invoke` or a `lithe/build/*` request (it sends only the + `lithe/build/progress` notification); Lithe would refuse them as `plugin.function.recursiveCall`. `Host::request` sends only `lithe/host/*` and refuses anything else as `sdk.host.method`. To call another plugin, use [`host().functions()`](#calling-other-plugins), which diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs index 44a90a45..e40a2bb0 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs @@ -7,6 +7,7 @@ //! Contract: `contract/v1/README.md` ("Plugin backend", "Plugin functions", //! and "Host services"). +use crate::build::{self, BuildContext}; use crate::diagnostics::{Diagnostics, OPERATIONS}; use crate::error::{ cancelled_response, internal_response, response_error, sdk_codes, Cancelled, FunctionError, @@ -17,8 +18,8 @@ use crate::host::{Channel, Credentials, Host, Outcome, Outgoing, WorkspaceContex use crate::panic_boundary::catch as catch_unwind; use crate::protocol::{ bounded_text, error_codes, is_command_id, is_function_id, is_parent_operation_id, methods, - offers, FUNCTIONS_VERSION, KEYMAP_IMPORT_VERSION, LOGGING_VERSION, MAX_FUNCTIONS, - MAX_MESSAGE_BYTES, MAX_RESULT_BYTES, + offers, BUILD_VERSION, FUNCTIONS_VERSION, KEYMAP_IMPORT_VERSION, LOGGING_VERSION, + MAX_BUILD_RESULT_BYTES, MAX_FUNCTIONS, MAX_MESSAGE_BYTES, MAX_RESULT_BYTES, }; use crate::toolchains::{self, ToolchainQuery, ToolchainQueryError, ToolchainQueryResult}; use crate::view::{ViewEvent, ViewResult}; @@ -35,6 +36,7 @@ use std::thread; use std::time::{Duration, Instant}; type Handler = Arc Result + Send + Sync>; +type BuildHandler = Arc Result + Send + Sync>; type InitializeHook = Box Result<(), FunctionError> + Send>; type ShutdownHook = Box; type CommandHandler = @@ -72,6 +74,11 @@ pub(crate) struct State { selected_keymap_providers: BTreeSet, toolchain_providers: BTreeMap, selected_toolchain_providers: BTreeSet, + /// Build-provider handlers, by wire method. + build_handlers: BTreeMap<&'static str, BuildHandler>, + /// The negotiated `litheBuild` version, when the backend has build + /// handlers and the host offered one it speaks. + build_version: Option, pub(crate) logging: bool, pub(crate) logging_ready: bool, pub(crate) early_diagnostics: Vec, @@ -163,6 +170,8 @@ impl Backend { selected_keymap_providers: BTreeSet::new(), toolchain_providers: BTreeMap::new(), selected_toolchain_providers: BTreeSet::new(), + build_handlers: BTreeMap::new(), + build_version: None, logging: false, logging_ready: false, early_diagnostics: Vec::new(), @@ -314,6 +323,92 @@ impl Backend { Ok(self) } + /// Answers `lithe/build/model` with the build model: projects, + /// targets, and their facts. Return the plain document; the SDK adds its + /// `format` (`litheBuildModel`) and `version`. + /// + /// A backend with any build handler negotiates `litheBuild` and becomes a + /// build provider. Each request runs on a thread of its own; a later + /// handler for the same request replaces the earlier one. + pub fn build_model(&mut self, handler: F) -> &mut Self + where + F: Fn(Value, &BuildContext) -> Result + Send + Sync + 'static, + { + self.build(methods::BUILD_MODEL, handler) + } + + /// Answers `lithe/build/dependencies` with a `litheDependencies` document. + pub fn build_dependencies(&mut self, handler: F) -> &mut Self + where + F: Fn(Value, &BuildContext) -> Result + Send + Sync + 'static, + { + self.build(methods::BUILD_DEPENDENCIES, handler) + } + + /// Answers `lithe/build/execute` for a task with `source: provider`: + /// `{ exitCode, output }`, where `output` is the complete tool output. + pub fn build_execute(&mut self, handler: F) -> &mut Self + where + F: Fn(Value, &BuildContext) -> Result + Send + Sync + 'static, + { + self.build(methods::BUILD_EXECUTE, handler) + } + + /// Answers `lithe/build/test` like [`build_execute`](Self::build_execute). + pub fn build_test(&mut self, handler: F) -> &mut Self + where + F: Fn(Value, &BuildContext) -> Result + Send + Sync + 'static, + { + self.build(methods::BUILD_TEST, handler) + } + + /// Answers `lithe/build/discoverTests` with a `litheTestDiscovery` document. + pub fn build_discover_tests(&mut self, handler: F) -> &mut Self + where + F: Fn(Value, &BuildContext) -> Result + Send + Sync + 'static, + { + self.build(methods::BUILD_DISCOVER_TESTS, handler) + } + + /// Answers `lithe/build/runEntrypoints` with a `litheRunEntrypoints` + /// document. Only a host that negotiated `litheBuild` version 1 sends it. + pub fn build_run_entrypoints(&mut self, handler: F) -> &mut Self + where + F: Fn(Value, &BuildContext) -> Result + Send + Sync + 'static, + { + self.build(methods::BUILD_RUN_ENTRYPOINTS, handler) + } + + /// Answers `lithe/build/prepareRun` with a portable launch plan: + /// `{ executable: { kind, value }, arguments, workingDirectory, + /// environment }`. + pub fn build_prepare_run(&mut self, handler: F) -> &mut Self + where + F: Fn(Value, &BuildContext) -> Result + Send + Sync + 'static, + { + self.build(methods::BUILD_PREPARE_RUN, handler) + } + + /// Answers `lithe/build/prepareDebug` with exactly the native target facts + /// `{ program, arguments, workingDirectory, environment }`; the adapter + /// and its DAP arguments come from the manifest. + pub fn build_prepare_debug(&mut self, handler: F) -> &mut Self + where + F: Fn(Value, &BuildContext) -> Result + Send + Sync + 'static, + { + self.build(methods::BUILD_PREPARE_DEBUG, handler) + } + + fn build(&mut self, method: &'static str, handler: F) -> &mut Self + where + F: Fn(Value, &BuildContext) -> Result + Send + Sync + 'static, + { + lock(&self.shared.state) + .build_handlers + .insert(method, Arc::new(handler)); + self + } + /// Runs before the `initialize` answer. A hook may read the host's /// params and add functions; an error refuses `initialize`, mapped like /// a handler's. @@ -499,13 +594,18 @@ impl Backend { Phase::Ready if method == toolchains::METHOD => { Shared::invoke_toolchain(&self.shared, id, params) } - Phase::Ready => self.shared.respond( - &id, - Err(rpc_error( - error_codes::METHOD_NOT_FOUND, - "Unsupported method.", - )), - ), + Phase::Ready => match self.shared.build_handler(method) { + Some(handler) => { + Shared::invoke_build(&self.shared, id, method, params, handler) + } + None => self.shared.respond( + &id, + Err(rpc_error( + error_codes::METHOD_NOT_FOUND, + "Unsupported method.", + )), + ), + }, Phase::Idle | Phase::Listening | Phase::Initializing => self.shared.respond( &id, Err(rpc_error( @@ -622,9 +722,19 @@ impl Backend { FUNCTIONS_VERSION, ) .then_some(FUNCTIONS_VERSION); + // The newest build version the host offers; each one adds to the one before. + let build_offer = params.pointer("/capabilities/experimental/litheBuild"); + let build_version = (!lock(&self.shared.state).build_handlers.is_empty()) + .then(|| { + (0..=BUILD_VERSION) + .rev() + .find(|version| offers(build_offer, *version)) + }) + .flatten(); let mut initialize = Initialize { params, functions_version, + build_version, existing: lock(&self.shared.state).functions.keys().cloned().collect(), added: BTreeMap::new(), }; @@ -644,8 +754,12 @@ impl Backend { let mut state = lock(&self.shared.state); state.functions.extend(initialize.added); state.functions_version = functions_version; + state.build_version = build_version; let mut experimental = Map::new(); experimental.insert("litheLogging".into(), json!({ "version": LOGGING_VERSION })); + if let Some(version) = build_version { + experimental.insert("litheBuild".into(), json!({ "version": version })); + } if let Some(offer) = keymap_offer { if offers(Some(&offer), KEYMAP_IMPORT_VERSION) { if let Some(providers) = offer @@ -930,8 +1044,13 @@ impl Shared { let outcome = catch_unwind(AssertUnwindSafe(|| handler(call_params, &context))); ended.cancel(); // Facts name the wire method Core registered, not the per-provider call id. - let answer = - worker.function_answer(&context, KEYMAP_IMPORT_METHOD, outcome, started); + let answer = worker.function_answer( + &context, + KEYMAP_IMPORT_METHOD, + outcome, + started, + MAX_RESULT_BYTES, + ); lock(&worker.state).incoming.remove(&thread_key); worker.respond(&thread_id, answer); }); @@ -1121,8 +1240,13 @@ impl Shared { let outcome = catch_unwind(AssertUnwindSafe(|| handler(call_params, &context))); context.reporting.store(false, Ordering::SeqCst); ended.cancel(); - let answer = - worker.function_answer(&context, &context.function_id, outcome, started); + let answer = worker.function_answer( + &context, + &context.function_id, + outcome, + started, + MAX_RESULT_BYTES, + ); lock(&worker.state).incoming.remove(&thread_key); worker.respond(&thread_id, answer); }); @@ -1133,6 +1257,109 @@ impl Shared { } } + /// The handler for a build request, when the session negotiated a + /// `litheBuild` version that has it. + fn build_handler(&self, method: &str) -> Option { + let state = lock(&self.state); + let version = state.build_version?; + (version >= build::introduced_in(method)) + .then(|| state.build_handlers.get(method).cloned()) + .flatten() + } + + /// One `lithe/build/*` request, on a thread of its own, answered like a + /// function call: its terminal fact names the wire method. + fn invoke_build( + shared: &Arc, + id: Value, + method: &str, + params: Value, + handler: BuildHandler, + ) { + let progressing = build::reports_progress(method); + if !params.is_object() || (progressing && !params["operationID"].is_string()) { + return shared.respond( + &id, + Err(rpc_error( + error_codes::INVALID_PARAMS, + "A build request needs object params and its wire operationID.", + )), + ); + } + let method = method.to_string(); + let key = request_key(&id); + let cancellation = Cancellation::new(); + lock(&shared.state).incoming.insert( + key.clone(), + Running { + function_id: method.clone(), + cancellation: cancellation.clone(), + }, + ); + let operation_id = if progressing { + params["operationID"].clone() + } else { + Value::Null + }; + let worker = Arc::clone(shared); + let thread_key = key.clone(); + let thread_id = id.clone(); + let thread_method = method.clone(); + let spawned = thread::Builder::new() + .name(format!( + "lithe-build-{}", + method.trim_start_matches("lithe/build/") + )) + .spawn(move || { + let method = thread_method; + let ended = Cancellation::new(); + let diagnostic_operation_id = + crate::diagnostics::request_operation_id(&operation_id, &thread_id); + let context = BuildContext::new( + Context { + shared: Arc::clone(&worker), + function_id: method.clone(), + operation_id, + diagnostic_operation_id, + host: Host::new( + Arc::clone(&worker), + vec![cancellation.clone(), ended.clone()], + ), + cancellation, + workspace_context: None, + caller: None, + reporting: AtomicBool::new(true), + quiet_success: AtomicBool::new(false), + }, + &method, + ); + let started = Instant::now(); + let outcome = + catch_unwind(AssertUnwindSafe(|| handler(params, &context))).map(|answer| { + answer.and_then(|value| { + build::result(&method, value) + .ok_or_else(|| FunctionError::internal("invalid_build_result")) + }) + }); + context.context.reporting.store(false, Ordering::SeqCst); + ended.cancel(); + let answer = worker.function_answer( + &context.context, + &method, + outcome, + started, + MAX_BUILD_RESULT_BYTES, + ); + lock(&worker.state).incoming.remove(&thread_key); + worker.respond(&thread_id, answer); + }); + if spawned.is_err() { + lock(&shared.state).incoming.remove(&key); + shared.failed(&method, "worker_start_failed"); + shared.respond(&id, Err(internal_response())); + } + } + /// The answer to one call. A cancelled call answers as cancelled whatever /// the handler returned, and only failures the host never sees in full /// are logged with a fixed category, without their private contents. @@ -1142,13 +1369,14 @@ impl Shared { function: &str, outcome: Result, Box>, started: Instant, + limit: usize, ) -> Answer { let cancelled = context.cancellation.is_cancelled(); match outcome { _ if cancelled => Err(cancelled_response()), Ok(Ok(value)) => { let size = serde_json::to_vec(&value).map_or(usize::MAX, |bytes| bytes.len()); - if size > MAX_RESULT_BYTES { + if size > limit { context.diagnostics().terminal( function, Some(&FunctionError::internal("result_limit")), @@ -1227,6 +1455,7 @@ fn failure_kind(error: &FunctionError) -> &'static str { pub struct Initialize { params: Value, functions_version: Option, + build_version: Option, existing: Vec, added: BTreeMap, } @@ -1243,6 +1472,12 @@ impl Initialize { self.functions_version } + /// The `litheBuild` version the backend will answer, or `None` when it + /// has no build handlers or the host offered no version it speaks. + pub fn build_version(&self) -> Option { + self.build_version + } + /// The `rootUri` as a path. For a plugin backend this is the plugin's /// `${stateDir}`, also the working directory. pub fn root_path(&self) -> Option { @@ -1306,15 +1541,15 @@ fn file_uri_path(uri: &str) -> Option { /// One running function call. pub struct Context { - shared: Arc, + pub(crate) shared: Arc, function_id: String, - operation_id: Value, + pub(crate) operation_id: Value, diagnostic_operation_id: Option, cancellation: Cancellation, host: Host, workspace_context: Option, caller: Option, - reporting: AtomicBool, + pub(crate) reporting: AtomicBool, quiet_success: AtomicBool, } @@ -1571,6 +1806,13 @@ impl BackendHandle { self.shared.functions_version() } + /// The negotiated `litheBuild` version; `None` before `initialize`, when + /// the backend has no build handlers, or when the host offered no + /// version it speaks. + pub fn build_version(&self) -> Option { + lock(&self.shared.state).build_version + } + /// IDs of the functions the backend currently serves, sorted. pub fn function_ids(&self) -> Vec { lock(&self.shared.state).functions.keys().cloned().collect() diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/build.rs b/shared/plugins/sdk/rust/plugin-sdk/src/build.rs new file mode 100644 index 00000000..d6fe4368 --- /dev/null +++ b/shared/plugins/sdk/rust/plugin-sdk/src/build.rs @@ -0,0 +1,290 @@ +//! Build providers: the typed `lithe/build/*` requests a plugin answers for +//! its build system, negotiated as `litheBuild` in `initialize`. The SDK +//! negotiates the version, checks each request's identity, sends progress, +//! and checks the shape of each result; the plugin supplies the build +//! semantics. +//! +//! Contract: `contract/v1/README.md` ("Build providers", "Provider task +//! execution", "Provider test execution", "Run preparation", "Native debug +//! preparation", and "Run entrypoints"). + +use crate::backend::{BackendHandle, Cancellation, Context}; +use crate::diagnostics::Diagnostics; +use crate::error::Cancelled; +use crate::host::Host; +use crate::protocol::{bounded_text, methods, MAX_BUILD_MESSAGE_BYTES, MAX_BUILD_OUTPUT_BYTES}; +use serde_json::{json, Value}; +use std::sync::atomic::Ordering; + +/// The `version` every build result document carries. +const DOCUMENT_VERSION: u64 = 0; + +/// Requests that run the build tool. Core gives each a wire `operationID`, +/// and only they report `lithe/build/progress`. +pub(crate) fn reports_progress(method: &str) -> bool { + matches!( + method, + methods::BUILD_EXECUTE + | methods::BUILD_TEST + | methods::BUILD_PREPARE_RUN + | methods::BUILD_PREPARE_DEBUG + ) +} + +/// The `litheBuild` version that introduced `method`; a session that +/// negotiated an older one does not route it. +pub(crate) fn introduced_in(method: &str) -> u64 { + u64::from(method == methods::BUILD_RUN_ENTRYPOINTS) +} + +/// The canonical format of a typed result document. +fn document_format(method: &str) -> Option<&'static str> { + match method { + methods::BUILD_MODEL => Some("litheBuildModel"), + methods::BUILD_DEPENDENCIES => Some("litheDependencies"), + methods::BUILD_DISCOVER_TESTS => Some("litheTestDiscovery"), + methods::BUILD_RUN_ENTRYPOINTS => Some("litheRunEntrypoints"), + _ => None, + } +} + +/// The result the SDK answers for a handler's `value`, or `None` when its +/// shape is not the one the request needs. A document gets its canonical +/// `format` and `version`, so a handler can return the plain document. Core +/// would refuse any other shape as `plugin.build.invalidResult` or +/// `plugin.build.invalidOutput`, so the SDK fails the call with a controlled +/// diagnostic instead. Workspace containment and domain facts stay with Core +/// and the provider; the size limit is checked with the answer. +pub(crate) fn result(method: &str, value: Value) -> Option { + let Value::Object(mut fields) = value else { + return None; + }; + if let Some(format) = document_format(method) { + if fields + .get("format") + .is_some_and(|value| value.as_str() != Some(format)) + || fields + .get("version") + .is_some_and(|value| value.as_u64() != Some(DOCUMENT_VERSION)) + { + return None; + } + fields.insert("format".into(), json!(format)); + fields.insert("version".into(), json!(DOCUMENT_VERSION)); + } + let strings = |value: Option<&Value>| { + value + .and_then(Value::as_array) + .is_some_and(|values| values.iter().all(Value::is_string)) + }; + let environment = |value: Option<&Value>| { + value + .and_then(Value::as_object) + .is_some_and(|values| values.values().all(Value::is_string)) + }; + let valid = match method { + methods::BUILD_EXECUTE | methods::BUILD_TEST => { + fields + .get("exitCode") + .and_then(Value::as_i64) + .is_some_and(|code| i32::try_from(code).is_ok()) + && fields.get("output").is_some_and(Value::is_string) + } + methods::BUILD_PREPARE_RUN => { + fields.get("executable").is_some_and(|executable| { + matches!( + executable["kind"].as_str(), + Some("toolchain") | Some("command") + ) && executable["value"].is_string() + }) && fields.get("workingDirectory").is_some_and(Value::is_string) + && strings(fields.get("arguments")) + && environment(fields.get("environment")) + } + // Native target facts only: the adapter and its DAP arguments come + // from the manifest. + methods::BUILD_PREPARE_DEBUG => { + fields.get("program").is_some_and(Value::is_string) + && fields.get("workingDirectory").is_some_and(Value::is_string) + && strings(fields.get("arguments")) + && environment(fields.get("environment")) + && fields.keys().all(|key| { + ["program", "arguments", "workingDirectory", "environment"] + .contains(&key.as_str()) + }) + } + _ => true, + }; + valid.then_some(Value::Object(fields)) +} + +/// One running `lithe/build/*` request. +/// +/// Every request runs on a thread of its own, so a handler may block on the +/// build tool; it should stop the tool and return promptly once +/// [`cancellation`](Self::cancellation) fires. +pub struct BuildContext { + pub(crate) context: Context, + reports_progress: bool, +} + +impl BuildContext { + pub(crate) fn new(context: Context, method: &str) -> Self { + Self { + context, + reports_progress: reports_progress(method), + } + } + + /// The wire method, such as `lithe/build/model`. + pub fn method(&self) -> &str { + self.context.function_id() + } + + /// The Core-assigned wire `operationID` of a request that runs the build + /// tool (`execute`, `test`, `prepareRun`, `prepareDebug`); the SDK echoes + /// it in every progress report. + pub fn operation_id(&self) -> Option<&str> { + self.context.operation_id.as_str() + } + + /// Fires when the host cancels the request or shuts the backend down. + /// Core has already ended the request by then. + pub fn cancellation(&self) -> &Cancellation { + self.context.cancellation() + } + + /// `Err(Cancelled)` once the request is cancelled, for use with `?`. + pub fn check_cancelled(&self) -> Result<(), Cancelled> { + self.context.check_cancelled() + } + + /// Structured diagnostics correlated with the request's operation. + pub fn diagnostics(&self) -> Diagnostics { + self.context.diagnostics() + } + + /// Omits only this request's successful terminal fact; failures remain + /// visible. + pub fn suppress_success_diagnostics(&self) { + self.context.suppress_success_diagnostics(); + } + + /// Reports what the build is doing; the host shows the latest report. + /// `message` is cut to 4 KiB and `percentage` to 100. + /// + /// Only requests that run the build tool report progress; for the others + /// (`model`, `dependencies`, `discoverTests`, `runEntrypoints`), and after + /// the request ended or was cancelled, a report is dropped. + pub fn progress(&self, message: &str, percentage: Option) { + let mut report = json!({ "message": bounded_text(message, MAX_BUILD_MESSAGE_BYTES) }); + if let Some(percentage) = percentage { + report["percentage"] = json!(percentage.min(100)); + } + self.report(report); + } + + /// Streams build tool output to the host's console as it arrives. Text + /// longer than one report's 64 KiB is sent in several reports, split at + /// character boundaries. The final result's `output` must still carry the + /// complete text: the host decodes diagnostics from it without showing it + /// twice. Dropped like [`progress`](Self::progress). + pub fn output(&self, text: &str) { + let mut rest = text; + while !rest.is_empty() { + let chunk = bounded_text(rest, MAX_BUILD_OUTPUT_BYTES); + rest = &rest[chunk.len()..]; + self.report(json!({ "output": chunk })); + } + } + + fn report(&self, mut report: Value) { + if !self.reports_progress + || !self.context.reporting.load(Ordering::SeqCst) + || self.context.cancellation().is_cancelled() + { + return; + } + report["operationID"] = self.context.operation_id.clone(); + self.context.shared.write( + &json!({ "jsonrpc": "2.0", "method": methods::BUILD_PROGRESS, "params": report }), + ); + } + + /// Host services for this request, bound to its cancellation. They need + /// a host that also negotiated plugin functions with this process. + pub fn host(&self) -> &Host { + self.context.host() + } + + pub fn backend(&self) -> BackendHandle { + self.context.backend() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn documents_get_their_canonical_format_and_version() { + let model = result(methods::BUILD_MODEL, json!({ "projects": [] })).unwrap(); + assert_eq!(model["format"], "litheBuildModel"); + assert_eq!(model["version"], 0); + let stamped = json!({ "format": "litheRunEntrypoints", "version": 0, "entrypoints": [] }); + assert_eq!( + result(methods::BUILD_RUN_ENTRYPOINTS, stamped.clone()), + Some(stamped) + ); + assert!(result( + methods::BUILD_MODEL, + json!({ "format": "litheDependencies" }) + ) + .is_none()); + assert!(result(methods::BUILD_DEPENDENCIES, json!({ "version": 1 })).is_none()); + assert!(result(methods::BUILD_DISCOVER_TESTS, json!([])).is_none()); + } + + #[test] + fn task_results_need_an_int32_exit_code_and_text_output() { + let ok = json!({ "exitCode": -1, "output": "" }); + assert_eq!(result(methods::BUILD_EXECUTE, ok.clone()), Some(ok)); + for invalid in [ + json!({ "exitCode": 2_147_483_648_i64, "output": "" }), + json!({ "exitCode": 1.5, "output": "" }), + json!({ "exitCode": 0 }), + json!({ "exitCode": 0, "output": ["text"] }), + ] { + assert!( + result(methods::BUILD_TEST, invalid.clone()).is_none(), + "{invalid}" + ); + } + } + + #[test] + fn launch_plans_and_debug_targets_need_their_portable_fields() { + let plan = json!({ "executable": { "kind": "command", "value": "app" }, + "arguments": ["a"], "workingDirectory": "app", "environment": { "A": "1" } }); + assert!(result(methods::BUILD_PREPARE_RUN, plan.clone()).is_some()); + let mut other = plan.clone(); + other["executable"]["kind"] = json!("shell"); + assert!(result(methods::BUILD_PREPARE_RUN, other).is_none()); + let mut environment = plan; + environment["environment"]["A"] = json!(1); + assert!(result(methods::BUILD_PREPARE_RUN, environment).is_none()); + + let target = json!({ "program": "app/bin", "arguments": [], "workingDirectory": "app", "environment": {} }); + assert!(result(methods::BUILD_PREPARE_DEBUG, target.clone()).is_some()); + let mut adapter = target; + adapter["adapter"] = json!("native"); + assert!(result(methods::BUILD_PREPARE_DEBUG, adapter).is_none()); + } + + #[test] + fn only_tool_runs_report_progress() { + assert!(reports_progress(methods::BUILD_PREPARE_DEBUG)); + assert!(!reports_progress(methods::BUILD_MODEL)); + assert_eq!(introduced_in(methods::BUILD_RUN_ENTRYPOINTS), 1); + assert_eq!(introduced_in(methods::BUILD_MODEL), 0); + } +} diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs index 8239f983..78b896e1 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs @@ -16,7 +16,10 @@ //! calls to the functions other plugins export through Core's relay //! ([`Functions`]) with the [`Caller`] of a function called that way; //! - **`litheKeymapImport`**: shortcut import providers; -//! - **`litheToolchains`**: [toolchain discovery providers](toolchains). +//! - **`litheToolchains`**: [toolchain discovery providers](toolchains); +//! - **`litheBuild`**: a build provider's typed `lithe/build/*` requests, +//! declared with [`Backend::build_model`] and its siblings and answered +//! with a [`BuildContext`] for progress, output, and cancellation. //! //! The SDK requires `litheLogging` at initialization. //! @@ -31,6 +34,7 @@ //! See [`Backend`] for a minimal backend. mod backend; +mod build; mod diagnostics; mod error; mod framing; @@ -45,6 +49,7 @@ pub use backend::{ Backend, BackendHandle, Caller, Cancellation, Context, Initialize, KeymapImportRequest, KeymapSourceFile, }; +pub use build::BuildContext; pub use diagnostics::Diagnostics; pub use error::{ sdk_codes, Cancelled, FunctionError, PluginError, SdkError, HOST_ERROR_CODES, RELAY_ERROR_CODES, diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs index caa2b24e..78ef2599 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs @@ -14,6 +14,10 @@ pub const FUNCTIONS_VERSION: u64 = 0; pub const LOGGING_VERSION: u64 = 0; /// The `litheKeymapImport` version this SDK answers. pub const KEYMAP_IMPORT_VERSION: u64 = 0; +/// The newest `litheBuild` version this SDK answers. The protocol is a +/// version of `buildProviders`: version 1 adds `lithe/build/runEntrypoints` +/// and changes nothing of version 0. +pub const BUILD_VERSION: u64 = 1; /// Whether an `initialize` offer, `{ "versions": [...] }`, lists `version`. pub(crate) fn offers(offer: Option<&Value>, version: u64) -> bool { @@ -73,6 +77,15 @@ pub(crate) mod methods { pub const COMMAND_DID_RUN: &str = "lithe/host/commands/didRun"; pub const FUNCTIONS_PROVIDERS: &str = "lithe/host/functions/providers"; pub const FUNCTIONS_INVOKE: &str = "lithe/host/functions/invoke"; + pub const BUILD_MODEL: &str = "lithe/build/model"; + pub const BUILD_DEPENDENCIES: &str = "lithe/build/dependencies"; + pub const BUILD_EXECUTE: &str = "lithe/build/execute"; + pub const BUILD_TEST: &str = "lithe/build/test"; + pub const BUILD_DISCOVER_TESTS: &str = "lithe/build/discoverTests"; + pub const BUILD_RUN_ENTRYPOINTS: &str = "lithe/build/runEntrypoints"; + pub const BUILD_PREPARE_RUN: &str = "lithe/build/prepareRun"; + pub const BUILD_PREPARE_DEBUG: &str = "lithe/build/prepareDebug"; + pub const BUILD_PROGRESS: &str = "lithe/build/progress"; } /// JSON-RPC and LSP error codes the SDK answers with. @@ -92,6 +105,12 @@ const MAX_FUNCTION_ID_BYTES: usize = 128; const MAX_PLUGIN_ERROR_CODE_BYTES: usize = 64; pub(crate) const MAX_MESSAGE_BYTES: usize = 1024; pub(crate) const MAX_RESULT_BYTES: usize = 1 << 20; +/// A build result document, including the complete `output` of a task or test. +pub(crate) const MAX_BUILD_RESULT_BYTES: usize = 32 << 20; +/// The `message` of one `lithe/build/progress` report. +pub(crate) const MAX_BUILD_MESSAGE_BYTES: usize = 4 * 1024; +/// The `output` of one `lithe/build/progress` report. +pub(crate) const MAX_BUILD_OUTPUT_BYTES: usize = 64 * 1024; const MAX_CREDENTIAL_KEY_BYTES: usize = 128; pub(crate) const MAX_CREDENTIAL_SECRET_BYTES: usize = 16 * 1024; /// Host requests a backend may have unanswered at once; later ones wait. @@ -192,6 +211,11 @@ mod tests { assert_eq!(KEYMAP_IMPORT_VERSION, 0); } + #[test] + fn the_build_protocol_follows_build_providers_one() { + assert_eq!(BUILD_VERSION, 1); + } + #[test] fn an_offer_lists_the_version_exactly() { use serde_json::json; diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/build.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/build.rs new file mode 100644 index 00000000..04c922d3 --- /dev/null +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/build.rs @@ -0,0 +1,327 @@ +//! Exercises build-provider requests over the SDK's actual framed transport. + +mod common; + +use common::Host; +use lithe_plugin_sdk::{Backend, PluginError}; +use serde_json::{json, Value}; +use std::sync::mpsc; +use std::time::Duration; + +fn initialize(host: &mut Host, build: Option) -> Value { + let mut experimental = json!({ "litheLogging": { "versions": [0] } }); + if let Some(versions) = build { + experimental["litheBuild"] = json!({ "versions": versions }); + } + host.request( + 0, + "initialize", + json!({ "rootUri": "file:///tmp/workspace", "capabilities": { "experimental": experimental } }), + ); + host.answer(0).0["result"]["capabilities"]["experimental"].clone() +} + +fn model_backend() -> Backend { + let mut backend = Backend::new("test-build"); + backend + .build_model(|_, _| Ok(json!({ "root": ".", "projects": [] }))) + .build_run_entrypoints(|_, _| Ok(json!({ "entrypoints": [] }))); + backend +} + +fn finish(mut host: Host) { + host.request("shutdown", "shutdown", Value::Null); + assert_eq!(host.answer("shutdown").0["result"], Value::Null); + host.notify("exit", Value::Null); + assert_eq!(host.exit_code(), 0); +} + +fn progress(frames: &[Value]) -> Vec<&Value> { + frames + .iter() + .filter(|frame| frame["method"] == "lithe/build/progress") + .map(|frame| &frame["params"]) + .collect() +} + +#[test] +fn negotiates_the_newest_offered_build_version() { + let mut host = Host::start(model_backend()); + let experimental = initialize(&mut host, Some(json!([0, 1, 7]))); + assert_eq!(experimental["litheBuild"], json!({ "version": 1 })); + host.request(1, "lithe/build/runEntrypoints", json!({ "root": "." })); + assert_eq!( + host.answer(1).0["result"], + json!({ "format": "litheRunEntrypoints", "version": 0, "entrypoints": [] }) + ); + finish(host); +} + +#[test] +fn a_version_zero_host_does_not_route_run_entrypoints() { + let mut host = Host::start(model_backend()); + assert_eq!( + initialize(&mut host, Some(json!([0])))["litheBuild"], + json!({ "version": 0 }) + ); + host.request(1, "lithe/build/model", json!({ "root": "." })); + let (answer, facts) = host.answer(1); + assert_eq!( + answer["result"], + json!({ "format": "litheBuildModel", "version": 0, "root": ".", "projects": [] }) + ); + assert!(facts + .iter() + .any(|fact| fact["params"]["kind"] == "operationFinished" + && fact["params"]["operation"] == "lithe/build/model")); + host.request(2, "lithe/build/runEntrypoints", json!({ "root": "." })); + assert_eq!(host.answer(2).0["error"]["code"], -32601); + finish(host); +} + +#[test] +fn no_build_provider_without_handlers_or_an_offer() { + let mut host = Host::start(Backend::new("test-build")); + assert!(initialize(&mut host, Some(json!([0, 1]))) + .get("litheBuild") + .is_none()); + host.request(1, "lithe/build/model", json!({ "root": "." })); + assert_eq!(host.answer(1).0["error"]["code"], -32601); + finish(host); + + let mut host = Host::start(model_backend()); + assert!(initialize(&mut host, None).get("litheBuild").is_none()); + host.request(1, "lithe/build/model", json!({ "root": "." })); + assert_eq!(host.answer(1).0["error"]["code"], -32601); + finish(host); +} + +#[test] +fn a_handler_without_its_request_declared_is_not_routed() { + let mut host = Host::start(model_backend()); + initialize(&mut host, Some(json!([1]))); + host.request(1, "lithe/build/dependencies", json!({ "root": "." })); + assert_eq!(host.answer(1).0["error"]["code"], -32601); + finish(host); +} + +#[test] +fn tool_runs_need_object_params_and_their_operation_id() { + let mut backend = Backend::new("test-build"); + backend.build_execute(|_, _| panic!("an invalid request ran")); + let mut host = Host::start(backend); + initialize(&mut host, Some(json!([1]))); + host.request(1, "lithe/build/execute", json!({ "root": "." })); + host.request(2, "lithe/build/execute", json!(["root"])); + for id in [1, 2] { + let error = host.answer(id).0["error"].clone(); + assert_eq!(error["code"], -32602); + assert_eq!( + error["message"], + "A build request needs object params and its wire operationID." + ); + } + finish(host); +} + +#[test] +fn reports_progress_and_streams_output_until_the_request_ends() { + let (sender, receiver) = mpsc::channel(); + let mut backend = Backend::new("test-build"); + backend.build_execute(move |params, context| { + assert_eq!(params["task"], "build"); + assert_eq!(context.method(), "lithe/build/execute"); + assert_eq!(context.operation_id(), Some("op-build")); + context.progress(&"m".repeat(5000), Some(250)); + let text = format!("{}é{}", "a".repeat(65_535), "b".repeat(10)); + context.output(&text); + context.output(""); + let _ = sender.send(context.backend()); + Ok(json!({ "exitCode": 0, "output": text })) + }); + let mut host = Host::start(backend); + initialize(&mut host, Some(json!([1]))); + host.request( + 1, + "lithe/build/execute", + json!({ "operationID": "op-build", "root": ".", "task": "build" }), + ); + let (answer, before) = host.answer(1); + assert_eq!(answer["result"]["exitCode"], 0); + let reports = progress(&before); + assert_eq!(reports.len(), 3, "{reports:?}"); + assert!(reports + .iter() + .all(|report| report["operationID"] == "op-build")); + assert_eq!(reports[0]["message"].as_str().unwrap().len(), 4096); + assert_eq!(reports[0]["percentage"], 100); + // The 2-byte `é` straddles the 64 KiB boundary, so the first chunk stops before it. + assert_eq!(reports[1]["output"], "a".repeat(65_535)); + assert_eq!(reports[2]["output"], format!("é{}", "b".repeat(10))); + let handle = receiver.recv_timeout(Duration::from_secs(10)).unwrap(); + assert_eq!(handle.build_version(), Some(1)); + finish(host); +} + +#[test] +fn requests_that_only_read_the_build_send_no_progress() { + let mut backend = Backend::new("test-build"); + backend.build_model(|_, context| { + assert_eq!(context.operation_id(), None); + context.progress("reading", Some(10)); + context.output("text"); + Ok(json!({ "root": ".", "projects": [] })) + }); + let mut host = Host::start(backend); + initialize(&mut host, Some(json!([0]))); + host.request( + 1, + "lithe/build/model", + json!({ "root": ".", "operationID": "op-model" }), + ); + let (answer, before) = host.answer(1); + assert!(answer.get("result").is_some(), "{answer}"); + assert!(progress(&before).is_empty(), "{before:?}"); + finish(host); +} + +#[test] +fn results_of_another_shape_fail_as_internal_errors() { + let mut backend = Backend::new("test-build"); + backend + .build_model(|_, _| Ok(json!({ "format": "litheDependencies", "projects": [] }))) + .build_prepare_debug(|_, _| { + Ok(json!({ + "program": "target/debug/app", "arguments": [], "workingDirectory": ".", + "environment": {}, "adapter": "native" + })) + }) + .build_test(|_, _| Ok(json!({ "exitCode": 0 }))); + let mut host = Host::start(backend); + initialize(&mut host, Some(json!([1]))); + host.request(1, "lithe/build/model", json!({ "root": "." })); + host.request( + 2, + "lithe/build/prepareDebug", + json!({ "operationID": "op-2", "root": "." }), + ); + host.request( + 3, + "lithe/build/test", + json!({ "operationID": "op-3", "root": "." }), + ); + // Each request runs on a thread of its own, so the answers come in any order. + let mut failures = Vec::new(); + let mut answered = 0; + while answered < 3 { + let frame = host.next(); + if frame.get("method").is_none() { + assert_eq!(frame["error"]["code"], -32603, "{frame}"); + answered += 1; + } + failures.push(frame); + } + let facts: Vec<_> = failures + .iter() + .filter(|frame| frame["method"] == "lithe/log") + .map(|frame| frame["params"].clone()) + .collect(); + for operation in [ + "lithe/build/model", + "lithe/build/prepareDebug", + "lithe/build/test", + ] { + assert!( + facts.iter().any(|fact| fact["operation"] == operation + && fact["kind"] == "operationFailed" + && fact["code"] == "internal_error"), + "{operation}: {facts:?}" + ); + } + finish(host); +} + +#[test] +fn plugin_errors_reach_the_host_with_their_code() { + let mut backend = Backend::new("test-build"); + backend.build_prepare_run(|_, _| { + Err(PluginError::new("cargo.unavailable", "Cargo was not found.").into()) + }); + let mut host = Host::start(backend); + initialize(&mut host, Some(json!([1]))); + host.request( + 1, + "lithe/build/prepareRun", + json!({ "operationID": "op-run", "root": "." }), + ); + let (answer, before) = host.answer(1); + assert_eq!(answer["error"]["code"], -32000); + assert_eq!(answer["error"]["data"]["code"], "cargo.unavailable"); + assert!(before.iter().any( + |frame| frame["params"]["operation"] == "lithe/build/prepareRun" + && frame["params"]["code"] == "cargo.unavailable" + && frame["params"]["operationId"] == "op-run" + )); + finish(host); +} + +#[test] +fn a_cancelled_request_answers_cancelled_and_reports_nothing_more() { + let (started, running) = mpsc::channel(); + let mut backend = Backend::new("test-build"); + backend.build_execute(move |_, context| { + let _ = started.send(()); + assert!(context.cancellation().wait_timeout(Duration::from_secs(10))); + context.progress("after cancel", None); + context.output("after cancel"); + Ok(json!({ "exitCode": 0, "output": "" })) + }); + let mut host = Host::start(backend); + initialize(&mut host, Some(json!([1]))); + host.request( + 7, + "lithe/build/execute", + json!({ "operationID": "op-7", "root": "." }), + ); + running.recv_timeout(Duration::from_secs(10)).unwrap(); + host.notify("$/cancelRequest", json!({ "id": 7 })); + let (answer, before) = host.answer(7); + assert_eq!(answer["error"]["code"], -32800); + assert!(progress(&before).is_empty(), "{before:?}"); + finish(host); +} + +#[test] +fn shutdown_cancels_running_build_requests() { + let (started, running) = mpsc::channel(); + let mut backend = Backend::new("test-build"); + backend.build_prepare_debug(move |_, context| { + let _ = started.send(()); + context.cancellation().wait_timeout(Duration::from_secs(10)); + context.check_cancelled()?; + Ok(json!({})) + }); + let mut host = Host::start(backend); + initialize(&mut host, Some(json!([1]))); + host.request( + 1, + "lithe/build/prepareDebug", + json!({ "operationID": "op-1", "root": "." }), + ); + running.recv_timeout(Duration::from_secs(10)).unwrap(); + host.request("shutdown", "shutdown", Value::Null); + // `shutdown` answers once it cancelled the request, which may answer later. + let (mut call, mut shutdown) = (None, None); + while call.is_none() || shutdown.is_none() { + let frame = host.next(); + if frame["id"] == 1 { + call = Some(frame); + } else if frame["id"] == "shutdown" { + shutdown = Some(frame); + } + } + assert_eq!(call.unwrap()["error"]["code"], -32800); + assert_eq!(shutdown.unwrap()["result"], Value::Null); + host.notify("exit", Value::Null); + assert_eq!(host.exit_code(), 0); +} From b0981852c5212557f955cee7ab28d56b3faa2ef8 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 19 Nov 2026 18:52:42 +0800 Subject: [PATCH 2/2] =?UTF-8?q?docs(plugins):=20=E6=8C=89=E6=A1=8C?= =?UTF-8?q?=E9=9D=A2=E7=AB=AF=E7=8E=B0=E7=8A=B6=E6=9B=B4=E6=AD=A3=E5=AE=BF?= =?UTF-8?q?=E4=B8=BB=E6=94=AF=E6=8C=81=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 桌面端自 Lithe-IDEA #1837 起在构建窗口和标题栏呈现构建提供者的调试准备, #2175 起呈现语言服务器的代码操作、签名帮助和内嵌提示,几页文档仍写尚未呈现。 同时更正 buildProviders 的版本(0 和 1)、构建提供者的运行准备与测试已呈现, 并在调试适配器的桌面端说明里补上 tcpAnnounced。 --- shared/plugins/guides/build-tool-integration.md | 10 ++++------ shared/plugins/guides/native-build-workflows.md | 8 ++++---- shared/plugins/reference/capabilities-and-versions.md | 8 ++++---- shared/plugins/reference/domains/build-providers.md | 8 ++++---- shared/plugins/reference/domains/build-systems.md | 4 ++-- shared/plugins/reference/domains/debug-adapters.md | 4 ++-- shared/plugins/sdk/java/README.md | 6 +++--- shared/plugins/sdk/rust/README.md | 3 +-- 8 files changed, 24 insertions(+), 27 deletions(-) diff --git a/shared/plugins/guides/build-tool-integration.md b/shared/plugins/guides/build-tool-integration.md index b27e9a3f..f91758c1 100644 --- a/shared/plugins/guides/build-tool-integration.md +++ b/shared/plugins/guides/build-tool-integration.md @@ -11,8 +11,8 @@ LSP 服务器负责语言分析,构建工具负责项目导入、编译、依 > **宿主支持。** 目前唯一的宿主是 Lithe 桌面端,下文的“宿主”都指它。它声明 `buildSystems`、`buildProviders` 和 `debugAdapters`, > **不声明 `executionProviders`**:`requires` 里有它的插件(第 2、3 节的运行和测试声明)不会被提供安装,所以这两节的清单按契约是有效的, > 但不能在桌面端安装和运行。要在桌面端运行固定命令或构建任务,用第 5 节的构建系统。 -> 桌面端的 Build 窗口检测构建实例、加载提供者模型、解析可执行文件候选并运行命令任务和提供者任务;构建提供者的运行准备、测试、 -> 调试准备、模型输入、原生配置、内联测试报告、运行时调试,以及构建系统的实例选项和任务准备尚未呈现。 +> 桌面端的 Build 窗口检测构建实例、加载提供者模型、解析可执行文件候选、运行命令任务和提供者任务、准备应用启动和原生程序调试, +> 并发现和运行提供者测试;构建提供者的模型输入、原生配置、内联测试报告、运行时调试,以及构建系统的实例选项和任务准备尚未呈现。 > 完整声明和说明见 [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go) > 中 `Declared()` 上方的注释,各能力的对照见[能力与协议版本对照](../reference/capabilities-and-versions.md)。 > 对本文有疑问,请到 [Lithe-core-rust 的 Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues) 反馈。 @@ -156,7 +156,6 @@ Core 校验声明、检测实例、解码模型、展开命令行;桌面端执 [构建提供者](../reference/domains/build-providers.md),用 `litheBuild` 协议回答模型、任务、测试和运行准备请求。 字段见[构建系统](../reference/domains/build-systems.md); 运行原生程序、调试准备和终端见[原生构建工作流](native-build-workflows.md)。 -注意桌面端目前不呈现构建提供者的测试、运行准备和调试准备,见开头的宿主支持。 可以参考实现的插件: @@ -229,8 +228,8 @@ Finish the [LSP plugin lifecycle tutorial](lsp-plugin-lifecycle.md) first, then > and **does not declare `executionProviders`**: a plugin whose `requires` lists it (the run and test declarations of sections 2 and 3) is not offered for install, > so the manifests in those two sections are valid under the contract but cannot be installed or run on the desktop. > To run a fixed command or a build task on the desktop, use the build system of section 5. -> The desktop's Build window detects build instances, loads provider models, resolves executable candidates, and runs command tasks and provider tasks; build-provider run preparation, tests, -> debug preparation, model inputs, native configuration, inline test reports, runtime debugging, and build-system instance options and task preparations are not presented yet. +> The desktop's Build window detects build instances, loads provider models, resolves executable candidates, runs command and provider tasks, prepares application launches and native program debugging, +> and discovers and runs provider tests; build-provider model inputs, native configuration, inline test reports, runtime debugging, and build-system instance options and task preparations are not presented yet. > The full declarations and notes are in the comment above `Declared()` in [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go); > for a per-capability comparison see the [capability and protocol versions](../reference/capabilities-and-versions.md). > Questions about this guide go to [Lithe-core-rust Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues). @@ -384,7 +383,6 @@ When only a program can compute the model (the Gradle Tooling API, for example), model, task, test, and run-preparation requests over the `litheBuild` protocol. For fields see [build systems](../reference/domains/build-systems.md); for running native programs, debug preparation, and terminals see [native build workflows](native-build-workflows.md). -Note that the desktop does not yet present build-provider tests, run preparation, or debug preparation; see the host support note at the top. Plugins whose implementation you can read: diff --git a/shared/plugins/guides/native-build-workflows.md b/shared/plugins/guides/native-build-workflows.md index 2c062b45..6dd2b78d 100644 --- a/shared/plugins/guides/native-build-workflows.md +++ b/shared/plugins/guides/native-build-workflows.md @@ -8,8 +8,8 @@ 这些入口都属于 `buildProviders`(版本 `0`):清单要求 `requires.buildProviders: 0`,进程协议 `litheBuild` 的版本就是 `buildProviders` 的版本。Node.js SDK 0.5.0 和 Java SDK 0.5.0 实现了全部入口;`main` 上的 Rust SDK 源码也实现了全部入口,随下一次 Rust SDK 发布提供(0.4.0 没有);Go SDK 没有构建提供者接口。能力定义见[构建提供者](../reference/domains/build-providers.md),字段和错误码以[契约](../contract/v1/README.md#build-providers)为准。 -> **宿主支持。** Lithe 桌面端声明 `buildSystems` 和 `buildProviders`(版本 `0` 和 `1`):构建窗口发现构建实例、加载提供者模型、解析可执行文件候选、运行命令任务和提供者任务、准备应用启动,并发现和运行提供者测试;“运行当前文件”向版本 `1` 的提供者询问文件里的入口。构建提供者的调试准备、model inputs、原生配置、内联测试报告和运行时调试,桌面端尚未呈现,见 -> [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go) 中 `Declared()` 上方的注释。下文的调试准备入口因此只由 Core 与 SDK 的端到端测试验证,插件作者在桌面端界面里暂时看不到它的效果。 +> **宿主支持。** Lithe 桌面端声明 `buildSystems` 和 `buildProviders`(版本 `0` 和 `1`):构建窗口发现构建实例、加载提供者模型、解析可执行文件候选、运行命令任务和提供者任务、准备应用启动,并发现和运行提供者测试;运行声明了 `debug.adapter` 时,构建窗口里目标的“调试”和标题栏对提供者运行配置的“调试”先让提供者准备程序,再用这个运行指定的本插件适配器启动调试;“运行当前文件”向版本 `1` 的提供者询问文件里的入口。model inputs、原生配置、内联测试报告和运行时调试,桌面端尚未呈现,见 +> [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go) 中 `Declared()` 上方的注释。 ### 选择入口 @@ -106,8 +106,8 @@ A plugin can provide only a workspace backend and create no web page. Users buil These entry points all belong to `buildProviders` (version `0`): the manifest requires `requires.buildProviders: 0`, and the version of the `litheBuild` process protocol is the version of `buildProviders`. Node.js SDK 0.5.0 and Java SDK 0.5.0 implement every entry point; the Rust SDK source on `main` implements them too, shipping in the next Rust SDK release (0.4.0 does not); the Go SDK has no build-provider interface. For the capability see [Build providers](../reference/domains/build-providers.md); the [contract](../contract/v1/README.md#build-providers) is normative for fields and error codes. -> **Host support.** The Lithe desktop declares `buildSystems` and `buildProviders` (versions `0` and `1`): the Build window detects build instances, loads provider models, resolves executable candidates, runs command and provider tasks, prepares application launches, and discovers and runs provider tests; Run on Current File asks providers of version `1` for a file's entrypoints. Build-provider debug preparation, model inputs, native configuration, inline test reports, and runtime debugging are not presented on the desktop yet; see the comment above `Declared()` in -> [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go). The debug preparation entry point below is therefore verified only by the Core and SDK end-to-end tests, and a plugin author cannot yet see its effect in the desktop UI. +> **Host support.** The Lithe desktop declares `buildSystems` and `buildProviders` (versions `0` and `1`): the Build window detects build instances, loads provider models, resolves executable candidates, runs command and provider tasks, prepares application launches, and discovers and runs provider tests; for a run that declares `debug.adapter`, Debug on a Build window target or on a provider run configuration in the title bar has the provider prepare the program and then starts the plugin's own adapter that the run names; Run on Current File asks providers of version `1` for a file's entrypoints. Model inputs, native configuration, inline test reports, and runtime debugging are not presented on the desktop yet; see the comment above `Declared()` in +> [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go). ### Choosing an entry point diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 4b4db58c..57a655e7 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -71,9 +71,9 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https ¹ 桌面端声明了这个能力,但其中有些部分还没有界面:对应的部分没有按钮、菜单或窗口,插件照常安装,也不会因此失败。尚未呈现的部分以桌面端源码里 `Declared()` 上方的注释为准([`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go)): -- 语言服务器的代码操作(code actions)、签名帮助(signature help)和内嵌提示(inlay hints)尚未呈现,插件的 `foldingRange` 提供者未路由;诊断、补全、悬停、定义、引用、重命名、格式化、文档符号、文档链接和语义高亮均已呈现,`{kind: "tool"}` 启动按工作区工具链解析。 +- 插件的 `foldingRange` 提供者未路由;语言服务器的诊断、补全、悬停、签名帮助、代码操作、内嵌提示、定义、引用、重命名、格式化、文档符号、文档链接和语义高亮均已呈现,`{kind: "tool"}` 启动按工作区工具链解析。 - `systemCommand` 启动的命令查找只读 `PATH` 和插件已安装的受管命令目录;依赖项目工具链或用户覆盖的启动应使用 `tool` 启动。 -- 构建提供者的调试准备、模型输入、原生配置、内联测试报告和运行期调试;构建系统的实例选项和任务准备。 +- 构建提供者的模型输入、原生配置、内联测试报告和运行期调试;构建系统的实例选项和任务准备。 - 插件声明的运行配置类型只能运行,不能调试。 - 不属于任何工具窗口的 `ui` 命令。 - VCS 提供者的逐行追溯(annotation)、文件历史、文件操作、元数据监听、认证、历史提交差异、项目树与编辑器行号栏状态,以及 `lithe/vcs/execution` 控制台输出。 @@ -186,9 +186,9 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani ¹ The desktop client declares this capability, but some of its parts have no surface yet: the missing part has no button, menu, or window, and the plugin installs and does not fail because of it. The notes above `Declared()` in the desktop source are authoritative for what is not presented ([`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go)): -- For language servers: code actions, signature help, and inlay hints have no editor surface yet, and a plugin's `foldingRange` provider is not routed; diagnostics, completion, hover, definition, references, rename, formatting, document symbols, document links, and semantic tokens are presented, and `{kind: "tool"}` launches resolve through the workspace toolchain. +- For language servers: a plugin's `foldingRange` provider is not routed; diagnostics, completion, hover, signature help, code actions, inlay hints, definition, references, rename, formatting, document symbols, document links, and semantic tokens are presented, and `{kind: "tool"}` launches resolve through the workspace toolchain. - Command lookup for `systemCommand` launches reads `PATH` and the plugin's installed command directories only; a launch that depends on a project toolchain or a user override must use a `tool` launch. -- For build providers: debug preparation, model inputs, native configuration, inline test reports, and runtime debugging; for build systems: instance options and task preparations. +- For build providers: model inputs, native configuration, inline test reports, and runtime debugging; for build systems: instance options and task preparations. - 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. diff --git a/shared/plugins/reference/domains/build-providers.md b/shared/plugins/reference/domains/build-providers.md index b8754cdf..820c9bc5 100644 --- a/shared/plugins/reference/domains/build-providers.md +++ b/shared/plugins/reference/domains/build-providers.md @@ -6,8 +6,8 @@ 有些构建工具只能通过自己的 API 给出项目模型(Gradle Tooling API、BEAM 里的 Mix)。这类插件在 `buildSystems[].provider` 声明一个构建提供者:一个和语言服务器同类的长驻 LSP 基础协议进程,回答 `lithe/build/*` 请求。模型、依赖、任务、测试、运行准备、调试准备、原生配置都可以交给它;宿主仍然负责启动和停止进程、显示界面、运行最终的程序。 -> **宿主支持。** Lithe 桌面端声明 `buildSystems` 和 `buildProviders`(版本都是 `0`),不声明 `buildModelInputs`:`requires` 里有它的插件(只读模型输入的生产者和消费者)不会被提供安装。构建窗口发现构建实例、加载提供者模型、解析可执行文件候选并运行命令任务和提供者任务。 -> 构建提供者的运行准备、测试、调试准备、模型输入、原生配置、内联测试报告和运行时调试,桌面端尚未呈现;`Declared()` 上方的同一段注释还写到构建窗口会准备应用目标,具体以该注释为准。 +> **宿主支持。** Lithe 桌面端声明 `buildSystems`(版本 `0`)和 `buildProviders`(版本 `0` 和 `1`),不声明 `buildModelInputs`:`requires` 里有它的插件(只读模型输入的生产者和消费者)不会被提供安装。构建窗口发现构建实例、加载提供者模型、解析可执行文件候选、运行命令任务和提供者任务、准备应用启动和原生程序调试,并发现和运行提供者测试;“运行当前文件”向版本 `1` 的提供者询问文件里的入口。 +> 模型输入、原生配置、内联测试报告和运行时调试,桌面端尚未呈现,以 `Declared()` 上方的注释为准。 > 宿主只呈现它实现的功能,提供者不得依赖宿主一定会调用其中任何一个。说明见 [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go);各能力的对照见[能力与协议版本对照](../capabilities-and-versions.md#能力版本requires)。 > 对契约有疑问,请到 [Lithe-core-rust 的 Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues) 反馈。 @@ -126,8 +126,8 @@ Some build tools expose their project model only through their own API (the Gradle Tooling API, Mix inside the BEAM). Such a plugin declares a build provider in `buildSystems[].provider`: a long-lived LSP base-protocol process of the same kind as a language server, which answers `lithe/build/*` requests. Models, dependencies, tasks, tests, run preparation, debug preparation, and native configuration can all be handed to it. The host still starts and stops the process, draws the UI, and runs the final program. -> **Host support.** The Lithe desktop declares `buildSystems` and `buildProviders` (both version `0`) and does not declare `buildModelInputs`: a plugin whose `requires` lists it (a producer or consumer of read-only model inputs) is not offered for install. The Build window detects build instances, loads provider models, resolves executable candidates, and runs command tasks and provider tasks. -> Build-provider run preparation, tests, debug preparation, model inputs, native configuration, inline test reports, and runtime debugging are not presented on the desktop yet; the same comment above `Declared()` also says the Build window prepares application targets, so read that comment for the current state. +> **Host support.** The Lithe desktop declares `buildSystems` (version `0`) and `buildProviders` (versions `0` and `1`) and does not declare `buildModelInputs`: a plugin whose `requires` lists it (a producer or consumer of read-only model inputs) is not offered for install. The Build window detects build instances, loads provider models, resolves executable candidates, runs command and provider tasks, prepares application launches and native program debugging, and discovers and runs provider tests; Run on Current File asks providers of version `1` for a file's entrypoints. +> Model inputs, native configuration, inline test reports, and runtime debugging are not presented on the desktop yet; the comment above `Declared()` is authoritative. > A host presents the features it implements, and a provider must not depend on a host calling any of them. See [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go); for a per-capability comparison see the [capability and protocol versions](../capabilities-and-versions.md#capability-versions-requires). > Questions about the contract go to [Lithe-core-rust Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues). diff --git a/shared/plugins/reference/domains/build-systems.md b/shared/plugins/reference/domains/build-systems.md index 025a0aa7..27299fa1 100644 --- a/shared/plugins/reference/domains/build-systems.md +++ b/shared/plugins/reference/domains/build-systems.md @@ -7,7 +7,7 @@ `buildSystems` 用数据描述一个项目级构建工具(Cargo、Go、Gradle、Maven 等):怎么识别项目根目录、找哪个可执行文件、怎么得到项目模型、有哪些任务和运行入口、哪些文件变化要重新同步。所有构建工具共用同一套模型和命令:Core 校验声明、检测实例、解码模型、展开每一条命令行,宿主只执行 Core 规划好的进程并把输出交回。所以社区插件加一个构建工具不需要改宿主,宿主代码也不按构建系统 ID 分支。模型需要程序计算时,再加一个[构建提供者](build-providers.md)。 > **宿主支持。** Lithe 桌面端声明 `buildSystems` 和 `buildProviders`(版本都是 `0`):构建窗口发现构建实例、加载提供者模型、解析 Core 返回的有序可执行文件候选,并运行命令任务和提供者任务。桌面端也声明 `runConfigurationTypes` `0`([1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148)):运行/调试配置对话框在内置类型之后列出插件类型,按 Core 描述的表单和插件翻译编辑,存到 `.lithe/run/plugin/<插件 ID>.toml`,按 Core 为检测到的实例规划的命令运行;插件类型不能调试。桌面端也声明 `beforeLaunchTasks` `0`([1lck/Lithe-IDEA#2169](https://github.com/1lck/Lithe-IDEA/pull/2169)):每个运行配置“启动前”列表的“添加新任务”菜单在“运行另一个配置”之后列出插件任务,按 Core 描述的表单和插件翻译编辑,在配置启动前按 Core 为检测到的实例规划的命令运行。运行配置类型和任务的包内 SVG 图标显示在菜单和列表里,PNG 图标暂时显示宿主图标。桌面端不声明 `buildModelInputs`、`executionProviders` 和 `toolchainProviders`:`requires` 里有其中任何一个的插件不会被提供安装,所以 `modelSharing` 和 `modelInputs` 在桌面端用不上。 -> 构建系统的实例级选项(`scope: "instance"`)和项目任务的 `preparation`,桌面端尚未呈现:插件照常安装,这部分没有界面,也不会被调用。构建提供者的运行准备、测试、调试准备、模型输入、原生配置、内联测试报告和运行时调试同样尚未呈现,见[构建提供者](build-providers.md)。 +> 构建系统的实例级选项(`scope: "instance"`)和项目任务的 `preparation`,桌面端尚未呈现:插件照常安装,这部分没有界面,也不会被调用。构建提供者的模型输入、原生配置、内联测试报告和运行时调试同样尚未呈现,见[构建提供者](build-providers.md)。 > 宿主只呈现它实现的功能,插件不得依赖宿主一定会调用其中任何一个。该注释还写到系统命令的工具发现目前只读 `PATH`,依赖项目工具链或用户覆盖的计划会被拒绝,它是否也约束可执行文件候选里的 `setting` 和 `toolchain` 来源,注释没有说明;依赖这两种来源前,先在桌面端实际试一遍。说明见 [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go);各能力的对照见[能力与协议版本对照](../capabilities-and-versions.md#能力版本requires)。 > 对契约有疑问,请到 [Lithe-core-rust 的 Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues) 反馈。 @@ -109,7 +109,7 @@ `buildSystems` describes a project-level build tool (Cargo, Go, Gradle, Maven, …) as data: how to recognize a project root, which executable to use, how to get the project model, which tasks and run entries exist, and which file changes require a re-sync. Every build tool shares the same model and commands: Core validates the declaration, detects instances, decodes the model, and expands every command line; the host only runs the processes Core planned and passes their output back. A community plugin therefore adds a build tool without any host change, and no host code branches on a build-system ID. When the model must be computed by a program, add a [build provider](build-providers.md). > **Host support.** The Lithe desktop declares `buildSystems` and `buildProviders` (both version `0`): the Build window detects build instances, loads provider models, resolves the ordered executable candidates Core returns, and runs command and provider tasks. It also declares `runConfigurationTypes` `0` ([1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148)): the Run/Debug Configurations dialog lists plugin types after the built-in ones, edits them with the form Core describes in the plugin's translation, saves them to `.lithe/run/plugin/.toml`, and runs them with the command Core plans for the detected instance; a plugin type has no debugger. It also declares `beforeLaunchTasks` `0` ([1lck/Lithe-IDEA#2169](https://github.com/1lck/Lithe-IDEA/pull/2169)): the Add New Task menu of every configuration's Before Launch list offers plugin tasks after Run Another Configuration, edits them with the form Core describes in the plugin's translation, and runs them before the configuration starts with the command Core plans for the detected instance. Run configuration types and tasks show their package SVG icons in the menus and lists; a PNG icon shows the host icon for now. The desktop does not declare `buildModelInputs`, `executionProviders` or `toolchainProviders`: a plugin whose `requires` lists any of them is not offered for installation, so `modelSharing` and `modelInputs` are unusable there. -> Build-system instance options (`scope: "instance"`) and project-task `preparation` are not presented on the desktop yet: the plugin installs, and that part has no surface and is never called. Build-provider run preparation, tests, debug preparation, model inputs, native configuration, inline test reports and runtime debug are not presented either; see [Build providers](build-providers.md). +> Build-system instance options (`scope: "instance"`) and project-task `preparation` are not presented on the desktop yet: the plugin installs, and that part has no surface and is never called. Build-provider model inputs, native configuration, inline test reports and runtime debug are not presented either; see [Build providers](build-providers.md). > A host presents the features it implements; a plugin must not depend on a host calling any of them. The same comment says tool discovery for system commands reads `PATH` only and that a plan depending on a project toolchain or a user override is refused. It does not say whether that also limits the `setting` and `toolchain` sources of executable candidates, so try those two on the desktop before relying on them. See [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go); the per-capability comparison is in [Capabilities and protocol versions](../capabilities-and-versions.md#capability-versions-requires). > Questions about the contract go to [Lithe-core-rust Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues). diff --git a/shared/plugins/reference/domains/debug-adapters.md b/shared/plugins/reference/domains/debug-adapters.md index fd39cffd..eaed3a77 100644 --- a/shared/plugins/reference/domains/debug-adapters.md +++ b/shared/plugins/reference/domains/debug-adapters.md @@ -104,7 +104,7 @@ Core 只把 `localhost`、`127.0.0.0/8`、`::1` 判为本机;其他主机都 | 宿主 | 现状 | | --- | --- | -| Lithe 桌面端 | 声明 `debugAdapters`:stdio 适配器,以及通过本机回环 TCP 连接插件语言服务器里的适配器;`launch` 和 `attach`(远程主机在用户确认后)、参数和环境绑定、`features` 和 `defaults`。后端发起的 `debug/start`、`run/start` 属于宿主服务,由后端通过 `getCapabilities` 在运行时发现,不在能力表里。构建提供者的原生调试准备和运行时调试在桌面端尚未呈现。细节见[桌面端源码](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go) | +| Lithe 桌面端 | 声明 `debugAdapters`:stdio 适配器、打印自己监听的本机回环 TCP 端点的适配器进程(`tcpAnnounced`),以及通过本机回环 TCP 连接插件语言服务器里的适配器;`launch` 和 `attach`(远程主机在用户确认后)、参数和环境绑定、`features` 和 `defaults`。后端发起的 `debug/start`、`run/start` 属于宿主服务,由后端通过 `getCapabilities` 在运行时发现,不在能力表里。构建提供者的原生调试准备由构建窗口和标题栏的“调试”发起;运行时调试在桌面端尚未呈现。细节见[桌面端源码](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go) | ### 契约章节 @@ -243,7 +243,7 @@ The other rules of `run/start`, `run/stop`, and `run/didExit` are in [Plugin bac | Host | Status | | --- | --- | -| Lithe desktop | Declares `debugAdapters`: stdio adapters and adapters inside the plugin's language server over loopback TCP; `launch` and `attach` (a remote host after the user confirms it), argument and environment bindings, `features`, and `defaults`. The backend-started `debug/start` and `run/start` are host services a backend discovers at runtime through `getCapabilities`, not through the capability table. A build provider's native debug preparation and runtime debug are not presented on the desktop yet. Details are in the [desktop source](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go) | +| Lithe desktop | Declares `debugAdapters`: stdio adapters, adapter processes that print the loopback TCP endpoint they listen on (`tcpAnnounced`), and adapters inside the plugin's language server over loopback TCP; `launch` and `attach` (a remote host after the user confirms it), argument and environment bindings, `features`, and `defaults`. The backend-started `debug/start` and `run/start` are host services a backend discovers at runtime through `getCapabilities`, not through the capability table. A build provider's native debug preparation starts from Debug in the Build window and the title bar; runtime debug is not presented on the desktop yet. Details are in the [desktop source](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go) | ### Contract sections diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index b84250d4..119c00d5 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -32,9 +32,9 @@ and `null` (see `Json`). ## What the Lithe desktop serves -The Lithe desktop declares `backend`, `pluginFunctions`, `buildProviders` and -`buildSystems` (all version 0), so the function, host-service and build -protocols below run there. It does not declare `keymapImportProviders` or +The Lithe desktop declares `backend`, `pluginFunctions` and `buildSystems` +(version 0) and `buildProviders` (versions 0 and 1), so the function, +host-service and build protocols below run there. It does not declare `keymapImportProviders` or `buildModelInputs`: a plugin whose manifest requires one of them is not offered for installation there. The Core end-to-end tests still drive those protocols. Which host services a session may call is reported at run time; see diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 98ca7156..13cfa7ca 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -38,8 +38,7 @@ This SDK has no VCS provider API; write VCS providers with the The Lithe desktop declares `backend` and `pluginFunctions` (both version 0) and `buildProviders` (versions 0 and 1), so the function, host-service and build -provider protocols below run there, except that the desktop does not present -build-provider debug preparation yet. It does not declare +provider protocols below run there. It does not declare `keymapImportProviders`: a plugin whose manifest requires it is not offered for installation there, although the Core end-to-end tests still drive the protocol. Which host services a session may call is reported at run time; see