diff --git a/.gitignore b/.gitignore index 24b3542d..3b9d07be 100644 --- a/.gitignore +++ b/.gitignore @@ -4,5 +4,6 @@ node_modules/ /shared/plugins/sdk/java/**/target/ /shared/plugins/sdk/rust/target/ +/shared/plugins/sdk/go/bin/ *.tmp .DS_Store diff --git a/README.md b/README.md index 03c5a4a4..6d08e0d6 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ node scripts/rust-core/verify-platform-tests.mjs # 每个测试都在所 scripts/rust-core/verify-rust-core-comments.sh # 注释规范 node scripts/logging/generate-log-events.mjs --check # 日志事件目录与生成表一致 node shared/plugins/scripts/verify-docs.mjs # 契约 $id 与文档链接 -node shared/plugins/scripts/sdk-e2e.mjs # 三个 SDK 对当前 Core 的端到端测试 +node shared/plugins/scripts/sdk-e2e.mjs # 四个 SDK 对当前 Core 的端到端测试 ``` 修改 `shared/plugins/contract/v1/`、`rust/crates/plugin-model/src/capabilities.rs` 或 @@ -59,7 +59,7 @@ node scripts/rust-core/verify-platform-tests.mjs # every test runs on a scripts/rust-core/verify-rust-core-comments.sh # comment rules node scripts/logging/generate-log-events.mjs --check # log event catalog matches the generated table node shared/plugins/scripts/verify-docs.mjs # contract $id values and documentation links -node shared/plugins/scripts/sdk-e2e.mjs # end-to-end tests of the three SDKs against this Core +node shared/plugins/scripts/sdk-e2e.mjs # end-to-end tests of the four SDKs against this Core ``` A pull request that changes `shared/plugins/contract/v1/`, `rust/crates/plugin-model/src/capabilities.rs` or `rust/crates/plugin-rpc/src/` updates the [protocol changelog](shared/plugins/reference/protocol-changelog.md) in the same pull request. diff --git a/rust/crates/core/Cargo.toml b/rust/crates/core/Cargo.toml index 45a9956e..01072a7e 100644 --- a/rust/crates/core/Cargo.toml +++ b/rust/crates/core/Cargo.toml @@ -91,6 +91,11 @@ name = "plugin_sdk_rust" path = "../../../shared/plugins/sdk/e2e/plugin_sdk_rust.rs" required-features = ["plugin-sdk-e2e"] +[[test]] +name = "plugin_sdk_go" +path = "../../../shared/plugins/sdk/e2e/plugin_sdk_go.rs" +required-features = ["plugin-sdk-e2e"] + [[test]] name = "plugin_sdk_build" path = "../../../shared/plugins/sdk/e2e/plugin_sdk_build.rs" diff --git a/shared/plugins/README.md b/shared/plugins/README.md index 11c7c166..e2ea50d1 100644 --- a/shared/plugins/README.md +++ b/shared/plugins/README.md @@ -104,11 +104,14 @@ Schema 只检查 JSON 结构。ID 引用、权限、激活事件、模板变量 只用语言服务器、运行和测试的插件不需要后端。需要构建后端(`buildProviders`)、插件函数,或给插件自己的网页配一个后端进程(`backend`)时,用官方 SDK 写:协议、取消、进程清理和错误处理由 SDK 负责,你只写处理函数。 +**新插件优先用 Rust 或 Go SDK。** 两者把后端编译成每个平台各一份的原生可执行文件,用户机器上不需要 Node.js 或 Java 运行时。插件本来就围绕 JVM 工具(例如 Maven、Gradle、Tomcat)时用 Java SDK。构建后端(`buildProviders`)目前只有 Node.js 和 Java SDK 支持,VCS 后端只有 Node.js SDK 支持,这两类后端照旧用它们。 + | SDK | 版本 | 运行时 | Release | 怎么放进插件 | | --- | --- | --- | --- | --- | +| [Rust](sdk/rust/README.md) | 0.4.0 | Rust 1.87+ | [`sdk-rust-v0.4.0`](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-rust-v0.4.0):`lithe-plugin-sdk-rust-0.4.0.crate` 和 `.sha256` | 用 Git 依赖锁定标签(`Cargo.lock` 记录 commit),或解压后作为 `path` 依赖;编译成每个平台各一份的插件后端可执行文件 | +| [Go](sdk/go/README.md) | 未发布 | Go 1.22+ | Go 模块标签 `shared/plugins/sdk/go/v<版本>`,由 Go 模块代理分发,没有 Release 附件;还没有打过标签 | `go get` 锁定标签或 commit(`go.sum` 记录内容哈希);编译成每个平台各一份的插件后端可执行文件 | | [Node.js](sdk/node/README.md) | 0.5.0 | Node.js 20.3+ | [`sdk-node-v0.5.0`](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-node-v0.5.0):`lithe-plugin-sdk-node-0.5.0.tgz` 和 `.sha256` | 解压后把 `package/` 复制进插件包,用相对路径导入 | | [Java](sdk/java/README.md) | 0.5.0 | Java 8+ | [`sdk-java-v0.5.0`](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-java-v0.5.0):`lithe-plugin-sdk-java-0.5.0.jar` 和 `.sha256` | shade 进后端 JAR | -| [Rust](sdk/rust/README.md) | 0.4.0 | Rust 1.87+ | [`sdk-rust-v0.4.0`](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-rust-v0.4.0):`lithe-plugin-sdk-rust-0.4.0.crate` 和 `.sha256` | 用 Git 依赖锁定标签(`Cargo.lock` 记录 commit),或解压后作为 `path` 依赖;编译成每个平台各一份的插件后端可执行文件 | Rust 的 Git 依赖这样写: @@ -116,9 +119,15 @@ Rust 的 Git 依赖这样写: lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust", tag = "sdk-rust-v0.4.0" } ``` -SDK 的源码都在本目录的 `sdk/` 下,发布在 [Core 仓库的 Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases) 里(标签 `sdk-node-v<版本>`、`sdk-java-v<版本>`、`sdk-rust-v<版本>`),不在 npm、Maven 或 crates.io 上。Rust SDK 只实现插件后端(`backend`):插件函数和宿主服务;构建后端请用 Node.js 或 Java SDK,VCS 后端请用 Node.js SDK。各 SDK 的 README 有 “What the Lithe desktop serves” 一节,说明 Lithe 桌面端提供哪些协议;各协议的版本见[进程协议版本](reference/capabilities-and-versions.md#进程协议版本)。以上三个版本说的是版本 `0` 的协议;已退役的 `lithe-plugin-docs` 仓库发布过更早的 SDK,它们说的是旧协议,Lithe 桌面端不接受用它们写的插件,请只使用 Core 仓库发布的版本。 +Go 这样引入(第一个标签发布前写 `main` 上的 commit,Go 会记成伪版本): + +```sh +go get github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go@<标签或 commit> +``` + +SDK 的源码都在本目录的 `sdk/` 下。Node.js、Java 和 Rust SDK 发布在 [Core 仓库的 Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases) 里(标签 `sdk-node-v<版本>`、`sdk-java-v<版本>`、`sdk-rust-v<版本>`),不在 npm、Maven 或 crates.io 上;Go SDK 是本仓库子目录里的 Go 模块,版本就是标签 `shared/plugins/sdk/go/v<版本>`,由 Go 模块代理和校验和数据库分发。Rust 和 Go SDK 只实现插件后端(`backend`):插件函数和宿主服务;构建后端请用 Node.js 或 Java SDK,VCS 后端请用 Node.js SDK。各 SDK 的 README 有 “What the Lithe desktop serves” 一节,说明 Lithe 桌面端提供哪些协议;各协议的版本见[进程协议版本](reference/capabilities-and-versions.md#进程协议版本)。以上版本说的都是版本 `0` 的协议;已退役的 `lithe-plugin-docs` 仓库发布过更早的 SDK,它们说的是旧协议,Lithe 桌面端不接受用它们写的插件,请只使用 Core 仓库发布的版本。 -SDK 与插件后端在构建时下载,并按锁定的 SHA-256(或 Git commit)校验;插件包安装后没有 `npm install` 步骤。独立的大型依赖可声明 [`managedRuntimes`](contract/v1/README.md#managed-runtimes):宿主在用户批准安装后校验并准备,完整缓存可离线复用;插件自身不能用启动脚本绕过这项声明或自行改写包。 +SDK 与插件后端在构建时下载,并按锁定的 SHA-256(或 Git commit、`go.sum`)校验;插件包安装后没有 `npm install` 步骤。独立的大型依赖可声明 [`managedRuntimes`](contract/v1/README.md#managed-runtimes):宿主在用户批准安装后校验并准备,完整缓存可离线复用;插件自身不能用启动脚本绕过这项声明或自行改写包。 [Maven 插件](https://github.com/Lithe-IDEA/lithe-plugin-maven) 的 `sdk.lock.json` 是锁定 Java SDK 的现成例子。 @@ -141,7 +150,7 @@ SDK 与插件后端在构建时下载,并按锁定的 SHA-256(或 Git commit | 教程 | 内容 | | --- | --- | | [LSP 插件完整生命周期](guides/lsp-plugin-lifecycle.md) | 从 Lua 模板开始:清单、服务器打包、激活、状态目录、停止、升级与卸载 | -| [插件接入统一日志](guides/plugin-logging.md) | 三 SDK 的安全失败边界、受管诊断通道,以及 `${logDir}` 的本地会话生命周期 | +| [插件接入统一日志](guides/plugin-logging.md) | 各 SDK 的安全失败边界、受管诊断通道,以及 `${logDir}` 的本地会话生命周期 | | [原生构建工作流](guides/native-build-workflows.md) | Node/Java SDK 的构建执行、精确测试、运行准备,以及用真实 Core 做端到端验证 | | [构建、运行与测试接入](guides/build-tool-integration.md) | 执行提供者示例、工程后端边界,以及声明式构建系统的现状和已发布示例 | | [编写调试适配器插件](guides/debug-adapter-plugin.md) | 从最小清单到启动方式、先编译再调试的 `executable`,以及调试控制台补全 | @@ -200,11 +209,12 @@ fixture 放在 `fixtures/<功能>/` 下,文件按演示的能力命名,例 | `npm run --prefix shared/plugins/sdk/node test:types` | Node.js SDK 的 TypeScript 使用方检查;先运行 `npm ci --prefix shared/plugins/sdk/node --ignore-scripts` 安装开发依赖 | | `mvn -B -ntp -f shared/plugins/sdk/java/pom.xml verify` | Java SDK 的单元测试;加 `-Djvm=` 可指定运行测试的 Java(CI 用 Java 8) | | `cargo test --locked --manifest-path shared/plugins/sdk/rust/Cargo.toml` | Rust SDK 的单元测试(CI 用 Rust 1.87,另用仓库 `rust-toolchain.toml` 固定的版本跑 `cargo fmt` 和 `cargo clippy`) | -| `node shared/plugins/scripts/sdk-e2e.mjs` | 端到端测试:先构建三个 SDK 的示例后端,再运行 `cargo test -p lithe-core --features plugin-sdk-e2e` 的 `plugin_sdk_node`、`plugin_sdk_java`、`plugin_sdk_rust` 和 `plugin_sdk_build` 四个测试,对象是**当前工作树的 Core**;总是包含原生构建工作流和快捷键导入场景 | +| `go -C shared/plugins/sdk/go test -race ./...` | Go SDK 的单元测试;另用 `go -C shared/plugins/sdk/go vet ./...` 和 `gofmt -l shared/plugins/sdk/go` 检查。CI 目前不跑这三条,只在端到端测试里构建 Go 示例 | +| `node shared/plugins/scripts/sdk-e2e.mjs` | 端到端测试:先构建四个 SDK 的示例后端,再运行 `cargo test -p lithe-core --features plugin-sdk-e2e` 的 `plugin_sdk_node`、`plugin_sdk_java`、`plugin_sdk_rust`、`plugin_sdk_go` 和 `plugin_sdk_build` 五个测试,对象是**当前工作树的 Core**;总是包含原生构建工作流和快捷键导入场景 | -端到端测试需要 Rust、Node.js 20.3+、Java(`LITHE_PLUGIN_SDK_JAVA_RUNTIME` 指定,或 `PATH` 上的 `java`)和 Maven。场景文件在 [`sdk/e2e/`](sdk/e2e):Node.js 和 Java 跑同一套构建后端场景,Rust 跑插件后端场景(`plugin_sdk/backend.rs`),测试代替宿主应答凭据请求。`LITHE_PLUGIN_SDK_JAVA_SAMPLE`、`LITHE_PLUGIN_SDK_JAVA_NATIVE_SAMPLE` 和 `LITHE_PLUGIN_SDK_RUST_SAMPLE` 可以指定已构建好的示例,跳过构建。 +端到端测试需要 Rust、Go 1.22+(`PATH` 上的 `go`)、Node.js 20.3+、Java(`LITHE_PLUGIN_SDK_JAVA_RUNTIME` 指定,或 `PATH` 上的 `java`)和 Maven。场景文件在 [`sdk/e2e/`](sdk/e2e):Node.js 和 Java 跑同一套构建后端场景,Rust 和 Go 跑同一套插件后端场景(`plugin_sdk/backend.rs`),测试代替宿主应答凭据请求。`LITHE_PLUGIN_SDK_JAVA_SAMPLE`、`LITHE_PLUGIN_SDK_JAVA_NATIVE_SAMPLE`、`LITHE_PLUGIN_SDK_RUST_SAMPLE` 和 `LITHE_PLUGIN_SDK_GO_SAMPLE` 可以指定已构建好的示例,跳过构建。 -发版:先改版本号(Node.js 改 `shared/plugins/sdk/node/package.json`;Java 运行 `mvn -f shared/plugins/sdk/java/pom.xml versions:set -DnewVersion=<版本> -DgenerateBackupPoms=false`,三个 pom 一起改;Rust 改 `shared/plugins/sdk/rust/Cargo.toml` 的 `workspace.package.version` 并更新 `Cargo.lock`),合并后推送对应标签 `sdk-node-v<版本>`、`sdk-java-v<版本>` 或 `sdk-rust-v<版本>`。仓库根的发版工作流 `.github/workflows/plugins-release-{node,java,rust}-sdk.yml` 由标签触发,检查标签和版本一致,测试通过后把包和 `.sha256` 发到 Core 仓库的 Releases。发版后更新本页和各 SDK README 里的版本号。 +发版:先改版本号(Node.js 改 `shared/plugins/sdk/node/package.json`;Java 运行 `mvn -f shared/plugins/sdk/java/pom.xml versions:set -DnewVersion=<版本> -DgenerateBackupPoms=false`,三个 pom 一起改;Rust 改 `shared/plugins/sdk/rust/Cargo.toml` 的 `workspace.package.version` 并更新 `Cargo.lock`),合并后推送对应标签 `sdk-node-v<版本>`、`sdk-java-v<版本>` 或 `sdk-rust-v<版本>`。仓库根的发版工作流 `.github/workflows/plugins-release-{node,java,rust}-sdk.yml` 由标签触发,检查标签和版本一致,测试通过后把包和 `.sha256` 发到 Core 仓库的 Releases。Go SDK 没有版本文件,也没有发版工作流:合并后推送标签 `shared/plugins/sdk/go/v<版本>` 就是发布,Go 模块代理按需从标签取源码;校验和数据库会记住每个版本的内容,所以标签推送后不能移动或删除,版本号也不能重用。发版后更新本页和各 SDK README 里的版本号。 ### 许可证 @@ -314,11 +324,14 @@ 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. Use the Java SDK when the plugin is built around JVM tools anyway, such as Maven, Gradle, or Tomcat. 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. + | SDK | Version | Runtime | Release | How it goes into the plugin | | --- | --- | --- | --- | --- | +| [Rust](sdk/rust/README.md) | 0.4.0 | Rust 1.87+ | [`sdk-rust-v0.4.0`](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-rust-v0.4.0): `lithe-plugin-sdk-rust-0.4.0.crate` and `.sha256` | Pin the tag as a Git dependency (`Cargo.lock` records the commit), or unpack it as a `path` dependency; compile one backend executable per platform | +| [Go](sdk/go/README.md) | Unreleased | Go 1.22+ | Go module tags `shared/plugins/sdk/go/v`, served by the Go module proxy with no Release assets; not tagged yet | Pin a tag or commit with `go get` (`go.sum` records the content hash); compile one backend executable per platform | | [Node.js](sdk/node/README.md) | 0.5.0 | Node.js 20.3+ | [`sdk-node-v0.5.0`](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-node-v0.5.0): `lithe-plugin-sdk-node-0.5.0.tgz` and `.sha256` | Unpack it, copy `package/` into the plugin package, and import it by relative path | | [Java](sdk/java/README.md) | 0.5.0 | Java 8+ | [`sdk-java-v0.5.0`](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-java-v0.5.0): `lithe-plugin-sdk-java-0.5.0.jar` and `.sha256` | Shade it into the backend JAR | -| [Rust](sdk/rust/README.md) | 0.4.0 | Rust 1.87+ | [`sdk-rust-v0.4.0`](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-rust-v0.4.0): `lithe-plugin-sdk-rust-0.4.0.crate` and `.sha256` | Pin the tag as a Git dependency (`Cargo.lock` records the commit), or unpack it as a `path` dependency; compile one backend executable per platform | The Rust Git dependency looks like this: @@ -326,9 +339,15 @@ The Rust Git dependency looks like this: lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust", tag = "sdk-rust-v0.4.0" } ``` -All SDK sources live under `sdk/` in this directory and are published in the [Core repository's Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases) (tags `sdk-node-v`, `sdk-java-v`, `sdk-rust-v`), not on npm, Maven, or crates.io. The Rust SDK implements only the plugin backend (`backend`): plugin functions and host services; write build backends with the Node.js or Java SDK and VCS backends with the Node.js SDK. Each SDK's README has a "What the Lithe desktop serves" section naming the protocols the Lithe desktop client provides; the version of each protocol is in [Process protocol versions](reference/capabilities-and-versions.md#process-protocol-versions). The three versions above speak the version `0` protocols; the retired `lithe-plugin-docs` repository published earlier SDKs that speak an older protocol, and the Lithe desktop client does not accept plugins written with them, so use only versions released from the Core repository. +Add the Go SDK like this (until the first tag, name a commit of `main`; Go records it as a pseudo-version): + +```sh +go get github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go@ +``` + +All SDK sources live under `sdk/` in this directory. The Node.js, Java, and Rust SDKs are published in the [Core repository's Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases) (tags `sdk-node-v`, `sdk-java-v`, `sdk-rust-v`), not on npm, Maven, or crates.io; the Go SDK is a Go module in a subdirectory of this repository, its versions are the tags `shared/plugins/sdk/go/v`, and the Go module proxy and checksum database serve it. The Rust and Go SDKs implement only the plugin backend (`backend`): plugin functions and host services; write build backends with the Node.js or Java SDK and VCS backends with the Node.js SDK. Each SDK's README has a "What the Lithe desktop serves" section naming the protocols the Lithe desktop client provides; the version of each protocol is in [Process protocol versions](reference/capabilities-and-versions.md#process-protocol-versions). The versions above all speak the version `0` protocols; the retired `lithe-plugin-docs` repository published earlier SDKs that speak an older protocol, and the Lithe desktop client does not accept plugins written with them, so use only versions released from the Core repository. -Download SDKs and plugin backends at build time and verify against the SHA-256 (or Git commit) you pinned. An installed package has no `npm install` step. Large independent dependencies can declare [`managedRuntimes`](contract/v1/README.md#managed-runtimes): the host verifies and prepares them after approved installation, and complete cached sets work offline. Plugin launch scripts must not bypass this declaration or rewrite the package. +Download SDKs and plugin backends at build time and verify against the SHA-256 (or Git commit, or `go.sum`) you pinned. An installed package has no `npm install` step. Large independent dependencies can declare [`managedRuntimes`](contract/v1/README.md#managed-runtimes): the host verifies and prepares them after approved installation, and complete cached sets work offline. Plugin launch scripts must not bypass this declaration or rewrite the package. The [Maven plugin](https://github.com/Lithe-IDEA/lithe-plugin-maven)'s `sdk.lock.json` is a ready example of pinning the Java SDK. @@ -351,7 +370,7 @@ The example plugins are maintained in their own repositories. Before copying one | Guide | Covers | | --- | --- | | [LSP plugin lifecycle](guides/lsp-plugin-lifecycle.md) | Starting from the Lua template: manifest, server packaging, activation, state directories, shutdown, upgrade, and uninstall | -| [Plugin logging](guides/plugin-logging.md) | The safe failure boundary of the three SDKs, the managed diagnostics channel, and the local session lifecycle of `${logDir}` | +| [Plugin logging](guides/plugin-logging.md) | The safe failure boundary of each SDK, the managed diagnostics channel, and the local session lifecycle of `${logDir}` | | [Native build workflows](guides/native-build-workflows.md) | Build execution, exact tests, and run preparation in the Node and Java SDKs, and end-to-end verification against a real Core | | [Build, run, and test integration](guides/build-tool-integration.md) | Execution provider examples, the project backend boundary, and the current status and published examples of declarative build systems | | [Writing a debug adapter plugin](guides/debug-adapter-plugin.md) | From a minimal manifest to launch modes, compile-then-debug `executable`, and debug console completion | @@ -410,11 +429,12 @@ When a change touches the contract, a capability version, or the plugin function | `npm run --prefix shared/plugins/sdk/node test:types` | Node.js SDK TypeScript consumer check; first run `npm ci --prefix shared/plugins/sdk/node --ignore-scripts` to install the development dependencies | | `mvn -B -ntp -f shared/plugins/sdk/java/pom.xml verify` | Java SDK unit tests; add `-Djvm=` to choose the Java that runs them (CI uses Java 8) | | `cargo test --locked --manifest-path shared/plugins/sdk/rust/Cargo.toml` | Rust SDK unit tests (CI uses Rust 1.87, plus the release `rust-toolchain.toml` pins for `cargo fmt` and `cargo clippy`) | -| `node shared/plugins/scripts/sdk-e2e.mjs` | End-to-end tests: builds the sample backends of the three SDKs, then runs the four tests `plugin_sdk_node`, `plugin_sdk_java`, `plugin_sdk_rust`, and `plugin_sdk_build` of `cargo test -p lithe-core --features plugin-sdk-e2e` against the **Core in the current working tree**; it always includes the native build workflow and shortcut import scenarios | +| `go -C shared/plugins/sdk/go test -race ./...` | Go SDK unit tests; also check with `go -C shared/plugins/sdk/go vet ./...` and `gofmt -l shared/plugins/sdk/go`. CI does not run these three yet; it only builds the Go sample in the end-to-end tests | +| `node shared/plugins/scripts/sdk-e2e.mjs` | End-to-end tests: builds the sample backends of the four SDKs, then runs the five tests `plugin_sdk_node`, `plugin_sdk_java`, `plugin_sdk_rust`, `plugin_sdk_go`, and `plugin_sdk_build` of `cargo test -p lithe-core --features plugin-sdk-e2e` against the **Core in the current working tree**; it always includes the native build workflow and shortcut import scenarios | -The end-to-end tests need Rust, Node.js 20.3+, Java (set `LITHE_PLUGIN_SDK_JAVA_RUNTIME`, or have `java` on `PATH`), and Maven. The scenario files are in [`sdk/e2e/`](sdk/e2e): Node.js and Java run the same build backend scenarios, Rust runs the plugin backend scenario (`plugin_sdk/backend.rs`), and the test answers credential requests in place of the host. `LITHE_PLUGIN_SDK_JAVA_SAMPLE`, `LITHE_PLUGIN_SDK_JAVA_NATIVE_SAMPLE`, and `LITHE_PLUGIN_SDK_RUST_SAMPLE` can point at already built samples to skip building them. +The end-to-end tests need Rust, Go 1.22+ (`go` on `PATH`), Node.js 20.3+, Java (set `LITHE_PLUGIN_SDK_JAVA_RUNTIME`, or have `java` on `PATH`), and Maven. The scenario files are in [`sdk/e2e/`](sdk/e2e): Node.js and Java run the same build backend scenarios, Rust and Go run the same plugin backend scenario (`plugin_sdk/backend.rs`), and the test answers credential requests in place of the host. `LITHE_PLUGIN_SDK_JAVA_SAMPLE`, `LITHE_PLUGIN_SDK_JAVA_NATIVE_SAMPLE`, `LITHE_PLUGIN_SDK_RUST_SAMPLE`, and `LITHE_PLUGIN_SDK_GO_SAMPLE` can point at already built samples to skip building them. -Releasing: first bump the version (Node.js in `shared/plugins/sdk/node/package.json`; for Java run `mvn -f shared/plugins/sdk/java/pom.xml versions:set -DnewVersion= -DgenerateBackupPoms=false`, which updates all three poms; for Rust change `workspace.package.version` in `shared/plugins/sdk/rust/Cargo.toml` and update `Cargo.lock`), then after merging push the tag `sdk-node-v`, `sdk-java-v`, or `sdk-rust-v`. The release workflows `.github/workflows/plugins-release-{node,java,rust}-sdk.yml` at the repository root start from the tag, check that it matches the version, and, once tests pass, publish the package and its `.sha256` to the Core repository's Releases. After a release, update the version numbers in this page and in each SDK README. +Releasing: first bump the version (Node.js in `shared/plugins/sdk/node/package.json`; for Java run `mvn -f shared/plugins/sdk/java/pom.xml versions:set -DnewVersion= -DgenerateBackupPoms=false`, which updates all three poms; for Rust change `workspace.package.version` in `shared/plugins/sdk/rust/Cargo.toml` and update `Cargo.lock`), then after merging push the tag `sdk-node-v`, `sdk-java-v`, or `sdk-rust-v`. The release workflows `.github/workflows/plugins-release-{node,java,rust}-sdk.yml` at the repository root start from the tag, check that it matches the version, and, once tests pass, publish the package and its `.sha256` to the Core repository's Releases. The Go SDK has no version file and no release workflow: after merging, pushing the tag `shared/plugins/sdk/go/v` is the release, and the Go module proxy fetches the source from the tag on demand. The checksum database remembers each version's content, so never move or delete a pushed tag or reuse a version. After a release, update the version numbers in this page and in each SDK README. ### License diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 0e42e1ac..6d072f1d 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -143,7 +143,7 @@ previous one. Errors never disclose absolute paths. A host that advertises `keymapImportProviders` 0 implements the scoped reader. A host advertises the capability only with the complete import workflow. The official Node, -Java and Rust SDKs implement `litheKeymapImport` 0. +Java, Rust and Go SDKs implement `litheKeymapImport` 0. ## Package layout @@ -4748,10 +4748,22 @@ used as a Git dependency pinned by the tag. It enforces the same rules: on Unix points stdout at stderr so only protocol frames reach the host, and a panic ends only its call, reported like any unexpected failure. +[`sdk/go`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/sdk/go/README.md) is the Go SDK for +[plugin backends](#plugin-backend), which ship as packaged executables. It +implements this protocol with its host services and `litheKeymapImport`, but +neither build nor VCS providers. It needs Go 1.22 or newer, uses only the +standard library, and is released as Go module tags +(`shared/plugins/sdk/go/v`) that plugins pin through `go.sum`. It +enforces the same rules: on Unix it moves the protocol to a duplicate of the +stdout descriptor and points stdout at stderr so only protocol frames reach the +host, and a panic in a handler ends only that call, reported like any +unexpected failure. + The Node.js and Java SDKs each have a sample build provider (`sdk/*/examples/sample-build`) that answers one end-to-end scenario driven -through a real Core session; the Rust SDK's sample backend -(`sdk/rust/examples/sample-backend`) answers a plugin backend scenario in which +through a real Core session; the Rust and Go SDKs' sample backends +(`sdk/rust/examples/sample-backend`, `sdk/go/examples/sample-backend`) answer +the same plugin backend scenario, in which the test plays the host: it serves the credential requests and the workspace, file watch and window requests, delivers a command and a context change, and checks that cancellation reaches the host. That repository runs diff --git a/shared/plugins/guides/debug-adapter-plugin.md b/shared/plugins/guides/debug-adapter-plugin.md index c705bd6b..f123905a 100644 --- a/shared/plugins/guides/debug-adapter-plugin.md +++ b/shared/plugins/guides/debug-adapter-plugin.md @@ -166,7 +166,7 @@ Lithe 的调试控制台有输入行和补全弹窗。补全来自适配器的 D `process.executable` 只能是清单 `requiresTools` 列出的工具定义 ID,或插件包内的文件。运行结束时宿主发 `run/didExit` 通知。 这三个方法能否调用,以宿主 `getCapabilities` 的返回为准。Lithe 桌面端的能力声明注释把 run 与 debug 服务列为尚未注册,目前不要假定它们可用。 -官方 Node、Java、Rust SDK 还没有 `debug/start`、`run/start`、`run/stop` 的封装,需要时可以用 SDK 的通用宿主请求,以完整方法名调用, +官方 Node、Java、Rust、Go SDK 还没有 `debug/start`、`run/start`、`run/stop` 的封装,需要时可以用 SDK 的通用宿主请求,以完整方法名调用, 例如 Node SDK 的 `backend.host.request(method, params?)`,见 [Host services](../sdk/node/README.md#host-services)。 细节见[调试适配器](../reference/domains/debug-adapters.md)和契约的 @@ -364,7 +364,7 @@ A plugin with a backend (`requires.backend`) can decide which debug session to s `process.executable` can only be a tool-definition ID listed in the manifest's `requiresTools`, or a file inside the plugin package. The host sends the `run/didExit` notification when the run ends. Whether these three methods can be called is decided by what the host returns from `getCapabilities`. The Lithe desktop app's capability declaration comment lists the run and debug services as not yet registered, so do not assume they are available. -The official Node, Java, and Rust SDKs do not wrap `debug/start`, `run/start`, or `run/stop` yet; where needed, call them with the SDK's generic host request using the full method name, +The official Node, Java, Rust, and Go SDKs do not wrap `debug/start`, `run/start`, or `run/stop` yet; where needed, call them with the SDK's generic host request using the full method name, for example `backend.host.request(method, params?)` in the Node SDK, see [Host services](../sdk/node/README.md#host-services). For details, see [Debug adapters](../reference/domains/debug-adapters.md) and diff --git a/shared/plugins/guides/lsp-plugin-lifecycle.md b/shared/plugins/guides/lsp-plugin-lifecycle.md index 04043a25..30b16359 100644 --- a/shared/plugins/guides/lsp-plugin-lifecycle.md +++ b/shared/plugins/guides/lsp-plugin-lifecycle.md @@ -237,7 +237,7 @@ shasum -a 256 dist/lua-support-0.3.1-darwin-arm64.zip 服务器交出的文档没有对应文件(例如反编译的库类)时,用 `documents/registerContentProvider` 提供:用户打开该 scheme 的文档时, 宿主调用绑定的函数取只读内容(最多 1 MiB,宿主等 30 秒)。每个工作区窗口每个 scheme 只能有一个 provider,用 `subscriptions/dispose` 撤销。 -边界:声明 `remote: "unsupported"` 的服务器不在远程工作区启动。官方 Node、Java、Rust SDK 还没有这些方法的专用封装, +边界:声明 `remote: "unsupported"` 的服务器不在远程工作区启动。官方 Node、Java、Rust、Go SDK 还没有这些方法的专用封装, 可以用 SDK 的通用宿主请求,以完整方法名调用,例如 Node SDK 的 `backend.host.request(method, params?)`, 见 [Host services](../sdk/node/README.md#host-services)。桌面端只注册自己实现的宿主服务, 调用前用 `supports(method)` 确认。 @@ -721,7 +721,7 @@ a server of another plugin returns `plugin.host.foreignContribution`): When the server hands out documents that have no file (for example the decompiled source of a library class), serve them with `documents/registerContentProvider`: when the user opens a document of that scheme, the host calls the bound function for its read-only content (at most 1 MiB; the host waits 30 seconds). Each workspace window can have one provider per scheme; revoke it with `subscriptions/dispose`. -Limits: a server that declares `remote: "unsupported"` does not start in a remote workspace. The official Node, Java, and Rust SDKs do not wrap these methods yet; +Limits: a server that declares `remote: "unsupported"` does not start in a remote workspace. The official Node, Java, Rust, and Go SDKs do not wrap these methods yet; until they do, call them with the SDK's generic host request using the full method name, for example `backend.host.request(method, params?)` in the Node SDK, see [Host services](../sdk/node/README.md#host-services). The desktop registers only the host services it implements, so confirm with `supports(method)` before calling. diff --git a/shared/plugins/guides/native-build-workflows.md b/shared/plugins/guides/native-build-workflows.md index 87ffc183..d74a8d21 100644 --- a/shared/plugins/guides/native-build-workflows.md +++ b/shared/plugins/guides/native-build-workflows.md @@ -6,7 +6,7 @@ 插件可以只提供工作区后端,不创建网页。用户从原生工具窗口执行构建、发现与运行测试、准备应用启动;宿主继续管理工作区、取消、输出和应用进程。 -这些入口都属于 `buildProviders`(版本 `0`):清单要求 `requires.buildProviders: 0`,进程协议 `litheBuild` 的版本就是 `buildProviders` 的版本。Node.js SDK 0.5.0 和 Java SDK 0.5.0 实现了全部入口;Rust SDK 0.4.0 没有构建提供者接口。能力定义见[构建提供者](../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 实现了全部入口;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 的端到端测试验证,插件作者在桌面端界面里暂时看不到测试、运行和调试这几类入口的效果。 @@ -82,7 +82,7 @@ node --test shared/plugins/scripts/*.test.mjs node shared/plugins/scripts/sdk-e2e.mjs ``` -`sdk-e2e.mjs` 先构建三个 SDK 的示例后端,再用 `cargo test -p lithe-core --features plugin-sdk-e2e` 运行 `plugin_sdk_node`、`plugin_sdk_java`、`plugin_sdk_rust` 和 `plugin_sdk_build`,被测对象是当前工作树里的 Core,所以改 Core 与改 SDK 或契约可以在同一个 PR 里一起验证。运行需要 Rust、Node.js 20.3 或更高版本、Java(用 `LITHE_PLUGIN_SDK_JAVA_RUNTIME` 指定,或放在 `PATH` 上的 `java`)和 Maven。 +`sdk-e2e.mjs` 先构建四个 SDK 的示例后端,再用 `cargo test -p lithe-core --features plugin-sdk-e2e` 运行 `plugin_sdk_node`、`plugin_sdk_java`、`plugin_sdk_rust`、`plugin_sdk_go` 和 `plugin_sdk_build`,被测对象是当前工作树里的 Core,所以改 Core 与改 SDK 或契约可以在同一个 PR 里一起验证。运行需要 Rust、Node.js 20.3 或更高版本、Go 1.22 或更高版本、Java(用 `LITHE_PLUGIN_SDK_JAVA_RUNTIME` 指定,或放在 `PATH` 上的 `java`)和 Maven。 这些测试通过真实 Core 规划与解码,覆盖构建非零退出码、精确筛选、运行前构建、准备计划、进度、取消后的工具清理、并行工作区隔离,以及包含 SDK 和 JAR 的完整包文件不变。它们不代替原生界面、真实 Maven/JDT 工程或桌面端实机验证。 @@ -104,7 +104,7 @@ 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 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. +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. > **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. @@ -180,7 +180,7 @@ node --test shared/plugins/scripts/*.test.mjs node shared/plugins/scripts/sdk-e2e.mjs ``` -`sdk-e2e.mjs` first builds the three SDKs' sample backends, then runs `plugin_sdk_node`, `plugin_sdk_java`, `plugin_sdk_rust`, and `plugin_sdk_build` with `cargo test -p lithe-core --features plugin-sdk-e2e`. The code under test is the Core in the working tree, so a change to Core and a change to an SDK or the contract are verified together in one PR. It needs Rust, Node.js 20.3 or newer, Java (set with `LITHE_PLUGIN_SDK_JAVA_RUNTIME`, or `java` on `PATH`), and Maven. +`sdk-e2e.mjs` first builds the four SDKs' sample backends, then runs `plugin_sdk_node`, `plugin_sdk_java`, `plugin_sdk_rust`, `plugin_sdk_go`, and `plugin_sdk_build` with `cargo test -p lithe-core --features plugin-sdk-e2e`. The code under test is the Core in the working tree, so a change to Core and a change to an SDK or the contract are verified together in one PR. It needs Rust, Node.js 20.3 or newer, Go 1.22 or newer, Java (set with `LITHE_PLUGIN_SDK_JAVA_RUNTIME`, or `java` on `PATH`), and Maven. These tests plan and decode through a real Core and cover a non-zero build exit code, exact filtering, build before run, preparation plans, progress, tool cleanup after cancellation, isolation between parallel workspaces, and an unchanged complete package including the SDK and JAR. They do not replace verification of the native UI, real Maven/JDT projects, or the desktop on a real machine. diff --git a/shared/plugins/guides/native-terminals.md b/shared/plugins/guides/native-terminals.md index 9ae0cc50..cec98b4c 100644 --- a/shared/plugins/guides/native-terminals.md +++ b/shared/plugins/guides/native-terminals.md @@ -4,7 +4,7 @@ ## 中文 -这些 SDK 封装随 Node.js SDK 0.5.0、Java SDK 0.5.0 和 Rust SDK 0.4.0 提供,并且需要宿主声明终端方法。契约和 SDK 都在 Core 仓库的 `shared/plugins/` 中,规则见[原生终端契约](../contract/v1/README.md#plugin-owned-native-terminals)。 +这些 SDK 封装随 Node.js SDK 0.5.0、Java SDK 0.5.0 和 Rust SDK 0.4.0 提供,Go SDK 也有(还没有发布标签),并且需要宿主声明终端方法。契约和 SDK 都在 Core 仓库的 `shared/plugins/` 中,规则见[原生终端契约](../contract/v1/README.md#plugin-owned-native-terminals)。 交互式客户端请使用宿主的集成终端。声明 `requires.backend: 2` 和权限 `terminal.create`;网页调用自己后端的函数,后端带着该函数的工作区上下文调用宿主。插件不需要实现终端模拟器,不需要通过插件函数转发按键,也不需要成为构建或运行提供者。 @@ -60,6 +60,47 @@ terminal.dispose(workspace, id)?; Rust 还提供 `terminal.on_exit(workspace,id)`,返回 SDK 已有的 `Subscription`,用有界的 `recv_timeout` 接收,并显式调用 `dispose`。 +### Go 示例 + +```go +workspace := call.WorkspaceContext() +if workspace == nil { + return nil, lithe.NewPluginError("example.noWorkspace", "Open a workspace first.") +} +host := call.Host() +if supported, err := host.Supports("lithe/host/terminal/reopen"); err != nil { + return nil, err +} else if !supported { + return nil, lithe.NewPluginError("example.unavailable", "This host has no native terminal API.") +} +terminal := host.Terminal() +answer, err := terminal.Create(*workspace, map[string]any{ + "executable": "example-client", "arguments": []string{"--interactive"}, + "retainedContextBytes": 4096, +}) +if err != nil { + return nil, err +} +var opened struct { + TerminalID string `json:"terminalID"` +} +if err := json.Unmarshal(answer, &opened); err != nil || opened.TerminalID == "" { + return nil, errors.New("host returned no terminalID") +} +id := opened.TerminalID +if _, err := terminal.Close(*workspace, id, 4096); err != nil { + return nil, err +} +if _, err := terminal.Reopen(*workspace, id); err != nil { + return nil, err +} +if _, err := terminal.Dispose(*workspace, id); err != nil { + return nil, err +} +``` + +Go 还提供 `terminal.OnExit(workspace, id)`,返回 SDK 已有的 `*Subscription`,用有界的 `RecvTimeout` 接收,并显式调用 `Dispose`。 + ### Java 接口 `host.terminal()` 提供 `create(context,params)`、`show(context,params)`、`close(context,params)`、`reopen(context,params)`、`dispose(context,params)` 和 `onExit(context,params)`。参数是普通的 JSON Map。前五个返回 `CompletableFuture>`(show 和 dispose 返回 null);`onExit` 返回 `CompletableFuture`。上下文、取消、宿主失败和订阅路由与其他协议 3 方法使用同一通道。 @@ -74,7 +115,7 @@ Rust 还提供 `terminal.on_exit(workspace,id)`,返回 SDK 已有的 `Subscrip `dispose` 忘掉句柄、启动设置和历史;会话仍在运行时先关闭它。每个插件最多保留 8 个句柄(包括已关闭的),所以不会再 reopen 的句柄要 dispose。后端或会话重启、插件停用或更新、关闭或替换工作区,也会释放这些句柄。上下文和历史只在内存中,从不写入已安装的插件包。 -Rust 示例的 `terminal.cycle` 函数和 Core 端到端场景覆盖协议的往返。该场景由测试提供宿主应答;真实的原生 PTY 输入、输出和历史由宿主自己的测试验证。 +Rust 和 Go 示例的 `terminal.cycle` 函数和 Core 端到端场景覆盖协议的往返。该场景由测试提供宿主应答;真实的原生 PTY 输入、输出和历史由宿主自己的测试验证。 终端生命周期场景在 Core 仓库根目录运行,对象是当前工作树的 Core: @@ -89,7 +130,7 @@ node shared/plugins/scripts/sdk-e2e.mjs ## English These SDK wrappers ship from Node.js SDK 0.5.0, Java SDK 0.5.0, and Rust SDK -0.4.0, and require a host that advertises the terminal methods. The contract and the SDKs live in the +0.4.0, are in the Go SDK too (not tagged yet), and require a host that advertises the terminal methods. The contract and the SDKs live in the Core repository under `shared/plugins/`. See the [native terminal contract](../contract/v1/README.md#plugin-owned-native-terminals). @@ -162,6 +203,48 @@ terminal.dispose(workspace, id)?; Rust also exposes `terminal.on_exit(workspace,id)` as an existing SDK `Subscription`, with bounded `recv_timeout` and explicit `dispose`. +### Go + +```go +workspace := call.WorkspaceContext() +if workspace == nil { + return nil, lithe.NewPluginError("example.noWorkspace", "Open a workspace first.") +} +host := call.Host() +if supported, err := host.Supports("lithe/host/terminal/reopen"); err != nil { + return nil, err +} else if !supported { + return nil, lithe.NewPluginError("example.unavailable", "This host has no native terminal API.") +} +terminal := host.Terminal() +answer, err := terminal.Create(*workspace, map[string]any{ + "executable": "example-client", "arguments": []string{"--interactive"}, + "retainedContextBytes": 4096, +}) +if err != nil { + return nil, err +} +var opened struct { + TerminalID string `json:"terminalID"` +} +if err := json.Unmarshal(answer, &opened); err != nil || opened.TerminalID == "" { + return nil, errors.New("host returned no terminalID") +} +id := opened.TerminalID +if _, err := terminal.Close(*workspace, id, 4096); err != nil { + return nil, err +} +if _, err := terminal.Reopen(*workspace, id); err != nil { + return nil, err +} +if _, err := terminal.Dispose(*workspace, id); err != nil { + return nil, err +} +``` + +Go also exposes `terminal.OnExit(workspace, id)` as an existing SDK +`*Subscription`, with bounded `RecvTimeout` and explicit `Dispose`. + ### Java `host.terminal()` exposes `create(context,params)`, `show(context,params)`, @@ -204,7 +287,7 @@ handles that will not be reopened. A backend/session restart, plugin disable or update, and closing/replacing the workspace also release them. Context and history are in-memory only and never written to the installed package. -The Rust sample's `terminal.cycle` function and Core end-to-end scenario exercise +The Rust and Go samples' `terminal.cycle` functions and Core end-to-end scenario exercise the protocol roundtrip. That scenario supplies host responses; the host's own tests verify actual native PTY input and output/history. diff --git a/shared/plugins/guides/plugin-backend-workspace.md b/shared/plugins/guides/plugin-backend-workspace.md index cb901a01..20e3181f 100644 --- a/shared/plugins/guides/plugin-backend-workspace.md +++ b/shared/plugins/guides/plugin-backend-workspace.md @@ -10,9 +10,9 @@ > **宿主支持。** Lithe 桌面端声明 `backend` 和 `pluginFunctions`(版本都是 `0`),所以本篇的函数协议、宿主服务和跨插件调用都在桌面端运行。宿主只授予它实现了的服务:一次会话能调用哪些方法,以运行时 `lithe/host/getCapabilities` 的 `services` 为准,不要按文档假定(第 5 节、第 10 节)。桌面端的声明和说明见 > [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/main/desktop/internal/pluginhost/pluginhost.go) 中 `Declared()` 上方的注释。 -> 三个官方 SDK 都实现了本篇的协议:Node.js SDK 0.5.0、Java SDK 0.5.0 和 Rust SDK 0.4.0 +> 四个官方 SDK 都实现了本篇的协议:Node.js SDK 0.5.0、Java SDK 0.5.0、Rust SDK 0.4.0 和 Go SDK(还没有发布标签) > (见各自 README 的 Host services:[Node.js](../sdk/node/README.md#host-services)、[Java](../sdk/java/README.md#host-services)、 -> [Rust](../sdk/rust/README.md#host-services);发布页:[sdk-node-v0.5.0](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-node-v0.5.0)、 +> [Rust](../sdk/rust/README.md#host-services)、[Go](../sdk/go/README.md#host-services);发布页:[sdk-node-v0.5.0](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-node-v0.5.0)、 > [sdk-java-v0.5.0](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-java-v0.5.0)、 > [sdk-rust-v0.4.0](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-rust-v0.4.0))。用其他语言需要自己处理下文的请求和通知。 > 各能力在 Core 和桌面端的支持情况见[能力与协议版本对照](../reference/capabilities-and-versions.md)。对契约有疑问,请到 @@ -333,9 +333,9 @@ The [contract](../contract/v1/README.md#backend-lifecycle-and-workspace-contexts > **Host support.** The Lithe desktop declares `backend` and `pluginFunctions` (both version `0`), so the function protocol, host services, and cross-plugin calls in this guide run there. The host grants only the services it implements: which methods a session can call is decided by `services` in the run-time `lithe/host/getCapabilities` answer, so do not assume it from this document (sections 5 and 10). The desktop's 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). -> All three official SDKs implement the protocol in this guide: Node.js SDK 0.5.0, Java SDK 0.5.0, and Rust SDK 0.4.0 +> All four official SDKs implement the protocol in this guide: Node.js SDK 0.5.0, Java SDK 0.5.0, Rust SDK 0.4.0, and the Go SDK (not tagged yet) > (see Host services in each README: [Node.js](../sdk/node/README.md#host-services), [Java](../sdk/java/README.md#host-services), -> [Rust](../sdk/rust/README.md#host-services); release pages: [sdk-node-v0.5.0](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-node-v0.5.0), +> [Rust](../sdk/rust/README.md#host-services), [Go](../sdk/go/README.md#host-services); release pages: [sdk-node-v0.5.0](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-node-v0.5.0), > [sdk-java-v0.5.0](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-java-v0.5.0), > [sdk-rust-v0.4.0](https://github.com/Lithe-IDEA/Lithe-core-rust/releases/tag/sdk-rust-v0.4.0)). With another language, handle the requests and notifications below yourself. > For how far Core and the desktop support each capability, see the [capability and protocol versions](../reference/capabilities-and-versions.md). Questions about the contract go to diff --git a/shared/plugins/guides/plugin-logging.md b/shared/plugins/guides/plugin-logging.md index cbf7463c..f422defb 100644 --- a/shared/plugins/guides/plugin-logging.md +++ b/shared/plugins/guides/plugin-logging.md @@ -4,11 +4,11 @@ ## 中文 -插件使用 `litheLogging` 0 与 `lithe/log` 发送受限的操作事实,由宿主的共享事件目录、脱敏、队列和文件写入器落盘。三个 SDK 不提供自由文本 `log` 接口,也没有 stderr 回退。插件无需实现日志文件格式、文件轮转、脱敏器或后台写入线程。 +插件使用 `litheLogging` 0 与 `lithe/log` 发送受限的操作事实,由宿主的共享事件目录、脱敏、队列和文件写入器落盘。官方 SDK 都不提供自由文本 `log` 接口,也没有 stderr 回退。插件无需实现日志文件格式、文件轮转、脱敏器或后台写入线程。 宿主必须在 initialize 中提供 `capabilities.experimental.litheLogging.versions: [0]`,SDK 回复 `capabilities.experimental.litheLogging.version: 0`。缺少协议时,SDK 拒绝初始化;不自动退回其他日志方式。初始化尚未协商时的失败只通过原有 RPC 错误与宿主进程生命周期记录,不能提前发送未协商的日志通知。 -本文的 API 由 Node.js SDK 0.5.0、Java SDK 0.5.0 和 Rust SDK 0.4.0 提供,发布标签分别为 `sdk-node-v0.5.0`、`sdk-java-v0.5.0` 和 `sdk-rust-v0.4.0`。插件在构建输入中锁定对应的 release tag 与 SHA-256,不要引用开发机的绝对 path 依赖。这些 SDK 要求宿主提供 `litheLogging` 0;在提供它的 Lithe 稳定版发布之前,用这些 SDK 构建的插件把 GitHub Release 标为预发布。 +本文的 API 由 Node.js SDK 0.5.0、Java SDK 0.5.0、Rust SDK 0.4.0 和 Go SDK 提供,前三个的发布标签分别为 `sdk-node-v0.5.0`、`sdk-java-v0.5.0` 和 `sdk-rust-v0.4.0`;Go SDK 的版本是模块标签 `shared/plugins/sdk/go/v<版本>`,目前还没有打过标签。插件在构建输入中锁定对应的 release tag 与 SHA-256(Go 由 `go.sum` 锁定),不要引用开发机的绝对 path 依赖。这些 SDK 要求宿主提供 `litheLogging` 0;在提供它的 Lithe 稳定版发布之前,用这些 SDK 构建的插件把 GitHub Release 标为预发布。 ### 每种事实与级别 @@ -21,11 +21,11 @@ `operationFinished` 和 `operationFailed` 必须有单调时钟计算的 `durationMs`。失败、降级、恢复使用受控的 `code`;成功没有 `code`。可选 `count` 与 `durationMs` 都是 0…9007199254740991 的整数。API 不接受原始 message、stack、request、URL、SQL、命令输出或字段字典。 -`operation` 只接受本 SDK 已注册的函数 ID 或封闭协议操作,超过 64 字节的已注册函数 ID 统一为 `function-call`。公开的协议操作包括 initialize/shutdown/notification/function-call/result-encoding、SDK 已知的 `lithe/build/*` 与 `lithe/vcs/*` 方法,以及快捷键导入请求 `lithe/keymap/import`(三种 SDK 自动上报其终态);任意用户文本即使字符合法也不接受。`code` 是最长 64 字节的 ASCII 类别标识,不是错误正文。 +`operation` 只接受本 SDK 已注册的函数 ID 或封闭协议操作,超过 64 字节的已注册函数 ID 统一为 `function-call`。公开的协议操作包括 initialize/shutdown/notification/function-call/result-encoding、SDK 已知的 `lithe/build/*` 与 `lithe/vcs/*` 方法,以及快捷键导入请求 `lithe/keymap/import`(实现它的 SDK 自动上报其终态);任意用户文本即使字符合法也不接受。`code` 是最长 64 字节的 ASCII 类别标识,不是错误正文。 通道由宿主从已校验的安装插件 ID 得到 `plugins//host`,插件不能更改通道或拼接路径。上下文诊断优先携带宿主原始 `operationID`,缺少合法值时沿用当前请求原始 JSON-RPC ID(安全字符串或整数的十进制字符串),wire 名为 `operationId`,只保留最长 128 字节的受控 ASCII 标识;无真实身份时省略。通知没有请求 ID,不生成回退身份。后台共享任务可以使用 backend/handle 的无 op 诊断,不能伪造一个操作 ID。 -### 三个 SDK 的用法 +### 各 SDK 的用法 ```js backend.function('project.refresh', async (params, context) => { @@ -51,14 +51,28 @@ handle.diagnostics().recovered("query.run", "connection_restored", None)?; backend.suppress_success_diagnostics("query.inspect")?; ``` -`degraded`、`recovered` 的 operation 必须已注册,静态示例需要放到实际的注册完成之后。Rust 的返回错误只表达调用参数非法;协议写入复用现有 writer,诊断传输失败不会把已经成功的用户操作改成失败。没有额外 writer 或后台队列。 +```go +if err := call.Diagnostics().Degraded("query.run", "rows_truncated", 1); err != nil { + return nil, err +} +if err := handle.Diagnostics().Recovered("query.run", "connection_restored"); err != nil { + return err +} +if err := backend.SuppressSuccessDiagnostics("query.inspect"); err != nil { + return err +} +``` + +`degraded`、`recovered` 的 operation 必须已注册,静态示例需要放到实际的注册完成之后。Rust 和 Go 返回的错误只表示调用参数非法;协议写入复用现有 writer,诊断传输失败不会把已经成功的用户操作改成失败。没有额外 writer 或后台队列。 -混合用户操作和高频读取的单个入口可以在当前调用上使用 `context.suppressSuccessDiagnostics()`(Rust 为 `context.suppress_success_diagnostics()`);该决定只影响本次成功事实,不影响其他调用与失败。 +混合用户操作和高频读取的单个入口可以在当前调用上使用 `context.suppressSuccessDiagnostics()`(Rust 为 `context.suppress_success_diagnostics()`,Go 为 `call.SuppressSuccessDiagnostics()`);该决定只影响本次成功事实,不影响其他调用与失败。 -SDK 在函数与受管 build/VCS 请求的结果边界自动发送一次终态,通知在 RPC 响应之前发送,宿主才能关联仍活动的请求。不要在处理函数里先发送失败再返回或抛出同一次失败。取消不产生失败事件,正常缺失的收尾对象不应产生 WARN。高频只读、预览、统计与轮询通过 `suppressSuccessDiagnostics` / `suppress_success_diagnostics` 关闭成功事实;失败与真正降级仍保留。 +SDK 在函数与受管 build/VCS 请求的结果边界自动发送一次终态,通知在 RPC 响应之前发送,宿主才能关联仍活动的请求。不要在处理函数里先发送失败再返回或抛出同一次失败。取消不产生失败事件,正常缺失的收尾对象不应产生 WARN。高频只读、预览、统计与轮询通过 `suppressSuccessDiagnostics` / `suppress_success_diagnostics` / `SuppressSuccessDiagnostics` 关闭成功事实;失败与真正降级仍保留。 Rust SDK 用一次安装的 panic hook 包装器,仅在线程处于 SDK 拥有的 catch 边界时屏蔽原始 payload 输出,随后发送固定 `panic` 类别。其他线程和边界外的 panic 继续执行原 hook。不要把用户内容放进 panic,插件也不要在 SDK 启动后替换该 hook 来恢复正文输出。 +Go SDK 在函数调用、快捷键导入调用、通知与命令处理函数、`OnInitialize` 和 `OnShutdown` 外层 `recover`:不输出 panic 的值,只发送固定的 `panic` 类别。插件自己启动的 goroutine 不在这个边界内,其中未恢复的 panic 按 Go 的默认行为打印并结束后端进程。 + ### 上游诊断与文件位置 上游语言服务器的 stderr、`window/logMessage` 继续由宿主接收;它们不是插件自己的结构化日志入口。插件不得把源码、协议载荷、SQL、HTTP body 或构建输出复制进上游诊断,以为脱敏与截断能使其安全。控制台输出走已有 Build、Run、Test、VCS 或插件界面结果。 @@ -86,11 +100,11 @@ Rust SDK 用一次安装的 panic hook 包装器,仅在线程处于 SDK 拥有 ## English -Plugins use `litheLogging` 0 and `lithe/log` to send restricted operation facts. The host's shared event catalog, redaction, queue, and file writer persist them. The three SDKs offer no free-text `log` interface and have no stderr fallback. A plugin does not implement the log file format, file rotation, a redactor, or a background writer thread. +Plugins use `litheLogging` 0 and `lithe/log` to send restricted operation facts. The host's shared event catalog, redaction, queue, and file writer persist them. None of the official SDKs offers a free-text `log` interface and have no stderr fallback. A plugin does not implement the log file format, file rotation, a redactor, or a background writer thread. The host must offer `capabilities.experimental.litheLogging.versions: [0]` in initialize, and the SDK replies with `capabilities.experimental.litheLogging.version: 0`. When the protocol is missing, the SDK refuses to initialize; it does not fall back to another logging path. A failure before initialization has negotiated logging is recorded only through the existing RPC error and the host's process lifecycle; the plugin must not send a log notification before negotiation. -The APIs in this guide are provided by Node.js SDK 0.5.0, Java SDK 0.5.0, and Rust SDK 0.4.0, with release tags `sdk-node-v0.5.0`, `sdk-java-v0.5.0`, and `sdk-rust-v0.4.0`. Pin the matching release tag and SHA-256 in your build inputs; do not depend on an absolute path on a development machine. These SDKs require the host to offer `litheLogging` 0; until a stable Lithe release offers it, mark the GitHub Release of a plugin built with these SDKs as a prerelease. +The APIs in this guide are provided by Node.js SDK 0.5.0, Java SDK 0.5.0, Rust SDK 0.4.0, and the Go SDK. The first three have release tags `sdk-node-v0.5.0`, `sdk-java-v0.5.0`, and `sdk-rust-v0.4.0`; the Go SDK's versions are the module tags `shared/plugins/sdk/go/v`, and none has been pushed yet. Pin the matching release tag and SHA-256 in your build inputs (for Go, `go.sum` pins it); do not depend on an absolute path on a development machine. These SDKs require the host to offer `litheLogging` 0; until a stable Lithe release offers it, mark the GitHub Release of a plugin built with these SDKs as a prerelease. ### Facts and levels @@ -103,11 +117,11 @@ The APIs in this guide are provided by Node.js SDK 0.5.0, Java SDK 0.5.0, and Ru `operationFinished` and `operationFailed` must carry a `durationMs` measured with a monotonic clock. Failure, degradation, and recovery use a controlled `code`; success has no `code`. The optional `count` and `durationMs` are integers from 0 to 9007199254740991. The API does not accept raw messages, stacks, requests, URLs, SQL, command output, or field dictionaries. -`operation` accepts only function IDs registered with this SDK or closed protocol operations; a registered function ID longer than 64 bytes is reported as `function-call`. The public protocol operations are initialize, shutdown, notification, function-call, and result-encoding, the `lithe/build/*` and `lithe/vcs/*` methods the SDK knows, and the shortcut import request `lithe/keymap/import` (all three SDKs report its end state automatically). Arbitrary user text is not accepted even when its characters are valid. `code` is an ASCII category identifier of at most 64 bytes, not an error message. +`operation` accepts only function IDs registered with this SDK or closed protocol operations; a registered function ID longer than 64 bytes is reported as `function-call`. The public protocol operations are initialize, shutdown, notification, function-call, and result-encoding, the `lithe/build/*` and `lithe/vcs/*` methods the SDK knows, and the shortcut import request `lithe/keymap/import` (every SDK that implements it reports its end state automatically). Arbitrary user text is not accepted even when its characters are valid. `code` is an ASCII category identifier of at most 64 bytes, not an error message. The host derives the channel `plugins//host` from the validated installed plugin ID; the plugin cannot change the channel or build a path. Contextual diagnostics carry the host's original `operationID` first; without a valid one they reuse the current request's original JSON-RPC ID (a safe string, or an integer as a decimal string). The wire name is `operationId`, and only a controlled ASCII identifier of at most 128 bytes is kept; it is omitted when there is no real identity. Notifications have no request ID, and no fallback identity is generated for them. Shared background work can use the backend or handle diagnostics without an operation, but must not invent an operation ID. -### Using the three SDKs +### Using each SDK ```js backend.function('project.refresh', async (params, context) => { @@ -133,14 +147,28 @@ handle.diagnostics().recovered("query.run", "connection_restored", None)?; backend.suppress_success_diagnostics("query.inspect")?; ``` -The operation passed to `degraded` and `recovered` must be registered, so put static examples after registration has actually finished. A Rust error return means only that the call's arguments are invalid. Protocol writes reuse the existing writer, and a failed diagnostic send never turns a successful user operation into a failure. There is no extra writer or background queue. +```go +if err := call.Diagnostics().Degraded("query.run", "rows_truncated", 1); err != nil { + return nil, err +} +if err := handle.Diagnostics().Recovered("query.run", "connection_restored"); err != nil { + return err +} +if err := backend.SuppressSuccessDiagnostics("query.inspect"); err != nil { + return err +} +``` + +The operation passed to `degraded` and `recovered` must be registered, so put static examples after registration has actually finished. A Rust or Go error return means only that the call's arguments are invalid. Protocol writes reuse the existing writer, and a failed diagnostic send never turns a successful user operation into a failure. There is no extra writer or background queue. -A single entry point that mixes user operations with high-frequency reads can call `context.suppressSuccessDiagnostics()` (in Rust, `context.suppress_success_diagnostics()`) for the current call. That decision affects only this call's success fact, not other calls or failures. +A single entry point that mixes user operations with high-frequency reads can call `context.suppressSuccessDiagnostics()` (in Rust, `context.suppress_success_diagnostics()`; in Go, `call.SuppressSuccessDiagnostics()`) for the current call. That decision affects only this call's success fact, not other calls or failures. -The SDK sends one end state automatically at the result boundary of functions and managed build and VCS requests. The notification goes out before the RPC response so the host can relate it to the still-active request. Do not send a failure from a handler and then return or throw the same failure. Cancellation produces no failure event, and a normally absent cleanup object should not produce a WARN. High-frequency reads, previews, statistics, and polling turn off success facts with `suppressSuccessDiagnostics` / `suppress_success_diagnostics`; failures and real degradations are kept. +The SDK sends one end state automatically at the result boundary of functions and managed build and VCS requests. The notification goes out before the RPC response so the host can relate it to the still-active request. Do not send a failure from a handler and then return or throw the same failure. Cancellation produces no failure event, and a normally absent cleanup object should not produce a WARN. High-frequency reads, previews, statistics, and polling turn off success facts with `suppressSuccessDiagnostics` / `suppress_success_diagnostics` / `SuppressSuccessDiagnostics`; failures and real degradations are kept. The Rust SDK installs a panic hook wrapper once. It suppresses the raw payload output only while the thread is inside a catch boundary the SDK owns, and then sends the fixed `panic` category. Panics on other threads and outside the boundary still run the original hook. Do not put user content in a panic, and do not replace the hook after the SDK starts to restore message output. +The Go SDK wraps function calls, shortcut import calls, notification and command handlers, `OnInitialize`, and `OnShutdown` in `recover`: it prints nothing of the panic value and sends only the fixed `panic` category. Goroutines the plugin starts itself are outside that boundary; an unrecovered panic there prints and ends the backend process, as Go always does. + ### Upstream diagnostics and file locations The host still receives an upstream language server's stderr and `window/logMessage`; they are not the plugin's own structured logging path. A plugin must not copy source code, protocol payloads, SQL, HTTP bodies, or build output into upstream diagnostics in the belief that redaction and truncation make them safe. Console output goes through the existing Build, Run, Test, VCS, or plugin UI results. diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 4962b457..02622547 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -83,7 +83,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I 后端向宿主发送的请求,前缀都是 `lithe/host/`,下表省略前缀。一个 API 编号下可以有多个方法,每个方法单独一行,按 API 编号排列。 - **“API”列是规划编号**,来自 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md),和“协议”列的 `litheFunctions` 版本、清单里的能力版本分开记录。同一个 API 的方法可以分几个 PR 陆续加入;向后兼容地新增方法不升协议版本(见契约 [Extending the host services](../contract/v1/README.md#extending-the-host-services))。每个方法哪天、由哪个 PR 首次加入,见[插件协议更新记录](protocol-changelog.md#宿主方法按-api-编号)。 -- **“协议”列**是方法所属的 `litheFunctions` 版本,现在都是 0。除 `getCapabilities`、`subscriptions/dispose`、`workspace/listContexts`、`credentials/*`、`run/stop`、`functions/providers` 外,其余方法都要带 `context: {contextID, generation}`。`functions/*` 只对声明了至少一个 `calls` 的后端开放;三个官方 SDK 都已封装 `functions/providers` 和 `functions/invoke`。 +- **“协议”列**是方法所属的 `litheFunctions` 版本,现在都是 0。除 `getCapabilities`、`subscriptions/dispose`、`workspace/listContexts`、`credentials/*`、`run/stop`、`functions/providers` 外,其余方法都要带 `context: {contextID, generation}`。`functions/*` 只对声明了至少一个 `calls` 的后端开放;官方 SDK 都已封装 `functions/providers` 和 `functions/invoke`。 - **“权限”列**:每个权限都要求清单声明 `backend`(`requires.backend` 为 0),否则安装时拒绝。`functions/*` 没有清单权限,由清单 `pluginFunctions` 段的 `calls` 是否声明了该函数决定。另有两条前置条件:`debug.start` 还要求已声明的 `debugAdapters` 条目;`languageServer.request` 只在某个语言服务器列出 `requestMethods` 或 `forwardNotifications` 时才能声明。 | API | 方法 | 用途 | 权限 | 协议 | @@ -255,7 +255,7 @@ The manifest, marketplace, package trust, and shortcut import are installation a Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omit the prefix. One API ID can cover several methods; each method has its own row, ordered by API ID. - **The “API” column holds planning IDs** from the [API implementation plan](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md). They are recorded separately from the `litheFunctions` version in the “Protocol” column and from manifest capability versions. The methods of one API can arrive over several PRs, and adding a backward-compatible method does not bump the protocol version (see [Extending the host services](../contract/v1/README.md#extending-the-host-services) in the contract). The date and PR that first added each method are in the [protocol changelog](protocol-changelog.md#宿主方法按-api-编号) (Chinese only). -- **The “Protocol” column** is the `litheFunctions` version the method belongs to, and is 0 for every method today. Apart from `getCapabilities`, `subscriptions/dispose`, `workspace/listContexts`, `credentials/*`, `run/stop`, and `functions/providers`, every method takes `context: {contextID, generation}`. `functions/*` is open only to a backend whose plugin declares at least one `calls` entry; the three official SDKs all wrap `functions/providers` and `functions/invoke`. +- **The “Protocol” column** is the `litheFunctions` version the method belongs to, and is 0 for every method today. Apart from `getCapabilities`, `subscriptions/dispose`, `workspace/listContexts`, `credentials/*`, `run/stop`, and `functions/providers`, every method takes `context: {contextID, generation}`. `functions/*` is open only to a backend whose plugin declares at least one `calls` entry; the official SDKs all wrap `functions/providers` and `functions/invoke`. - **The “Permission” column**: every permission requires the manifest to declare `backend` (`requires.backend` is 0), or installation refuses it. `functions/*` has no manifest permission; whether the manifest's `pluginFunctions` section lists the function under `calls` decides. Two more preconditions: `debug.start` also requires a declared `debugAdapters` entry, and `languageServer.request` can be declared only when a language server lists `requestMethods` or `forwardNotifications`. | API | Method | Purpose | Permission | Protocol | diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 09ac4cd5..693f2cb7 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -112,7 +112,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https ### 官方 SDK -Node.js SDK 0.5.0、Java SDK 0.5.0 和 Rust SDK 0.4.0 说的是版本 `0` 的协议;`main` 上的 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) README。下载地址在 [Lithe-core-rust 的 Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases)。 +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)。 --- @@ -226,4 +226,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, and Rust SDK 0.4.0 speak the version `0` protocols; the 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), and [Rust](../sdk/rust/README.md) READMEs. Downloads are on the [Lithe-core-rust Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases) page. +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. diff --git a/shared/plugins/reference/domains/backend.md b/shared/plugins/reference/domains/backend.md index 4ba0513d..db7c52ae 100644 --- a/shared/plugins/reference/domains/backend.md +++ b/shared/plugins/reference/domains/backend.md @@ -20,7 +20,7 @@ | API 编号 | API-01、04、05、06、07、08、20、21、22、23、24、35、37、40、41,见 [API 总表](../api-catalog.md#现在能用的-api) | | 权限 | `backend.launch`;宿主服务按方法另加权限(`credentials.store`、`workspace.metadata`、`workspace.files.read`、`workspace.files.watch`、`workspace.search`、`terminal.create`、`run.start` 等),见[已公开的宿主方法](../api-catalog.md#已公开的宿主方法)。跨插件调用没有清单权限:调用方的 `calls` 和被调方的 `exports` 就是双方的同意 | | 激活事件 | 至少要有一种启动方式:网页工具窗口第一次调用 `functions.*`;`ui.commands[]` 的命令(`onCommand:`);可选的 `onWorkspaceOpen`;或宿主查询的提供者(工具链或快捷键导入提供者,以及 `launch.kind: "backend"` 的语言服务器)。都没有是 `plugin.manifest.invalid`。只导出函数的插件不需要网页、命令或 `onWorkspaceOpen`,被调用时启动后端;只调用的插件仍要有其中一种 | -| 官方 SDK | [Node.js 0.5.0](../../sdk/node/README.md)、[Java 0.5.0](../../sdk/java/README.md)、[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 都实现函数协议,封装凭据、工作区、文档与编辑器(含 `editor/registerActions`)、预览、浏览器、窗口消息、`functions/providers` 和 `functions/invoke`,被调函数能读到 `caller`,用法见各 SDK 的 README;`parentOperationID` 不传时,SDK 取正在处理的 `lithe/function/invoke` 的 `operationID`。`run/*`、`debug/start`、`languageServer/*`、`documents/registerContentProvider` 和 `editor/registerProviders` 没有专门的封装,用 SDK 的通用宿主请求(`request`)调用。原生终端有封装,见[从插件打开原生终端](../../guides/native-terminals.md) | +| 官方 SDK | [Node.js 0.5.0](../../sdk/node/README.md)、[Java 0.5.0](../../sdk/java/README.md)、[Rust 0.4.0](../../sdk/rust/README.md)、[Go](../../sdk/go/README.md)(未发布),发布标签 `sdk-node-v0.5.0`、`sdk-java-v0.5.0`、`sdk-rust-v0.4.0`,Go 用模块标签 `shared/plugins/sdk/go/v<版本>`(还没有推送),见[官方 SDK](../capabilities-and-versions.md#官方-sdk)。四个 SDK 都实现函数协议,封装凭据、工作区、文档与编辑器(含 `editor/registerActions`)、预览、浏览器、窗口消息、`functions/providers` 和 `functions/invoke`,被调函数能读到 `caller`,用法见各 SDK 的 README;`parentOperationID` 不传时,SDK 取正在处理的 `lithe/function/invoke` 的 `operationID`。`run/*`、`debug/start`、`languageServer/*`、`documents/registerContentProvider` 和 `editor/registerProviders` 没有专门的封装,用 SDK 的通用宿主请求(`request`,Go 是 `Request`)调用。原生终端有封装,见[从插件打开原生终端](../../guides/native-terminals.md) | ### 后端的启动与工作区 @@ -240,7 +240,7 @@ A plugin backend is the plugin's own long-lived process. It runs what a web page | API IDs | API-01, 04, 05, 06, 07, 08, 20, 21, 22, 23, 24, 35, 37, 40, 41; see the [API catalog](../api-catalog.md#apis-usable-now) | | Permissions | `backend.launch`; host services need their own permission per method (`credentials.store`, `workspace.metadata`, `workspace.files.read`, `workspace.files.watch`, `workspace.search`, `terminal.create`, `run.start`, …); see [public host methods](../api-catalog.md#public-host-methods). Cross-plugin calls have no manifest permission: the caller's `calls` and the provider's `exports` are the consent of the two sides | | Activation | At least one way to start is required: a web tool window's first `functions.*` call; a `ui.commands[]` command (`onCommand:`); the optional `onWorkspaceOpen`; or a provider the host queries (a toolchain or keymap import provider, or a language server with `launch.kind: "backend"`). None of them is `plugin.manifest.invalid`. A plugin that only exports functions needs no page, command, or `onWorkspaceOpen`: a call starts its backend; a plugin that only calls still needs one of them | -| Official SDKs | [Node.js 0.5.0](../../sdk/node/README.md), [Java 0.5.0](../../sdk/java/README.md), [Rust 0.4.0](../../sdk/rust/README.md), 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). All three implement the function protocol and wrap credentials, workspaces, documents and editors (including `editor/registerActions`), preview, browser, window messages, `functions/providers`, and `functions/invoke`; a called function can read `caller`; see each SDK's README for usage. When `parentOperationID` is omitted, the SDK uses the `operationID` of the `lithe/function/invoke` being handled. `run/*`, `debug/start`, `languageServer/*`, `documents/registerContentProvider`, and `editor/registerProviders` have no dedicated wrappers; call them through the SDK's generic host request (`request`). Native terminals are wrapped; see [Open a native Lithe terminal from a plugin](../../guides/native-terminals.md) | +| Official SDKs | [Node.js 0.5.0](../../sdk/node/README.md), [Java 0.5.0](../../sdk/java/README.md), [Rust 0.4.0](../../sdk/rust/README.md), [Go](../../sdk/go/README.md) (unreleased), released as `sdk-node-v0.5.0`, `sdk-java-v0.5.0`, and `sdk-rust-v0.4.0`, with Go on module tags `shared/plugins/sdk/go/v` (none pushed yet); see [official SDKs](../capabilities-and-versions.md#official-sdks). All four implement the function protocol and wrap credentials, workspaces, documents and editors (including `editor/registerActions`), preview, browser, window messages, `functions/providers`, and `functions/invoke`; a called function can read `caller`; see each SDK's README for usage. When `parentOperationID` is omitted, the SDK uses the `operationID` of the `lithe/function/invoke` being handled. `run/*`, `debug/start`, `languageServer/*`, `documents/registerContentProvider`, and `editor/registerProviders` have no dedicated wrappers; call them through the SDK's generic host request (`request`, `Request` in Go). Native terminals are wrapped; see [Open a native Lithe terminal from a plugin](../../guides/native-terminals.md) | ### Backend start and workspaces diff --git a/shared/plugins/reference/domains/keymap-import.md b/shared/plugins/reference/domains/keymap-import.md index 0513123b..3dd91bda 100644 --- a/shared/plugins/reference/domains/keymap-import.md +++ b/shared/plugins/reference/domains/keymap-import.md @@ -16,7 +16,7 @@ | 激活事件 | 没有;宿主只在用户发起导入时启动后端 | | 后端启动 | 包内可执行文件或包内运行时,不能依赖需要发现的运行时 | | Lithe 桌面端 | 未声明 `keymapImportProviders`,也没有读取导入源的实现,安装时拒绝需要它的包 | -| 官方 SDK | [Node](../../sdk/node/README.md#shortcut-import-providers) 0.5.0、[Java](../../sdk/java/README.md#shortcut-import-providers) 0.5.0、[Rust](../../sdk/rust/README.md#shortcut-import-providers) 0.4.0 均实现 `litheKeymapImport` 0 | +| 官方 SDK | [Node](../../sdk/node/README.md#shortcut-import-providers) 0.5.0、[Java](../../sdk/java/README.md#shortcut-import-providers) 0.5.0、[Rust](../../sdk/rust/README.md#shortcut-import-providers) 0.4.0、[Go](../../sdk/go/README.md#shortcut-import-providers)(未发布)均实现 `litheKeymapImport` 0 | ### 声明与读取 @@ -65,7 +65,7 @@ A plugin can convert another editor's shortcut configuration into Lithe shortcut | Activation events | None; the host starts the backend only when the user starts an import | | Backend launch | A packaged executable or packaged runtime, without discovered runtime dependencies | | Lithe desktop | Does not declare `keymapImportProviders` and has no import source reader; packages that require it are refused before installation | -| Official SDKs | [Node](../../sdk/node/README.md#shortcut-import-providers) 0.5.0, [Java](../../sdk/java/README.md#shortcut-import-providers) 0.5.0, and [Rust](../../sdk/rust/README.md#shortcut-import-providers) 0.4.0 implement `litheKeymapImport` 0 | +| Official SDKs | [Node](../../sdk/node/README.md#shortcut-import-providers) 0.5.0, [Java](../../sdk/java/README.md#shortcut-import-providers) 0.5.0, [Rust](../../sdk/rust/README.md#shortcut-import-providers) 0.4.0, and [Go](../../sdk/go/README.md#shortcut-import-providers) (unreleased) implement `litheKeymapImport` 0 | ### Declaration and reading diff --git a/shared/plugins/reference/domains/toolchains.md b/shared/plugins/reference/domains/toolchains.md index 4c999db3..3134fefb 100644 --- a/shared/plugins/reference/domains/toolchains.md +++ b/shared/plugins/reference/domains/toolchains.md @@ -16,7 +16,7 @@ | 激活事件 | 不需要。提供者由宿主的第一次查询唤起,不需要页面或启动事件 | | 后端启动 | 提供者的后端只能是包内可执行文件(`packaged`),或包内运行时(`runtime` 加 `packagedRuntime`),不能依赖需要发现的运行时 | | 桌面端 | 声明 `toolDefinitions`;未声明 `toolchainProviders`,见“桌面端现状” | -| 官方 SDK | 三个官方 SDK 都还没有实现 `litheToolchains`,提供者后端要自己处理 `toolchains/query` | +| 官方 SDK | 官方 SDK 都还没有实现 `litheToolchains`,提供者后端要自己处理 `toolchains/query` | ### 两条安装来源 @@ -203,7 +203,7 @@ A plugin can tell Lithe what a tool (a JDK, Maven, Node, Go and so on) looks lik | Activation | None needed. The host's first query starts a provider; no page or startup event is needed | | Backend launch | The provider's backend must be `packaged`, or `runtime` with `packagedRuntime`, and must not depend on a discovered runtime | | Desktop | Declares `toolDefinitions`; does not declare `toolchainProviders`. See "Desktop status" | -| Official SDKs | None of the three official SDKs implements `litheToolchains` yet; a provider backend handles `toolchains/query` itself | +| Official SDKs | None of the official SDKs implements `litheToolchains` yet; a provider backend handles `toolchains/query` itself | ### Two installation routes diff --git a/shared/plugins/reference/domains/ui.md b/shared/plugins/reference/domains/ui.md index f9a9343c..3b0a427c 100644 --- a/shared/plugins/reference/domains/ui.md +++ b/shared/plugins/reference/domains/ui.md @@ -21,7 +21,7 @@ - **工具窗口**:1–64 个。每个窗口有稳定的 `id`、`title`、初始 `placement`(`left`、`bottom` 或 `right`)、整数 `order`(默认 0),以及且只能有一种内容:`text`(纯文本)、`web`(包内网页)或 `view`(插件视图)。 - **命令**:最多 128 个,`placements` 非空,取值为 `commandPalette`、`toolbar`、`menu`。带 `toolWindowID` 的命令打开同一插件的一个窗口;省略 `toolWindowID` 的命令只通知后端,此时 `toolWindows` 可以为空或省略。 - **网页窗口**:`web.entry` 是包内 `.html` 文件的相对路径,需要 `ui.web` 权限。网页的桥接和生命周期见[网页内容](../../contract/v1/README.md#web-content)。 -- **插件视图**:`view.function` 是插件后端的私有函数,清单需要 `backend`、`ui` 0 和 `ui.contribute` 权限。宿主按事件(`open`、`click`、`change`、`select`、`viewport` 等)调用它,函数返回整个视图或按节点 ID 的补丁。一个视图最多 512 个界面节点、深度 16、2000 个树项和 8 个画布,每个画布最多 2000 个节点;超出预算或违反界面规则的结果整体拒绝,宿主保留上一版视图并显示错误和重试。工具窗口里不能绑定设置,设置区域里不能放树。三个官方 SDK 都用 `view(id, handler)` 声明视图函数([Node.js](../../sdk/node/README.md#plugin-views)、[Rust](../../sdk/rust/README.md#plugin-views)、[Java](../../sdk/java/README.md#plugin-views))。 +- **插件视图**:`view.function` 是插件后端的私有函数,清单需要 `backend`、`ui` 0 和 `ui.contribute` 权限。宿主按事件(`open`、`click`、`change`、`select`、`viewport` 等)调用它,函数返回整个视图或按节点 ID 的补丁。一个视图最多 512 个界面节点、深度 16、2000 个树项和 8 个画布,每个画布最多 2000 个节点;超出预算或违反界面规则的结果整体拒绝,宿主保留上一版视图并显示错误和重试。工具窗口里不能绑定设置,设置区域里不能放树。官方 SDK 都用 `view(id, handler)`(Go 是 `View(id, handler)`)声明视图函数([Node.js](../../sdk/node/README.md#plugin-views)、[Rust](../../sdk/rust/README.md#plugin-views)、[Go](../../sdk/go/README.md#plugin-views)、[Java](../../sdk/java/README.md#plugin-views))。 - **没有窗口的命令**:需要 `backend`(清单 `requires`)、`ui.contribute` 和 `backend.launch` 权限,以及 `onCommand:` 激活事件。`commands/didRun` 只是事件,不代表命令的业务动作成功。 - 所有 ID 以插件 ID 加点开头。标题最多 256 字节,窗口文本最多 65536 字节,按原样显示,不作为 HTML 或脚本执行。 @@ -77,7 +77,7 @@ A plugin can place tool windows and commands in the workbench. The window shell - **Tool windows**: 1–64. Each has a stable `id`, `title`, initial `placement` (`left`, `bottom`, or `right`), integer `order` (default 0), and exactly one kind of content: `text` (plain text), `web` (a packaged page), or `view` (a plugin view). - **Commands**: up to 128. `placements` is nonempty and takes `commandPalette`, `toolbar`, or `menu`. A command with `toolWindowID` opens one of the same plugin's windows. A command without `toolWindowID` only notifies the backend; `toolWindows` may then be empty or omitted. - **Web windows**: `web.entry` is a package-relative `.html` path and requires the `ui.web` permission. The bridge and lifecycle are in [Web content](../../contract/v1/README.md#web-content). -- **Plugin views**: `view.function` is a private function of the plugin's backend; the manifest needs `backend`, `ui` 0, and the `ui.contribute` permission. The host calls it once per event (`open`, `click`, `change`, `select`, `viewport`, and so on), and it returns a whole view or patches by node ID. A view holds at most 512 UI nodes, depth 16, 2000 tree items and 8 canvases of at most 2000 nodes each; a result over budget or against a surface rule is refused whole, and the host keeps the last view with an error and Retry. A tool window cannot bind settings, and a settings region cannot show a tree. All three official SDKs declare a view function with `view(id, handler)` ([Node.js](../../sdk/node/README.md#plugin-views), [Rust](../../sdk/rust/README.md#plugin-views), [Java](../../sdk/java/README.md#plugin-views)). +- **Plugin views**: `view.function` is a private function of the plugin's backend; the manifest needs `backend`, `ui` 0, and the `ui.contribute` permission. The host calls it once per event (`open`, `click`, `change`, `select`, `viewport`, and so on), and it returns a whole view or patches by node ID. A view holds at most 512 UI nodes, depth 16, 2000 tree items and 8 canvases of at most 2000 nodes each; a result over budget or against a surface rule is refused whole, and the host keeps the last view with an error and Retry. A tool window cannot bind settings, and a settings region cannot show a tree. All official SDKs declare a view function with `view(id, handler)` (`View(id, handler)` in Go) ([Node.js](../../sdk/node/README.md#plugin-views), [Rust](../../sdk/rust/README.md#plugin-views), [Go](../../sdk/go/README.md#plugin-views), [Java](../../sdk/java/README.md#plugin-views)). - **Commands without a window**: require `backend` (in `requires`), `ui.contribute`, and `backend.launch`, plus the `onCommand:` activation event. `commands/didRun` is an event; it does not show that the command's business action succeeded. - Every ID starts with the plugin ID and a dot. Titles are at most 256 bytes and window text at most 65536 bytes; text is shown literally and never evaluated as HTML or script. diff --git a/shared/plugins/reference/domains/vcs.md b/shared/plugins/reference/domains/vcs.md index f2529326..1451483c 100644 --- a/shared/plugins/reference/domains/vcs.md +++ b/shared/plugins/reference/domains/vcs.md @@ -15,7 +15,7 @@ | 权限 | `process.vcs`、`languageServer.launch` | | 激活事件 | `onVcsRoot:`;根目录检测只看标记文件,不启动进程,找到该 VCS 的根目录后才启动提供者。目录标记(如 `.svn`)是 VCS 元数据,插件启用期间所有工作区都会隐藏,Search Everywhere 也不列出其中的文件名 | | Lithe 桌面端 | 未声明 `vcsProviders`,安装时拒绝需要它的包 | -| 官方 SDK | [Node SDK](../../sdk/node/README.md#a-vcs-provider) 0.5.0 实现 `litheVcs` 0;Java、Rust SDK 不实现 | +| 官方 SDK | [Node SDK](../../sdk/node/README.md#a-vcs-provider) 0.5.0 实现 `litheVcs` 0;Java、Rust、Go SDK 不实现 | ### 能力与操作 @@ -69,7 +69,7 @@ A plugin can implement a provider for a version control system other than Git (S | Permissions | `process.vcs`, `languageServer.launch` | | Activation events | `onVcsRoot:`; root detection reads marker files only and starts no process, and a provider starts only after a root of its VCS is found. Directory markers, such as `.svn`, are VCS metadata: every workspace hides them while the plugin is enabled, and Search Everywhere never lists their file names | | Lithe desktop | Does not declare `vcsProviders`; packages that require it are refused before installation | -| Official SDKs | The [Node SDK](../../sdk/node/README.md#a-vcs-provider) 0.5.0 implements `litheVcs` 0; the Java and Rust SDKs do not | +| Official SDKs | The [Node SDK](../../sdk/node/README.md#a-vcs-provider) 0.5.0 implements `litheVcs` 0; the Java, Rust, and Go SDKs do not | ### Capabilities and operations diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index f0b956b8..442ab0e1 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- `ui` 0 内的补充(API-13):视图事件新增 `width` 和 `resize`,画布可以跟随窗口宽度重新排版。会报告宽度的宿主在每个视图事件里带 `width`(排版视图节点用的宽度,单位为点,至少为 1 的整数,也是顶层画布的宽度),并且量到宽度之后才发 `open`;画布的 `on` 除 `viewport` 外可以写 `resize`,视图里有这样的画布时,宽度停止变化 400 ms 后宿主发 `resize` 和新的 `width`,等待中的 `resize` 可以合并成最新的一个。插件只有在收到带 `width` 的事件后才写 `resize`:不报告宽度的宿主不发 `resize`,它的 Core 也会拒绝写了 `resize` 的画布。契约 README 同时写明画布在缩放 1 时怎样放 `viewBox`:不写 `pan` 时显示整个 `viewBox`,按视图宽度缩放但不超过 `height`,从区域左上角开始;写了 `pan` 时宽度占满视图、上边对齐区域顶部,缩小到比区域窄时水平居中。以前的说明只有“按视图宽度缩放、`height` 点高”,在更宽的窗口里会裁掉场景下半部分。Core 的画布校验接受 `on: ["viewport", "resize"]`,`plugin-ui.schema.json` 的 canvas 说明和 `on` 同步;Rust SDK 新增 `ViewEventKind::Resize` 和 `ViewEvent::width`,Java SDK 新增 `Kind.RESIZE` 和 `width()`,Node SDK 的 `ViewEventKind` 加上 `resize`、`ViewEvent` 加上 `width`、画布 `on` 的类型放宽,三个 SDK 的 README 补充用法;`domains/settings.md` 中英两段说明区域画布怎样按 `width` 排版,以及旧宿主下的固定宽度(语言页约 610 点、构建系统页和编译器页右侧详情约 340 点)([1lck/Lithe-IDEA#2181](https://github.com/1lck/Lithe-IDEA/issues/2181))。没有新增能力版本、宿主方法、通知或 SDK 版本,取代 [#107](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/107)。 +- 官方 SDK 新增 Go(—):Go 插件后端 SDK 放在 `shared/plugins/sdk/go`,模块路径 `github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go`,需要 Go 1.22 或更高版本,只用标准库,按模块标签 `shared/plugins/sdk/go/v<版本>` 发布(还没有推送标签)。它实现函数协议和宿主服务(凭据、工作区、文档与编辑器、预览、浏览器、窗口消息、`functions/providers` 与 `functions/invoke`、原生终端、订阅)、插件视图 `View(id, handler)` 和 `litheKeymapImport` 0,不实现构建和 VCS 提供者。契约 README 的 Official backend SDK 加上 `sdk/go` 一段:在 Unix 上把协议移到 stdout 的副本、stdout 指向 stderr,处理函数 panic 只结束这一次调用。Go 示例后端和 Rust 示例后端跑同一个插件后端场景,`sdk-e2e.mjs` 新增 `plugin_sdk_go`。插件总览、日志指南和各参考页列出 Go SDK,并推荐新插件优先用 Rust 或 Go SDK(构建后端照旧用 Node.js 或 Java SDK,VCS 后端用 Node.js SDK)。没有新增版本号、宿主方法、通知或协议字段。 ## 按协议查首次出现 @@ -57,6 +57,7 @@ | `projectGenerators` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `beforeLaunchTasks` | 0 | 2026-11-18 | [#97](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/97) | | `managedRuntimes` | 0 | 2026-11-18 | [#96](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/96) | +| `managedRuntimes` | 1 | 2026-11-19 | [#108](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/108) | | `runConfigurationTypes` | 0 | 2026-11-18 | [#94](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/94) | | `sourceSettings` | 0 | 2026-11-15 | [#57](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/57) | | `sourceSettings` | 1 | 2026-11-17 | [#79](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/79) | @@ -148,6 +149,8 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#109](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/109) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-13 | `ui` 0 内的补充(API-13) | 视图事件新增 `width` 和 `resize`,画布可以跟随窗口宽度重新排版。会报告宽度的宿主在每个视图事件里带 `width`(排版视图节点用的宽度,单位为点,至少为 1 的整数,也是顶层画布的宽度),并且量到宽度之后才发 `open`;画布的 `on` 除 `viewport` 外可以写 `resize`,视图里有这样的画布时,宽度停止变化 400 ms 后宿主发 `resize` 和新的 `width`,等待中的 `resize` 可以合并成最新的一个。插件只有在收到带 `width` 的事件后才写 `resize`:不报告宽度的宿主不发 `resize`,它的 Core 也会拒绝写了 `resize` 的画布。契约 README 同时写明画布在缩放 1 时怎样放 `viewBox`:不写 `pan` 时显示整个 `viewBox`,按视图宽度缩放但不超过 `height`,从区域左上角开始;写了 `pan` 时宽度占满视图、上边对齐区域顶部,缩小到比区域窄时水平居中。以前的说明只有“按视图宽度缩放、`height` 点高”,在更宽的窗口里会裁掉场景下半部分。Core 的画布校验接受 `on: ["viewport", "resize"]`,`plugin-ui.schema.json` 的 canvas 说明和 `on` 同步;Rust SDK 新增 `ViewEventKind::Resize` 和 `ViewEvent::width`,Java SDK 新增 `Kind.RESIZE` 和 `width()`,Node SDK 的 `ViewEventKind` 加上 `resize`、`ViewEvent` 加上 `width`、画布 `on` 的类型放宽,三个 SDK 的 README 补充用法;`domains/settings.md` 中英两段说明区域画布怎样按 `width` 排版,以及旧宿主下的固定宽度(语言页约 610 点、构建系统页和编译器页右侧详情约 340 点)([1lck/Lithe-IDEA#2181](https://github.com/1lck/Lithe-IDEA/issues/2181))。没有新增能力版本、宿主方法、通知或 SDK 版本,取代 [#107](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/107)。 | +| [#108](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/108) | [@1lck](https://github.com/1lck) | API-23 | **`managedRuntimes` 1** | 受管运行时的每个平台归档可以写 `mirrors`:最多 8 个备用 HTTPS 地址,提供与 `url` 同一个 SHA-256 固定的归档,不改变 `cacheKey`。Core 要求镜像地址不带凭据和片段、彼此不同且不同于 `url`;写了 `mirrors` 却没有声明 `managedRuntimes: 1` 的清单被拒绝,其他插件继续写 0。清单 schema 的 `requires.managedRuntimes` 加上版本 1、平台归档加上 `mirrors`;[能力与协议版本对照](capabilities-and-versions.md)把 `managedRuntimes` 0 的桌面端一列改为 ✅,新增版本 1 一行。没有新增宿主方法、通知或 SDK 版本。宿主须先声明 `managedRuntimes` 1,插件才可要求它。 | | [#105](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/105) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-13、API-19 | `ui` 0、`settings` 0 内的说明补充(API-13、API-19) | 契约 README 写明画布 `image` 节点怎样读取:路径留在插件包内、经过真实目录、指向普通 PNG 文件,单个文件最多 256 KiB、每边最多 1024 像素(预算表新增一行);宿主在场景第一次画到它时于窗口线程外读取,保留到视图关闭,读到之前或读取失败时场景不画它,失败只记一次日志。`image` 节点的字段表补上 `opacity`。文字是一行,基线在 `y`,`align` 把行首(默认)、中点或行尾放在 `x`;渐变 `angle` 与 CSS `linear-gradient` 一致(0 向上、90 向右、默认 180 向下),渐变线穿过形状中心;分组的 `x`、`y` 放置原点,`scale` 缩放内部,`children`、`w`、`h`、`radius` 都在分组自己的坐标里;捏合缩放只在宿主能上报捏合时可用。fixture `fixtures/ui/view-results.json` 的文字基线移到卡片中间。[能力与协议版本对照](capabilities-and-versions.md)删掉“插件视图尚未在桌面端绘制”的脚注,`domains/ui.md`、`domains/settings.md` 的桌面端一行改为已呈现插件视图、设置区域和包内翻译 `l10n/`([1lck/Lithe-IDEA#2181](https://github.com/1lck/Lithe-IDEA/issues/2181))。没有新增版本号、宿主方法、通知或 SDK 版本。 | ### 2026-11-18 diff --git a/shared/plugins/scripts/sdk-e2e.mjs b/shared/plugins/scripts/sdk-e2e.mjs index 51019719..5bb5518a 100644 --- a/shared/plugins/scripts/sdk-e2e.mjs +++ b/shared/plugins/scripts/sdk-e2e.mjs @@ -6,14 +6,17 @@ // The scenario files are Cargo integration tests of lithe-core, declared in // rust/crates/core/Cargo.toml behind the `plugin-sdk-e2e` feature, so a plain // `cargo test` skips them. This script builds the sample backends and then -// runs those tests, which exercise the Node.js, Java and Rust SDKs, the native -// build workflows and shortcut import against Core at this working tree. +// runs those tests, which exercise the Node.js, Java, Rust and Go SDKs, the +// native build workflows and shortcut import against Core at this working +// tree. // // The Node.js sample runs on the node running this script. The Java sample // runs on LITHE_PLUGIN_SDK_JAVA_RUNTIME, or `java` on PATH, and is built with // Maven unless LITHE_PLUGIN_SDK_JAVA_SAMPLE names a built sample-build.jar. // The Rust sample backend is built with Cargo unless -// LITHE_PLUGIN_SDK_RUST_SAMPLE names a built sample-backend executable. +// LITHE_PLUGIN_SDK_RUST_SAMPLE names a built sample-backend executable, and +// the Go sample backend with `go` on PATH unless LITHE_PLUGIN_SDK_GO_SAMPLE +// names one. import { spawn } from 'node:child_process'; import { access } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; @@ -22,7 +25,7 @@ import { dirname, join, resolve } from 'node:path'; /** shared/plugins: the SDKs, their samples and the contract. */ const plugins = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const repository = resolve(plugins, '..', '..'); -const tests = ['plugin_sdk_node', 'plugin_sdk_java', 'plugin_sdk_rust', 'plugin_sdk_build']; +const tests = ['plugin_sdk_node', 'plugin_sdk_java', 'plugin_sdk_rust', 'plugin_sdk_go', 'plugin_sdk_build']; function run(command, args, options = {}) { return new Promise((resolvePromise, reject) => { @@ -77,10 +80,21 @@ async function rustSample() { return executable; } +/** Builds the Go sample backend from the current SDK sources unless it is given. */ +async function goSample() { + if (process.env.LITHE_PLUGIN_SDK_GO_SAMPLE) return resolve(process.env.LITHE_PLUGIN_SDK_GO_SAMPLE); + const module = join(plugins, 'sdk/go'); + const executable = join(module, 'bin', process.platform === 'win32' ? 'sample-backend.exe' : 'sample-backend'); + await run(await which('go'), ['build', '-o', executable, './examples/sample-backend'], { cwd: module }); + await access(executable); + return executable; +} + async function main() { const java = process.env.LITHE_PLUGIN_SDK_JAVA_RUNTIME || await which('java'); const { jar, nativeJar } = await javaSamples(); const rust = await rustSample(); + const go = await goSample(); await run('cargo', ['test', '--locked', '--manifest-path', join(repository, 'rust/Cargo.toml'), '-p', 'lithe-core', '--features', 'plugin-sdk-e2e', ...tests.flatMap(test => ['--test', test])], { env: { @@ -91,6 +105,7 @@ async function main() { LITHE_PLUGIN_SDK_JAVA_SAMPLE: jar, LITHE_PLUGIN_SDK_JAVA_NATIVE_SAMPLE: nativeJar, LITHE_PLUGIN_SDK_RUST_SAMPLE: rust, + LITHE_PLUGIN_SDK_GO_SAMPLE: go, }, }); } diff --git a/shared/plugins/sdk/e2e/plugin_sdk_go.rs b/shared/plugins/sdk/e2e/plugin_sdk_go.rs new file mode 100644 index 00000000..5980050c --- /dev/null +++ b/shared/plugins/sdk/e2e/plugin_sdk_go.rs @@ -0,0 +1,45 @@ +//! End-to-end check of the official Go plugin SDK (`sdk/go`) against Rust +//! Core, with the plugin backend scenario in `plugin_sdk/backend.rs` that the +//! Rust SDK sample also runs. +//! +//! The sample is installed the way a plugin ships: `plugin.json`, the +//! backend executable at its packaged path, and the web page that calls it. +//! It runs only when `LITHE_PLUGIN_SDK_GO_SAMPLE` names the built +//! `sample-backend` executable; `shared/plugins/scripts/sdk-e2e.mjs` sets it. + +mod plugin_sdk; + +#[test] +fn the_go_sdk_import_provider_reads_a_selected_source_through_core() { + let Some(executable) = std::env::var_os("LITHE_PLUGIN_SDK_GO_SAMPLE") else { + return; + }; + plugin_sdk::keymap::run("go-keymap", &executable.to_string_lossy(), &[]); +} + +#[test] +fn the_go_sdk_sample_backend_serves_functions_and_host_services() { + let Some(executable) = std::env::var_os("LITHE_PLUGIN_SDK_GO_SAMPLE") else { + eprintln!("skipped: set LITHE_PLUGIN_SDK_GO_SAMPLE to run the Go SDK end-to-end check"); + return; + }; + let sample = |file: &str| { + ( + file.to_string(), + plugin_sdk::repository_path(&format!("sdk/go/examples/sample-backend/{file}")), + ) + }; + let files = [ + sample("plugin.json"), + sample("ui/index.html"), + sample("ui/main.js"), + sample("ui/style.css"), + ("bin/sample-backend".to_string(), executable.into()), + ]; + let files: Vec<_> = files + .iter() + .map(|(destination, source)| (destination.as_str(), source.clone())) + .collect(); + let package = plugin_sdk::TemporaryPackage::new("go", &files); + plugin_sdk::backend::run_backend_scenario(&package.root); +} diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md new file mode 100644 index 00000000..b2134b91 --- /dev/null +++ b/shared/plugins/sdk/go/README.md @@ -0,0 +1,527 @@ +# Lithe plugin backend SDK for Go + +The Go module `github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go`, +package `lithe`, is the official way to write a +[plugin backend](../../contract/v1/README.md#plugin-backend) in Go: the one +long-lived process a plugin declares under `backend` in `plugin.json`, which +Lithe starts on demand (a page's first call, a command, workspace open; see +[Backend lifecycle and workspace contexts](../../contract/v1/README.md#backend-lifecycle-and-workspace-contexts)). +The backend is a packaged executable, so a plugin ships one archive per +platform. It speaks the LSP base protocol on stdio and implements, from the +[plugin contract](../../contract/v1/README.md), which lives in this repository +next to the SDK and changes with it: + +- **`litheFunctions`**: plugin functions with progress, cancellation, and + registration at runtime, and the [view functions](#plugin-views) that draw + a plugin's tool windows and settings regions. +- **Host services**: the plugin's own credentials, kept by the host in the + platform's secret store, workspace contexts, files, documents, editors, + preview, the browser, window messages, commands, native terminals, and + subscriptions, and [calls to the functions other plugins export](#calling-other-plugins), + relayed by Core, with the `Caller` a function called that way sees. +- **`litheKeymapImport`**: independently negotiated shortcut import providers + reading only explicitly selected source snapshots. +- **`litheLogging`**: typed diagnostics, required at initialization; see + [Logging](#logging). + +It covers the same protocols as the [Rust SDK](../rust/README.md), and the +same Core end-to-end scenario checks both. The SDK owns the wire format, +negotiation, cancellation, and error mapping; your code supplies only +handlers. It uses only the Go standard library, runs every call on a +goroutine of its own, and needs Go 1.22 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. + +## 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 +`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). + +## A minimal backend + +```json +"pluginAPIVersion": 0, +"requires": { "backend": 0, "ui": 0 }, +"permissions": ["backend.launch", "credentials.store", "ui.contribute", "ui.web"], +"backend": { "launch": { "kind": "packaged", "path": "bin/backend" }, "arguments": ["--state", "${stateDir}"] } +``` + +```go +package main + +import ( + "encoding/json" + "os" + + "github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go/lithe" +) + +func main() { + backend := lithe.NewBackend("example-backend").Version("1.0.0") + err := backend.Function("connection.test", func(params json.RawMessage, call *lithe.Context) (any, error) { + call.ProgressPercent("Connecting", 10) + var input struct { + Connection string `json:"connection"` + } + if json.Unmarshal(params, &input) != nil || input.Connection == "" { + return nil, lithe.NewPluginError("example.invalidParams", `"connection" must be a string.`) + } + _, present, err := call.Credentials().Get("connection:" + input.Connection) + if err != nil { + return nil, err + } + if err := call.CheckCancelled(); err != nil { + return nil, err + } + return map[string]any{"hasPassword": present}, nil + }) + if err != nil { + panic(err) + } + os.Exit(backend.Listen()) +} +``` + +The page calls it through the host bridge, without an `instance`: + +```js +const { value } = await lithe.request('functions.invoke', { function: 'connection.test', params: { connection: 'main' } }); +``` + +[`examples/sample-backend`](examples/sample-backend) is a complete plugin: +the manifest, a web page, notes kept in `${stateDir}` with progress, a +function registered at runtime, a secret in the credential store, +cancellation, a watch on the page's workspace, a native terminal, a command +answered with a message in its window, and a handler for workspace changes. +From the root of this repository, +`node shared/plugins/scripts/sdk-e2e.mjs` builds it and drives it through a +real Core session with the scenario in +[`sdk/e2e/plugin_sdk/backend.rs`](../e2e/plugin_sdk/backend.rs). + +Build one executable per platform, without cgo so it needs nothing installed: + +```sh +CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -trimpath -o package/bin/backend . +CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -trimpath -o package/bin/backend.exe . +``` + +## Plugin views + +A tool window or settings region whose manifest entry has +`view: { function }` is drawn by that backend function +([Plugin views](../../contract/v1/README.md#plugin-views)). Declare it with +`backend.View(id, handler)`. The handler gets a `*lithe.ViewEvent`: `Kind`, +`Instance`, `Surface`, `Language`, the `Effective` and `Draft` setting +values, and the fields of that event (`Node`, `Canvas`, `Value`, `Setting`, +`Item`, `Viewport`, `Width`). Params that are not a view event fail the call +with `sdk.view.invalidEvent` before the handler runs; an optional field that +is `null` counts as absent. The handler answers a `lithe.ViewResult`: + +- `lithe.View(nodes...)`: a whole view. The first answer after `ViewOpen` + must be one. +- `lithe.Patches(patches...)`: edits to the view the host is drawing, built + with `PatchSet`, `PatchReplace`, `PatchRemove`, and `PatchInsert` (placed + with `.Under`, `.At`, `.InTree`, or `.InCanvas`). +- `lithe.Unchanged()`: nothing changed. The SDK answers `{}`. + +Nodes are any JSON-serializable values shaped as +[`plugin-ui.schema.json`](../../contract/v1/plugin-ui.schema.json) describes. +Core checks every answer, and the host draws nothing that Core refused. Return +view text in `event.Language`. A host that reports the view's width sends it +as `event.Width` on every event; a canvas that follows the window lays itself +out at that width, lists `resize` in its `on`, and answers `ViewResize` with +the scene laid out again ([Canvas](../../contract/v1/README.md#canvas)). + +```go +must(backend.View("explorer.draw", func(event *lithe.ViewEvent, _ *lithe.Context) (lithe.ViewResult, error) { + switch { + case event.Kind == lithe.ViewOpen: + return lithe.View(map[string]any{"type": "row", "children": []any{ + map[string]any{"type": "label", "text": "Modules"}, + map[string]any{"type": "button", "id": "refresh", "text": "Refresh"}, + }}), nil + case event.Kind == lithe.ViewClick && event.Node == "refresh": + return lithe.Patches(lithe.PatchSet("refresh", map[string]any{"enabled": false})), nil + } + return lithe.Unchanged(), nil +})) +``` + +## Shortcut import providers + +Declare `backend.KeymapImportProvider(id, handler)` before listening. The host +negotiates IDs independently of plugin functions; a handler receives a +`KeymapImportRequest` and a call-scoped `*Context`. Use +`request.ListInputs(call.Host())` and `request.ReadChunk(call.Host(), fileID, +offset, maximumBytes)` to read declared files in bounded chunks. +`KeymapSourceFile.Path` is a relative label; the file ID is the authority. +Return `{ "bindings": [...] }` in the normalized contract format. The host +cancels the call on import cancellation and revokes the snapshot when it ends. +Do not convert conditional or multi-stroke rules into global bindings. + +## Getting the SDK + +The SDK is a Go module in a subdirectory of this repository, so its versions +are tags named `shared/plugins/sdk/go/v`; the Go module proxy and +checksum database serve it, and `go.sum` pins its exact contents: + +```sh +go get github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go@v0.1.0 +``` + +Until the first tag, name a commit of `main` instead of `v0.1.0`; Go records +it as a pseudo-version. Fetch the module at build time, never at runtime; +`go mod vendor` keeps a copy in your repository when your build must not +reach the network. + +## Logging + +The SDK requires `experimental.litheLogging` at initialization and refuses a +host that does not offer it. +See [plugin logging](../../guides/plugin-logging.md) for the typed diagnostics +API, host-owned catalog, exact levels, operation correlation and `${logDir}`. +Use `Diagnostics().Degraded` and `.Recovered` for handled fallback or recovery +facts. Function terminal facts are automatic; do not log a failure before +returning it to the SDK. Suppress successful high-frequency reads with +`SuppressSuccessDiagnostics`. There is no free-text log API, no stderr +fallback and no plugin-owned file writer. + +## API + +| API | Purpose | +| --- | --- | +| `lithe.NewBackend(name).Version(version)` | Creates the backend; `name` and `version` are reported as `serverInfo`. | +| `backend.Function(id, handler)` | Declares a function offered in `initialize`. | +| `backend.View(id, handler)` | Declares a view function; see [Plugin views](#plugin-views). | +| `backend.OnInitialize(hook)` | Runs before the `initialize` answer with an `*Initialize`: the host's `Params()`, `FunctionsVersion()` (`0, true` when the host offered `litheFunctions`), `RootPath()` (the plugin's `${stateDir}`), and `Function(id, handler)` to add functions that depend on state found at startup. An error refuses `initialize`. | +| `backend.OnShutdown(hook)` | Runs on `shutdown`, after running calls were cancelled. | +| `backend.Handle()` | A `*BackendHandle` for other goroutines. | +| `backend.Listen()` | Serves stdio until `exit` or the end of input and returns the exit code: `0` after `shutdown` and `exit`, `1` otherwise. | +| `backend.Serve(input, output)` | The same on other streams, for tests. | +| `handle.RegisterFunction(id, handler)`, `handle.UnregisterFunction(id)` | Adds or withdraws a function after `initialize` and waits until the host accepted it. Withdrawing revokes and cancels running calls; a handler must not withdraw its own function. | +| `handle.FunctionIDs()`, `handle.FunctionsVersion()` | What the backend serves, and `0, true` when the host offered `litheFunctions`. | +| `backend.OnCommand(id, handler)` | Runs `func(commandID string, context *WorkspaceContext) error` when the user runs one of the plugin's commands. | +| `backend.OnContextsChanged(handler)`, `backend.OnHostNotification(method, handler)` | Handle `lithe/host/workspace/didChangeContexts` and any other `lithe/host/*` notification a later host adds. | +| `handle.Host()`, `call.Host()` | The [host services](#host-services). `handle.Host()` is bound to no call. | +| `handle.Credentials()`, `call.Credentials()` | Shorthand for `Host().Credentials()`. | +| `lithe.NewPluginError(code, message)` | A failure meant for your own UI. | + +A handler is `func(params json.RawMessage, call *lithe.Context) (any, error)`; +`params` is `{}` when the host sent none. Its context offers: + +| Member | Meaning | +| --- | --- | +| `Cancellation()` | A `*Cancellation`, fired when Lithe cancels the call, its deadline passes, the function is withdrawn, or the session ends: `IsCancelled()`, `Check()`, `Done()`, `Context()` (a `context.Context` to pass to database drivers and HTTP clients), `WaitTimeout(duration)` (use it instead of `time.Sleep`), and `OnCancel(callback)`. | +| `CheckCancelled()` | `lithe.ErrCancelled` once cancelled. | +| `Progress(message)`, `ProgressPercent(message, percentage)` | The message is cut to 1024 bytes and the percentage clamped to 0–100; reports after the call ended are dropped. | +| `Host()` | Host services bound to the call: a request still waiting for the host when the call is cancelled ends at once. `Credentials()` is `Host().Credentials()`. | +| `WorkspaceContext()` | The `*WorkspaceContext` of the window whose page made the call; `nil` when no window made it. | +| `Caller()` | The `*Caller` (`PluginID()`) of the plugin whose backend called this function through Core's relay; `nil` when the host started the call and when the host's `caller` is not exactly `{ pluginID }` with a non-empty string. | +| `Backend()`, `FunctionID()`, `Diagnostics()` | The handle, the function's ID, and typed diagnostics correlated with this call. | + +## Host services + +A backend may ask the host for services; each is granted by a manifest +permission and refused otherwise. They are available when the host offers +`litheFunctions` in `initialize`; without it, host requests fail locally with +`plugin.host.unavailable` and send nothing. Every method blocks its goroutine +until the host answers and returns an `error` that is a `*lithe.SdkError`; +wrong arguments fail locally and send nothing. + +```go +must(backend.Function("query.run", func(params json.RawMessage, call *lithe.Context) (any, error) { + // Permission credentials.store: the platform's secret store, per plugin. + password, present, err := call.Host().Credentials().Get("connection.prod:password") + if err != nil { + return nil, err + } + if !present { + return nil, lithe.NewPluginError("query.noPassword", "Sign in first.") + } + // The window the page runs in. + var folders json.RawMessage + if workspace := call.WorkspaceContext(); workspace != nil { + if ok, err := call.Host().Supports("lithe/host/workspace/getFolders"); err == nil && ok { + if folders, err = call.Host().Workspace().GetFolders(*workspace); err != nil { + return nil, err + } + } + } + return runQuery(params, password, folders) +})) + +host := backend.Handle().Host() +must(backend.OnCommand("db.refresh", func(_ string, workspace *lithe.WorkspaceContext) error { + if workspace == nil { + return nil + } + _, err := host.Window().ShowInformation(*workspace, map[string]any{"text": "Refreshed."}) + return err +})) +``` + +| `Host` member | Purpose | +| --- | --- | +| `Credentials().Get(key)`, `.Set(key, secret)`, `.Delete(key)` | Secrets in the platform's store; see [Credentials](#credentials). | +| `Capabilities()`, `Supports(method)` | What this session may call, from `lithe/host/getCapabilities` (asked once). | +| `Workspace().ListContexts()`, `.GetContext(context)`, `.GetFolders(context)` | Workspace contexts; only `GetContext` returns, and creates, the context's `stateDirectory`. | +| `Workspace().ReadDirectory`, `.Stat`, `.ReadFile`, `.FindFiles`, `.FindText`, `.Watch` | Files of a local context, addressed as `{ rootID, path }` from `GetFolders`. | +| `Documents().List`, `.GetSnapshot`; `Editor().GetActive`, `.GetSelections`, `.ApplyEdits`, `.ReplaceSelections`, `.InsertText`, `.Open`, `.Reveal`, `.RegisterActions` | Live documents and editors. Edits name the `expectedVersion` they were computed against. | +| `Preview().OpenHTML`, `Browser().OpenExternal`, `Window().ShowInformation`, `.ShowWarning`, `.ShowError` | Preview, browser, and messages. | +| `Terminal().Create`, `.Show`, `.Close`, `.Reopen`, `.Dispose`, `.OnExit` | Native terminals; see [Native terminal API](#native-terminal-api). | +| `Functions().Providers(functionID)`, `.Invoke(context, call)` | The plugins that export a function, and a call to one of them; see [Calling other plugins](#calling-other-plugins). | +| `Request(method, params)`, `Subscribe(method, params)` | Any `lithe/host/*` method, including ones a later host adds. | +| `Subscriptions().Dispose(id)` | Ends a subscription; `Subscription.Dispose()` does the same. | +| `WithCancellation(cancellation)` | The same services, cancelled together with `cancellation`. | +| `Negotiated()` | `true` when the host offered `litheFunctions` in this session; `false` before `initialize`. | + +A host registers only the services it implements, and `Capabilities()` lists +exactly those; call `Supports(method)` before depending on one of them. What +the Lithe desktop does not register yet is listed under +[Capability versions](../../reference/capabilities-and-versions.md#capability-versions-requires). + +Methods taking a workspace context take a `WorkspaceContext`: one from +`call.WorkspaceContext()`, `lithe.NewWorkspaceContext(id, generation)`, or +`lithe.ParseWorkspaceContext` on a whole context from `ListContexts`. Their +`params` are the contract's, without `context`, and they return the +contract's result as `json.RawMessage`. The full params and results are in +[the contract](../../contract/v1/README.md#public-document-file-and-window-methods). + +What the SDK does for you, and what it leaves to you: + +- **Refusals keep the host's code.** Get the `*lithe.SdkError` with + `errors.As` and branch on `Code()`, such as `plugin.host.contextExpired`; + `RPCCode()` is the JSON-RPC number and `Details()` the host's object, if + any. A code this SDK does not know is kept as sent. On `versionConflict` + reread and recompute; on `contextExpired` resolve the original target + again, never the focused window; retry `busy` and `rateLimited` (after the + `retryAfterMilliseconds` detail) with a bound; `permissionDenied` and + `readOnly` need the user. An unknown param is + `plugin.host.unsupportedOption` naming it in the `option` detail, so you can + retry without it. `lithe.HostErrorCodes` lists the codes and numbers the + contract defines. +- **Cancellation has no rollback.** Cancelling the token given to + `WithCancellation`, or ending the call whose `call.Host()` sent a request, + fails it at once with `sdk.call.cancelled`; the SDK also sends + `$/cancelRequest` so the host stops. An edit or an external open may + already have taken effect, and the SDK never sends a request again. +- **At most 16 host requests are unanswered.** Further ones wait in the SDK + for a free slot instead of being refused. +- **Subscriptions route by ID.** `Workspace().Watch`, + `Editor().RegisterActions`, `Terminal().OnExit`, and `Subscribe` return a + `*Subscription`; `Recv()` and `RecvTimeout(duration)` give each `Event` in + order, with `Sequence()`, `Event()`, and `Gap()`, which is true when events + were missed, so rescan. Events the host sends before its answer are kept. + No event is delivered after `Dispose()` or the end of the session, not even + one still queued: `Recv()` returns `false` and `RecvTimeout` returns + `lithe.ErrSubscriptionDisposed` (`lithe.ErrRecvTimeout` when nothing + arrived in time). +- **Commands are events.** `OnCommand` runs on a goroutine of its own when + the user runs one of the plugin's commands, with the window's + `*WorkspaceContext` when the host sent one. The host waits for no result, + and a failure is only logged. A stopped backend is started for it only + when the manifest declares `onCommand:`. Host notifications + without a handler are ignored. + +### Credentials + +A key is 1–128 ASCII letters, digits, `.`, `_`, `:`, or `-` +(`lithe.IsCredentialKey`); a secret is at most 16 KiB. Credentials are private +to your plugin ID, survive disabling and updating the plugin, and are deleted +when it is uninstalled. They are never written to `${stateDir}` or the +package. `Get` returns `"", false, nil` when nothing is stored. + +| Failure (`SdkError.Code()`) | Meaning | +| --- | --- | +| `plugin.host.unavailable` | The host did not offer `litheFunctions`, so it has no host services. Nothing was sent. | +| `plugin.host.permissionDenied` | The plugin lacks the `credentials.store` permission. | +| `plugin.host.invalidParams`, `sdk.credentials.invalidKey`, `sdk.credentials.invalidSecret` | A malformed key or secret. | +| `plugin.host.failed` | The host's secret store failed, for example a locked secret store; the message says why and never contains the secret. | +| `sdk.call.cancelled` | The call was cancelled while waiting; returning it answers as cancelled. | +| `sdk.session.notReady`, `sdk.session.closed` | The session has not finished `initialize`, or it ended while waiting. | + +### Calling other plugins + +A backend may call a function another plugin exports; Core relays the call and +the provider's backend never learns more than the call it serves. The +manifest declares both sides: the caller lists `{ id, version }` under +`pluginFunctions.calls`, and the provider lists +`{ id, version, context: "workspace" }` under `pluginFunctions.exports` and +registers the function with `backend.Function(id, handler)`. See +[cross-plugin calls](../../contract/v1/README.md#cross-plugin-calls) +for the manifest, the order of Core's checks, and the call chain. + +```go +must(backend.Function("project.options", func(_ json.RawMessage, call *lithe.Context) (any, error) { + workspace := call.WorkspaceContext() + if workspace == nil { + return nil, lithe.NewPluginError("example.noWorkspace", "Open a folder first.") + } + host := call.Host() + if ok, err := host.Supports("lithe/host/functions/invoke"); err != nil || !ok { + return map[string]any{"options": []any{}}, err + } + answer, err := host.Functions().Providers("project.describe") + if err != nil { + return nil, err + } + var providers struct { + Providers []struct { + PluginID string `json:"pluginID"` + } `json:"providers"` + } + if json.Unmarshal(answer, &providers) != nil || len(providers.Providers) == 0 { + return map[string]any{"options": []any{}}, nil + } + described, err := host.Functions().Invoke(*workspace, map[string]any{ + "pluginID": providers.Providers[0].PluginID, + "functionID": "project.describe", + "params": map[string]any{"project": "app"}, + "timeoutMilliseconds": 5000, + }) + if err != nil { + return nil, err + } + return map[string]any{"options": described}, nil +})) + +must(backend.Function("project.describe", func(params json.RawMessage, call *lithe.Context) (any, error) { + // Core wrote the caller from the calling session; it cannot be forged. + askedBy := "" + if caller := call.Caller(); caller != nil { + askedBy = caller.PluginID() + } + return map[string]any{"params": params, "askedBy": askedBy}, nil +})) +``` + +- **Check before calling.** `Supports("lithe/host/functions/invoke")` and + `Supports("lithe/host/functions/providers")` tell whether this session may + call. Host services alone are not enough: a plugin that declares no `calls` + gets `plugin.host.permissionDenied`. When the host did not offer + `litheFunctions`, `Providers`, `Invoke`, and `Host().Request` with either + method fail locally with `plugin.host.unavailable` and send nothing. +- **`Providers(functionID)`** answers `{ "providers": [{ "pluginID", + "version" }] }`: the enabled plugins other than this one that export the + function, sorted by plugin ID. This plugin must have declared the function, + or the host answers `plugin.function.notDeclared`. A provider's backend need + not be running. +- **`Invoke(context, call)`** answers `{ "value": ... }`, where `value` is the + provider's result and may be `null`. `context` is a `WorkspaceContext` this + backend learned from the workspace service or `call.WorkspaceContext()`; + the relay accepts local workspaces only. `call` is an object (a map or a + struct) with `pluginID` and `functionID`, and optionally `params` (an + object, `{}` by default), `timeoutMilliseconds` (a positive integer; the + host defaults it to 60000 and caps it at 600000, and the SDK does not clamp + it), and `parentOperationID`. Any other key, such as `context` or `caller`, + is not sent; the host would refuse it as `plugin.host.unsupportedOption`. A + call that is not an object, lacks `pluginID` or `functionID`, or has a + field of the wrong type fails locally with `sdk.functions.invalidCall`, and + a `functionID` that is not a function ID does the same for `Providers`. +- **Limits are the host's.** A chain has at most 4 calls and does not return + to a plugin already on it (`plugin.function.callCycle`); a caller has at + most 8 relayed calls running; params and a result are at most 256 KiB. A + provider that is asked to apply values must not call the plugin that asked + inside that call. +- **`parentOperationID` is filled in for you inside a handler.** A call made + with `call.Host().Functions().Invoke(...)` while a function runs names that + call's `operationID`, so Core makes it a child: cancelling or ending the + handler's call cancels the relayed call. An explicit `parentOperationID` in + `call` overrides it (1 to 128 bytes). A `handle.Host()` serves no call and a + generic `Request` is sent as written, so neither fills it in. An ID that + names a call this backend is no longer serving fails with + `plugin.host.cancelled`. +- **A relayed call occupies a request slot.** It counts among the 16 + unanswered host requests until the provider answers, which can take up to + 600 seconds; further requests wait in the SDK. Keep relayed calls bounded + with `timeoutMilliseconds`. +- **`call.Caller()` names the calling plugin.** It is non-nil only for a call + Core relayed, and `nil` for a call the host started. The SDK accepts only a + `caller` that is exactly `{ "pluginID": "" }`; any other + shape is read as no caller. It names who called, not what they may do: + authorize with the plugin's own rules. + +| Failure (`SdkError.Code()`) | Meaning | +| --- | --- | +| `sdk.functions.invalidCall` | The `call` or the function ID was malformed. Nothing was sent. | +| `plugin.host.unavailable` | The host did not offer `litheFunctions`. Nothing was sent. | +| `plugin.host.permissionDenied` | The plugin declares no `pluginFunctions.calls`. | +| `plugin.function.notDeclared`, `.providerDisabled`, `.notExported`, `.versionMismatch` | The call is not declared, the provider is missing or disabled, does not export the function now, or exports another version. | +| `plugin.function.callCycle`, `.depthExceeded`, `.tooManyCalls`, `.payloadTooLarge` | The chain, the caller's running calls, or a payload exceeded a limit. | +| `plugin.function.providerUnavailable`, `.invalidResult` | The provider's backend stopped or did not start in time, or answered with no result or one over 1 MiB. | +| `plugin.function.failed` | The provider's function returned an error. The `pluginErrorCode` entry of `Details()` is the provider's own `PluginError` code, and `Message()` is its message. | +| `plugin.host.contextExpired`, `plugin.host.authorityUnsupported`, `plugin.host.timeout`, `plugin.host.cancelled` | The context was closed or replaced, is not a local workspace, the deadline passed, or the call (or its parent) was cancelled. | +| `sdk.host.invalidResult` | The host answered with something other than an object. | + +## Results and errors + +| Handler outcome | What Lithe sees | +| --- | --- | +| `value, nil` (including `nil`) | `result.value` | +| `nil, *PluginError` (or an error wrapping one) | `plugin.function.failed` with your message and `pluginErrorCode`. The code is for your plugin's own UI; Lithe never branches on it. | +| Any other error, or a panic | `plugin.function.failed` with a generic message, so paths, secrets, and stack traces never reach the UI. Automatic SDK diagnostics record only a fixed failure category. A panic ends only its call. | +| `lithe.ErrCancelled` (or an error wrapping it, such as `sdk.call.cancelled`), or any outcome after cancellation | `requestCancelled` (or Lithe's timeout or revocation outcome) | + +A result must serialize to at most 1 MiB of JSON; a `json.RawMessage` is sent +as it is. A function ID is dot-separated lowerCamelCase segments +(`snapshot.refresh`, `lithe.IsFunctionID`), at most 128 bytes, and a session +holds at most 256 functions. A `PluginError` code matches +`[A-Za-z][A-Za-z0-9._-]*`, at most 64 bytes (`lithe.IsPluginErrorCode`); +`NewPluginError` panics on any other code. + +## Rules that keep Lithe in charge + +1. **stdout belongs to the protocol.** On Unix, `Listen()` moves the protocol + to a duplicate of the stdout descriptor and points stdout at stderr, so a + stray `fmt.Println` in your code or a dependency lands in the host's log. + Elsewhere, never print to stdout. +2. **The package is read-only.** Keep caches and databases under `${stateDir}`, + which Lithe also passes as the root and working directory. Diagnostics use + the SDK and host; native log files require an explicitly supplied `${logDir}`. + Writing to the package breaks code signing and update deltas. +3. **Secrets go to the credentials service.** Never write a password or + token to `${stateDir}`, to a log line, or to a `PluginError` message. +4. **Work ends with its call.** Check the cancellation in long loops, use + `WaitTimeout` between retries, and pass `Cancellation().Context()` to + 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 + `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 sends + `lithe/host/functions/invoke` and lets Core relay it. + +## Native terminal API + +The SDK includes wrappers for plugin-owned native terminal create/show/close, +reopen with bounded display history, disposal and exit subscriptions. They are +host methods discovered through `Capabilities()`; they require a host that +offers them and the `terminal.create` permission. See +[the native terminal guide](../../guides/native-terminals.md). + +## Testing + +Run these from this directory: + +```sh +go test -race ./... +go vet ./... +gofmt -l . +``` + +and, from the root of this repository, `node shared/plugins/scripts/sdk-e2e.mjs`. + +The unit tests drive a session through in-process pipes with a scripted +host; `lithe/host_services_test.go` checks the host services against the +contract's fixture. The end-to-end check builds the sample, installs it as a +package, and runs it through a real Core session of this checkout. It needs +Go, Rust, Node.js 20.3 or newer, Java (`LITHE_PLUGIN_SDK_JAVA_RUNTIME` or +`java` on `PATH`) and Maven; `LITHE_PLUGIN_SDK_GO_SAMPLE` names an already +built `sample-backend`. diff --git a/shared/plugins/sdk/go/examples/sample-backend/main.go b/shared/plugins/sdk/go/examples/sample-backend/main.go new file mode 100644 index 00000000..938e9c31 --- /dev/null +++ b/shared/plugins/sdk/go/examples/sample-backend/main.go @@ -0,0 +1,462 @@ +// Sample plugin backend for the Go SDK: the `backend` process of the sample +// plugin in this directory. Lithe starts it when the plugin's web page first +// calls a function or the user runs its command, with `--state ${stateDir}`. +// It: +// +// - keeps notes in its state directory, with progress (note.save, +// note.read), and registers note.clear once there is a note to clear; +// - keeps a secret in the host's credential store, never in its state +// (secret.remember, secret.check, secret.forget); +// - waits until it is cancelled (work.wait), and fails unexpectedly without +// leaking details to the page (fail.unexpectedly); +// - watches the files of the page's workspace through the host +// (files.nextChange), answers its command with a message in the window it +// ran in, and lists the open workspaces when they change. +// +// Build it with `go build -o bin/sample-backend ./examples/sample-backend` +// from the SDK directory. +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go/lithe" +) + +const ( + // version is the version plugin.json declares. + version = "0.1.0" + // greet is the command plugin.json declares. + greet = "org.example.sample-backend.greet" + watch = "lithe/host/workspace/watch" +) + +func main() { + state, err := stateDirectory(os.Args[1:]) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + backend := lithe.NewBackend("sample-backend").Version(version) + + // Exercised only when the Core end-to-end harness offers this provider. + must(backend.KeymapImportProvider("fixture", func(request lithe.KeymapImportRequest, call *lithe.Context) (any, error) { + files, err := request.ListInputs(call.Host()) + if err != nil { + return nil, err + } + if len(files) == 0 { + return nil, errors.New("no fixture source") + } + data, err := request.ReadChunk(call.Host(), files[0].ID, 0, 4) + if err != nil { + return nil, err + } + if string(data) != "data" { + return nil, errors.New("unexpected fixture source") + } + return map[string]any{"bindings": []any{map[string]any{ + "commandID": "find-next", + "keys": []any{map[string]any{"key": "f3", "modifiers": []any{}}}, + }}}, nil + })) + + must(backend.Function("note.save", func(params json.RawMessage, call *lithe.Context) (any, error) { + var input struct { + Text *string `json:"text"` + } + _ = json.Unmarshal(params, &input) + name, err := noteName(params) + if err != nil { + return nil, err + } + if input.Text == nil { + return nil, lithe.NewPluginError("sample.invalidParams", `"text" must be a string.`) + } + call.ProgressPercent("Saving", 0) + directory := filepath.Join(state, "notes") + if err := os.MkdirAll(directory, 0o755); err != nil { + return nil, err + } + // Written beside the note and renamed, so a reader never sees half a note. + temporary := filepath.Join(directory, "."+name+".tmp") + if err := os.WriteFile(temporary, []byte(*input.Text), 0o644); err != nil { + return nil, err + } + if err := os.Rename(temporary, filepath.Join(directory, name+".txt")); err != nil { + return nil, err + } + call.ProgressPercent("Saved", 100) + offerClear(call.Backend(), state) + return map[string]any{"name": name, "bytes": len(*input.Text)}, nil + })) + + must(backend.Function("note.read", func(params json.RawMessage, _ *lithe.Context) (any, error) { + name, err := noteName(params) + if err != nil { + return nil, err + } + text, err := os.ReadFile(filepath.Join(state, "notes", name+".txt")) + if errors.Is(err, fs.ErrNotExist) { + return nil, lithe.NewPluginError("sample.noteMissing", fmt.Sprintf("There is no note named %s.", name)) + } + if err != nil { + return nil, err + } + return map[string]any{"text": string(text)}, nil + })) + + must(backend.Function("secret.remember", func(params json.RawMessage, call *lithe.Context) (any, error) { + key, secret, err := credential(params) + if err != nil { + return nil, err + } + if err := call.Credentials().Set(key, secret); err != nil { + return nil, credentialsFailure(err) + } + return map[string]any{}, nil + })) + + must(backend.Function("secret.check", func(params json.RawMessage, call *lithe.Context) (any, error) { + key, secret, err := credential(params) + if err != nil { + return nil, err + } + stored, present, err := call.Credentials().Get(key) + if err != nil { + return nil, credentialsFailure(err) + } + // The page learns whether its input matches, never the secret. + return map[string]any{"stored": present, "matches": present && stored == secret}, nil + })) + + must(backend.Function("secret.forget", func(params json.RawMessage, call *lithe.Context) (any, error) { + key, err := credentialKey(params) + if err != nil { + return nil, err + } + if err := call.Credentials().Delete(key); err != nil { + return nil, credentialsFailure(err) + } + return nil, nil + })) + + must(backend.Function("work.wait", func(_ json.RawMessage, call *lithe.Context) (any, error) { + if err := os.WriteFile(filepath.Join(state, "waiting"), nil, 0o644); err != nil { + return nil, err + } + // Blocks without spinning until the host cancels the call. + if call.Cancellation().WaitTimeout(600 * time.Second) { + if err := os.WriteFile(filepath.Join(state, "cancelled"), nil, 0o644); err != nil { + return nil, err + } + return nil, lithe.ErrCancelled + } + return "finished", nil + })) + + must(backend.Function("fail.unexpectedly", func(json.RawMessage, *lithe.Context) (any, error) { + return nil, fmt.Errorf("could not open %s", filepath.Join(state, "missing")) + })) + + must(backend.Function("files.nextChange", func(_ json.RawMessage, call *lithe.Context) (any, error) { + return nextChange(call) + })) + + // The terminal API is a host service. The lifecycle sample deliberately + // uses a harmless interactive client and display-only history; it never + // executes retained text as input. + must(backend.Function("terminal.cycle", func(_ json.RawMessage, call *lithe.Context) (any, error) { + return terminalCycle(call) + })) + + // Notifications are events: each handler runs on a goroutine of its own + // and may ask the host for more, outside any call. + handle := backend.Handle() + must(backend.OnCommand(greet, func(_ string, context *lithe.WorkspaceContext) error { + if context == nil { + return nil + } + host := handle.Host() + answer, err := host.Workspace().GetFolders(*context) + if err != nil { + return err + } + var folders struct { + Folders []struct { + Name string `json:"name"` + } `json:"folders"` + } + _ = json.Unmarshal(answer, &folders) + var names []string + for _, folder := range folders.Folders { + if folder.Name != "" { + names = append(names, folder.Name) + } + } + text := "Sample Backend sees no folders." + if len(names) > 0 { + text = fmt.Sprintf("Sample Backend sees %s.", strings.Join(names, ", ")) + } + _, err = host.Window().ShowInformation(*context, map[string]any{"text": text}) + return err + })) + + // A backend that keeps state per workspace would refresh it here. + backend.OnContextsChanged(func(json.RawMessage) error { + _, err := handle.Host().Workspace().ListContexts() + return err + }) + + backend.OnInitialize(func(initialize *lithe.Initialize) error { + if hasNotes(state) { + return initialize.Function("note.clear", func(_ json.RawMessage, call *lithe.Context) (any, error) { + return clearNotes(state, call) + }) + } + return nil + }) + + os.Exit(backend.Listen()) +} + +func stateDirectory(arguments []string) (string, error) { + if len(arguments) == 2 && arguments[0] == "--state" { + return arguments[1], nil + } + return "", errors.New("usage: sample-backend --state ") +} + +// must stops the sample on a registration its own code got wrong. +func must(err error) { + if err != nil { + panic(err) + } +} + +// offerClear registers note.clear the first time there is a note to clear. +func offerClear(backend *lithe.BackendHandle, state string) { + if slices.Contains(backend.FunctionIDs(), "note.clear") { + return + } + err := backend.RegisterFunction("note.clear", func(_ json.RawMessage, call *lithe.Context) (any, error) { + return clearNotes(state, call) + }) + if err != nil { + degraded(backend.Diagnostics(), "initialize", "registration_failed") + } +} + +func clearNotes(state string, call *lithe.Context) (any, error) { + if err := call.CheckCancelled(); err != nil { + return nil, err + } + // RemoveAll succeeds when there is nothing to remove. + if err := os.RemoveAll(filepath.Join(state, "notes")); err != nil { + return nil, err + } + return nil, nil +} + +// nextChange waits for the next change under the first folder of the page's +// workspace, through a host file watch. +func nextChange(call *lithe.Context) (any, error) { + workspace := call.WorkspaceContext() + if workspace == nil { + return nil, lithe.NewPluginError("sample.noWorkspace", "Open a workspace first.") + } + host := call.Host() + // Core answers capability discovery itself, from the plugin's permissions. + supported, err := host.Supports(watch) + if err != nil { + return nil, err + } + if !supported { + return nil, lithe.NewPluginError("sample.watchUnavailable", "Lithe does not let this plugin watch files.") + } + answer, err := host.Workspace().GetFolders(*workspace) + if err != nil { + return nil, workspaceFailure(err) + } + var folders struct { + Folders []struct { + RootID string `json:"rootID"` + } `json:"folders"` + } + _ = json.Unmarshal(answer, &folders) + if len(folders.Folders) == 0 || folders.Folders[0].RootID == "" { + return nil, lithe.NewPluginError("sample.noWorkspace", "The workspace has no folders.") + } + subscription, err := host.Workspace().Watch(*workspace, map[string]any{ + "resource": map[string]any{"rootID": folders.Folders[0].RootID, "path": ""}, + "recursive": true, + }) + if err != nil { + return nil, workspaceFailure(err) + } + result, err := firstChange(call, subscription) + // A subscription outlives the call until it is disposed. + if subscription.Dispose() != nil { + degraded(call.Diagnostics(), "files.nextChange", "subscription_dispose_failed") + } + return result, err +} + +func firstChange(call *lithe.Context, subscription *lithe.Subscription) (any, error) { + for { + if call.Cancellation().IsCancelled() { + return nil, lithe.ErrCancelled + } + event, err := subscription.RecvTimeout(200 * time.Millisecond) + if errors.Is(err, lithe.ErrRecvTimeout) { + continue + } + if err != nil { + return nil, errors.New("the watch ended") + } + var change struct { + ChangedPaths json.RawMessage `json:"changedPaths"` + } + _ = json.Unmarshal(event.Event(), &change) + return map[string]any{"changedPaths": change.ChangedPaths}, nil + } +} + +func terminalCycle(call *lithe.Context) (any, error) { + workspace := call.WorkspaceContext() + if workspace == nil { + return nil, lithe.NewPluginError("sample.noWorkspace", "Open a workspace first.") + } + host := call.Host() + supported, err := host.Supports("lithe/host/terminal/reopen") + if err != nil { + return nil, err + } + if !supported { + return nil, lithe.NewPluginError("sample.terminalUnavailable", "The host has no native terminal API.") + } + terminal := host.Terminal() + answer, err := terminal.Create(*workspace, map[string]any{ + "executable": "example-client", "arguments": []string{"--interactive"}, + "retainedContextBytes": 4096, "show": true, + }) + if err != nil { + return nil, err + } + var created struct { + TerminalID string `json:"terminalID"` + } + _ = json.Unmarshal(answer, &created) + if created.TerminalID == "" { + return nil, errors.New("missing terminalID") + } + subscription, err := terminal.OnExit(*workspace, created.TerminalID) + if err != nil { + return nil, err + } + closed, err := terminal.Close(*workspace, created.TerminalID, 4096) + if err != nil { + return nil, err + } + event, err := subscription.RecvTimeout(5 * time.Second) + if err != nil { + return nil, errors.New("terminal exit did not arrive") + } + reopened, err := terminal.Reopen(*workspace, created.TerminalID) + if err != nil { + return nil, err + } + if _, err := terminal.Dispose(*workspace, created.TerminalID); err != nil { + return nil, err + } + if err := subscription.Dispose(); err != nil { + return nil, err + } + return map[string]any{"closed": closed, "reopened": reopened, "event": event.Event()}, nil +} + +// workspaceFailure turns a stale context (plugin.host.contextExpired), left by +// a window that switched folders, into an error the page can recover from. +func workspaceFailure(err error) error { + var sdk *lithe.SdkError + if errors.As(err, &sdk) && sdk.Code() == "plugin.host.contextExpired" { + return lithe.NewPluginError("sample.workspaceChanged", "The workspace changed; try again.") + } + return err +} + +func hasNotes(state string) bool { + entries, err := os.ReadDir(filepath.Join(state, "notes")) + return err == nil && len(entries) > 0 +} + +// noteName is a file name the sample chooses the alphabet of, so a page can +// never name a path outside the notes directory. +func noteName(params json.RawMessage) (string, error) { + var input struct { + Name string `json:"name"` + } + _ = json.Unmarshal(params, &input) + valid := len(input.Name) >= 1 && len(input.Name) <= 64 + for _, b := range []byte(input.Name) { + if !(b >= 'a' && b <= 'z' || b >= '0' && b <= '9' || b == '-') { + valid = false + } + } + if !valid { + return "", lithe.NewPluginError("sample.invalidParams", `"name" must be 1-64 lowercase letters, digits, or "-".`) + } + return input.Name, nil +} + +func credentialKey(params json.RawMessage) (string, error) { + var input struct { + Key string `json:"key"` + } + _ = json.Unmarshal(params, &input) + if !lithe.IsCredentialKey(input.Key) { + return "", lithe.NewPluginError("sample.invalidParams", `"key" is not a credential key.`) + } + return input.Key, nil +} + +func credential(params json.RawMessage) (key, secret string, err error) { + if key, err = credentialKey(params); err != nil { + return "", "", err + } + var input struct { + Secret *string `json:"secret"` + } + _ = json.Unmarshal(params, &input) + if input.Secret == nil { + return "", "", lithe.NewPluginError("sample.invalidParams", `"secret" must be a string.`) + } + return key, *input.Secret, nil +} + +// credentialsFailure explains a host that offers no credential store +// (plugin.host.unavailable), or a plugin installed without the +// credentials.store permission, to the page; other failures stay internal. +func credentialsFailure(err error) error { + var sdk *lithe.SdkError + if errors.As(err, &sdk) && strings.HasPrefix(sdk.Code(), "plugin.host.") { + return lithe.NewPluginError("sample.credentialsUnavailable", "Lithe cannot store credentials for this plugin.") + } + return err +} + +// degraded reports a fixed degradation; the values are valid, so a failure +// only means the session already ended. +func degraded(diagnostics *lithe.Diagnostics, operation, code string) { + if err := diagnostics.Degraded(operation, code); err != nil { + fmt.Fprintln(os.Stderr, err) + } +} diff --git a/shared/plugins/sdk/go/examples/sample-backend/plugin.json b/shared/plugins/sdk/go/examples/sample-backend/plugin.json new file mode 100644 index 00000000..04324601 --- /dev/null +++ b/shared/plugins/sdk/go/examples/sample-backend/plugin.json @@ -0,0 +1,50 @@ +{ + "schemaVersion": 0, + "id": "org.example.sample-backend", + "displayName": "Sample Backend", + "version": "0.1.0", + "pluginAPIVersion": 0, + "requires": { "backend": 0, "ui": 0 }, + "vendor": { + "id": "org.example", + "displayName": "Example", + "signatureRequirement": "publisherPackage" + }, + "permissions": [ + "backend.launch", + "terminal.create", + "credentials.store", + "ui.contribute", + "ui.web", + "window.messages", + "workspace.files.watch", + "workspace.metadata" + ], + "activationEvents": [ + "onView:org.example.sample-backend.notes", + "onCommand:org.example.sample-backend.greet" + ], + "languages": [], + "ui": { + "toolWindows": [ + { + "id": "org.example.sample-backend.notes", + "title": "Sample Notes", + "placement": "right", + "web": { "entry": "ui/index.html" } + } + ], + "commands": [ + { + "id": "org.example.sample-backend.greet", + "title": "Greet from Sample Backend", + "toolWindowID": "org.example.sample-backend.notes", + "placements": ["commandPalette"] + } + ] + }, + "backend": { + "launch": { "kind": "packaged", "path": "bin/sample-backend" }, + "arguments": ["--state", "${stateDir}"] + } +} diff --git a/shared/plugins/sdk/go/examples/sample-backend/ui/index.html b/shared/plugins/sdk/go/examples/sample-backend/ui/index.html new file mode 100644 index 00000000..78447cfb --- /dev/null +++ b/shared/plugins/sdk/go/examples/sample-backend/ui/index.html @@ -0,0 +1,23 @@ + + + + + Sample Notes + + + + +
+ + + + +
+
+ + + +
+

+ + diff --git a/shared/plugins/sdk/go/examples/sample-backend/ui/main.js b/shared/plugins/sdk/go/examples/sample-backend/ui/main.js new file mode 100644 index 00000000..82da4b21 --- /dev/null +++ b/shared/plugins/sdk/go/examples/sample-backend/ui/main.js @@ -0,0 +1,43 @@ +// The page reaches its backend only through the host bridge: functions.invoke +// without an instance calls this plugin's backend, which Lithe starts on the +// first call. Inline scripts are refused by the page's content security policy. +const status = document.getElementById('status'); +const note = document.getElementById('note'); +const secret = document.getElementById('secret'); +let calls = 0; + +async function call(fn, params) { + const id = `call-${Date.now()}-${calls++}`; + try { + const { value } = await lithe.request('functions.invoke', { function: fn, params, call: id }); + return value; + } catch (error) { + status.textContent = error.pluginErrorCode ? `${error.message} (${error.pluginErrorCode})` : error.message; + throw error; + } +} + +lithe.on('functions.progress', ({ message }) => { if (message) status.textContent = message; }); + +note.addEventListener('submit', async (event) => { + event.preventDefault(); + const { bytes } = await call('note.save', { name: note.name.value, text: note.text.value }); + status.textContent = `Saved ${bytes} bytes.`; +}); + +document.getElementById('read').addEventListener('click', async () => { + note.text.value = (await call('note.read', { name: note.name.value })).text; + status.textContent = 'Loaded.'; +}); + +secret.addEventListener('submit', async (event) => { + event.preventDefault(); + await call('secret.remember', { key: 'sample:password', secret: secret.secret.value }); + secret.secret.value = ''; + status.textContent = 'Stored in the system credential store.'; +}); + +document.getElementById('check').addEventListener('click', async () => { + const { stored, matches } = await call('secret.check', { key: 'sample:password', secret: secret.secret.value }); + status.textContent = !stored ? 'Nothing stored.' : matches ? 'It matches.' : 'It does not match.'; +}); diff --git a/shared/plugins/sdk/go/examples/sample-backend/ui/style.css b/shared/plugins/sdk/go/examples/sample-backend/ui/style.css new file mode 100644 index 00000000..d3973150 --- /dev/null +++ b/shared/plugins/sdk/go/examples/sample-backend/ui/style.css @@ -0,0 +1,3 @@ +body { font: var(--lithe-font-body, 13px system-ui); color: var(--lithe-text, CanvasText); background: transparent; margin: 12px; } +form { display: grid; gap: 6px; margin-bottom: 16px; } +label { display: grid; gap: 2px; } diff --git a/shared/plugins/sdk/go/go.mod b/shared/plugins/sdk/go/go.mod new file mode 100644 index 00000000..dba9ceee --- /dev/null +++ b/shared/plugins/sdk/go/go.mod @@ -0,0 +1,3 @@ +module github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go + +go 1.22 diff --git a/shared/plugins/sdk/go/lithe/backend.go b/shared/plugins/sdk/go/lithe/backend.go new file mode 100644 index 00000000..0e93f29b --- /dev/null +++ b/shared/plugins/sdk/go/lithe/backend.go @@ -0,0 +1,1235 @@ +package lithe + +import ( + "bufio" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "runtime" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + "unicode/utf8" +) + +// FunctionHandler serves one plugin function. params is the call's params +// object, {} when the host sent none. The result is any JSON-serializable +// value, at most 1 MiB encoded. Return a [*PluginError] to answer with the +// plugin's own code, [ErrCancelled] (or an error wrapping it) when the call +// stopped because it was cancelled; any other error answers as an internal +// failure whose text stays in the backend. +type FunctionHandler func(params json.RawMessage, call *Context) (any, error) + +// ViewHandler serves a view function; see [Backend.View]. +type ViewHandler func(event *ViewEvent, call *Context) (ViewResult, error) + +// KeymapImportHandler serves one shortcut import provider; see +// [Backend.KeymapImportProvider]. +type KeymapImportHandler func(request KeymapImportRequest, call *Context) (any, error) + +// CommandHandler handles a run of one of the plugin's commands, with the +// workspace context it ran in, nil when it has none. +type CommandHandler func(commandID string, context *WorkspaceContext) error + +// NotificationHandler handles a host notification's params. +type NotificationHandler func(params json.RawMessage) error + +// phase: idle -> listening -> initializing -> ready -> shuttingDown -> exited. +type phase int + +const ( + phaseIdle phase = iota + phaseListening + phaseInitializing + phaseReady + phaseShuttingDown + phaseExited +) + +type running struct { + functionID string + cancellation *Cancellation +} + +type state struct { + phase phase + functions map[string]FunctionHandler + keymapProviders map[string]KeymapImportHandler + selectedKeymapProviders []string + logging bool + loggingReady bool + earlyDiagnostics []map[string]any + quietSuccess map[string]bool + // functionsNegotiated is true when the host offered plugin functions, + // version FunctionsVersion. + functionsNegotiated bool + // incoming are the host requests being handled, by JSON-RPC ID. + incoming map[string]*running + // outgoing are the requests this backend sent to the host, by ID. + outgoing map[string]*outgoing + channel channel + // slotSignal is closed, and replaced, when a host-request slot frees or + // a waiting request must look again. + slotSignal chan struct{} +} + +// shared is everything handler goroutines share with the session. Locks are +// taken in the order registrations, capabilitiesMu, mu, outputMu, never the +// other way round. +type shared struct { + name string + mu sync.Mutex + state state + + outputMu sync.Mutex + output *bufio.Writer + + // registrations serializes register and unregister so the host sees + // them in call order. + registrations sync.Mutex + nextRequest atomic.Uint64 + + // capabilities caches the session's getCapabilities answer. + capabilitiesMu sync.Mutex + capabilities any +} + +// notifySlots wakes every request waiting for a slot. The caller holds mu. +func (s *shared) notifySlots() { + close(s.state.slotSignal) + s.state.slotSignal = make(chan struct{}) +} + +func (s *shared) currentPhase() phase { + s.mu.Lock() + defer s.mu.Unlock() + return s.state.phase +} + +func (s *shared) functionsNegotiated() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.state.functionsNegotiated +} + +func (s *shared) runningCancellations() []*Cancellation { + tokens := make([]*Cancellation, 0, len(s.state.incoming)) + for _, call := range s.state.incoming { + tokens = append(tokens, call.cancellation) + } + return tokens +} + +// requireFunctions checks, with mu held, that functions can be registered. +func (s *shared) requireFunctions() error { + switch { + case s.state.phase == phaseExited: + return closedError() + case s.state.phase == phaseReady && s.state.functionsNegotiated: + return nil + default: + return newSdkError("sdk.functions.unavailable", "The host has not negotiated plugin functions.") + } +} + +// write sends one message. After a failed write every later one is +// dropped: the protocol pipe is gone and the host owns the process's end. +func (s *shared) write(message any) { + body, err := encodeJSON(message) + if err != nil { + return + } + s.outputMu.Lock() + defer s.outputMu.Unlock() + if s.output == nil { + return + } + if writeFrame(s.output, body) != nil { + s.output = nil + } +} + +// answer is a JSON-RPC result, or an error object when err is set. +type answer struct { + result any + err map[string]any +} + +func rpcError(code int, message string) answer { + return answer{err: map[string]any{"code": code, "message": message}} +} + +func (s *shared) respond(id any, a answer) { + if a.err != nil { + s.write(map[string]any{"jsonrpc": "2.0", "id": id, "error": a.err}) + return + } + s.write(map[string]any{"jsonrpc": "2.0", "id": id, "result": a.result}) +} + +func (s *shared) failed(operation, code string) { + s.write(map[string]any{"jsonrpc": "2.0", "method": methodLog, "params": map[string]any{ + "kind": "operationFailed", "operation": operation, "code": code, "durationMs": 0, + }}) +} + +func (s *shared) finish(code int) int { + s.mu.Lock() + s.state.phase = phaseExited + s.closeChannel() + tokens := s.runningCancellations() + s.mu.Unlock() + for _, token := range tokens { + token.Cancel() + } + s.outputMu.Lock() + s.output = nil + s.outputMu.Unlock() + return code +} + +// notifyHandler runs a notification handler off the reading goroutine; a +// failure is logged with its category only. +func (s *shared) notifyHandler(handler func() error) { + go func() { + defer func() { + if recover() != nil { + s.failed("notification", "panic") + } + }() + if err := handler(); err != nil { + if kind, _ := classify(err); kind != kindCancelled { + s.failed("notification", failureKind(err)) + } + } + }() +} + +// request sends a lithe/function/* request; it takes no host-request slot. +func (s *shared) request(method string, params any) (any, error) { + return s.exchange(method, params, false, nil, nil) +} + +// Backend is a plugin backend. Declare functions and hooks, then call +// [Backend.Listen]: +// +// backend := lithe.NewBackend("example-backend").Version("1.0.0") +// err := backend.Function("snapshot.refresh", func(params json.RawMessage, call *lithe.Context) (any, error) { +// call.ProgressPercent("Refreshing", 10) +// var request struct{ Name *string } +// if json.Unmarshal(params, &request) != nil || request.Name == nil { +// return nil, lithe.NewPluginError("example.invalidName", `"name" must be a string.`) +// } +// return map[string]any{"refreshed": *request.Name}, nil +// }) +// if err != nil { +// log.Fatal(err) +// } +// os.Exit(backend.Listen()) +// +// Declare everything before Listen; a Backend is not safe for concurrent +// declaration. After that, use [Backend.Handle] from any goroutine. +type Backend struct { + shared *shared + version string + hasVersion bool + initializeHooks []func(*Initialize) error + shutdownHooks []func() + commands map[string]CommandHandler + contextsChanged NotificationHandler + hostNotifications map[string]NotificationHandler +} + +// NewBackend returns a backend; name is reported as serverInfo.name. +func NewBackend(name string) *Backend { + s := &shared{name: name} + s.state = state{ + phase: phaseIdle, + functions: map[string]FunctionHandler{}, + keymapProviders: map[string]KeymapImportHandler{}, + quietSuccess: map[string]bool{}, + incoming: map[string]*running{}, + outgoing: map[string]*outgoing{}, + channel: channel{routes: map[string]*route{}}, + slotSignal: make(chan struct{}), + } + return &Backend{ + shared: s, + commands: map[string]CommandHandler{}, + hostNotifications: map[string]NotificationHandler{}, + } +} + +// Version sets serverInfo.version. +func (b *Backend) Version(version string) *Backend { + b.version, b.hasVersion = version, true + return b +} + +// SuppressSuccessDiagnostics omits the successful terminal diagnostics of a +// registered high-frequency operation; failures stay visible. +func (b *Backend) SuppressSuccessDiagnostics(operation string) error { + s := b.shared + s.mu.Lock() + defer s.mu.Unlock() + if _, registered := s.state.functions[operation]; !registered && !slices.Contains(operations, operation) { + return newSdkError("sdk.logging.invalidOperation", "Suppress a registered operation.") + } + s.state.quietSuccess[operation] = true + return nil +} + +// Function declares a function offered from the start, in the initialize +// answer. To add one later, use [BackendHandle.RegisterFunction]. +// +// Each call runs on a goroutine of its own, so a handler may block; it +// should stop early when its [Context.Cancellation] fires. +func (b *Backend) Function(id string, handler FunctionHandler) error { + s := b.shared + s.mu.Lock() + defer s.mu.Unlock() + if err := checkNewFunction(id, s.state.functions); err != nil { + return err + } + s.state.functions[id] = handler + return nil +} + +// View declares the view function a tool window or settings region names in +// view.function: a plugin function whose params the SDK reads into a +// [ViewEvent] and whose [ViewResult] it answers. Params that are not a view +// event fail the call before the handler runs. +func (b *Backend) View(id string, handler ViewHandler) error { + return b.Function(id, func(params json.RawMessage, call *Context) (any, error) { + event, err := ParseViewEvent(params) + if err != nil { + return nil, err + } + result, err := handler(event, call) + if err != nil { + return nil, err + } + return result, nil + }) +} + +// KeymapImportProvider declares a shortcut import provider: id is 1-64 +// lowercase letters, digits or "-", starting with a letter; a backend has at +// most 8. The handler receives an opaque snapshot, never a filesystem path; +// it lists and reads the selected inputs through its call's host. +func (b *Backend) KeymapImportProvider(id string, handler KeymapImportHandler) error { + if !validKeymapProviderID(id) { + return newSdkError("sdk.keymap.invalidID", "Invalid shortcut import provider ID.") + } + s := b.shared + s.mu.Lock() + defer s.mu.Unlock() + if _, exists := s.state.keymapProviders[id]; exists || len(s.state.keymapProviders) >= 8 { + return newSdkError("sdk.keymap.invalidRegistration", "Duplicate provider or provider limit exceeded.") + } + s.state.keymapProviders[id] = handler + return nil +} + +// OnInitialize runs hook before the initialize answer. A hook may read the +// host's params and add functions; an error refuses initialize, mapped like +// a handler's. +func (b *Backend) OnInitialize(hook func(*Initialize) error) { + b.initializeHooks = append(b.initializeHooks, hook) +} + +// OnShutdown runs hook on shutdown, after running calls were cancelled. +func (b *Backend) OnShutdown(hook func()) { + b.shutdownHooks = append(b.shutdownHooks, hook) +} + +// OnCommand handles lithe/host/commands/didRun for one of the plugin's +// commands, its ID from the manifest (1-128 of [a-z0-9.-]). It is an event: +// the host waits for no result, and a failure is only logged. Each run has +// a goroutine of its own. A later handler for the same ID replaces the +// earlier one. +func (b *Backend) OnCommand(commandID string, handler CommandHandler) error { + if !IsCommandID(commandID) { + return newSdkError("sdk.command.invalidID", fmt.Sprintf("Command ID %q must be 1-128 of [a-z0-9.-].", commandID)) + } + b.commands[commandID] = handler + return nil +} + +// OnContextsChanged handles lithe/host/workspace/didChangeContexts with +// { revision }; call Host().Workspace().ListContexts() for the contexts. +func (b *Backend) OnContextsChanged(handler NotificationHandler) { + b.contextsChanged = handler +} + +// OnHostNotification handles a lithe/host/* notification a later host adds. +// Commands, context changes and subscription events have their own APIs. +func (b *Backend) OnHostNotification(method string, handler NotificationHandler) error { + if !strings.HasPrefix(method, hostPrefix) { + return newSdkError("sdk.method.invalid", method+" is not a host notification.") + } + if method == methodContexts || method == methodNotify || method == methodCommandRan { + return newSdkError("sdk.method.reserved", method+" is routed by the SDK; use OnCommand, OnContextsChanged, or Host.Subscribe.") + } + b.hostNotifications[method] = handler + return nil +} + +// Handle returns a handle for other goroutines: runtime registration, host +// services and diagnostics. +func (b *Backend) Handle() *BackendHandle { + return &BackendHandle{shared: b.shared} +} + +// Listen serves the host on stdin and stdout until it sends exit or closes +// stdin, and returns the process exit code. Stdout carries only protocol +// frames: on Unix the SDK moves the protocol to a duplicate of the stdout +// descriptor and points stdout at stderr, so a stray fmt.Println, in the +// plugin or a dependency, lands in the host's log instead of corrupting the +// stream. On Windows plugin code must not write to stdout. +func (b *Backend) Listen() int { + return b.Serve(os.Stdin, protocolOutput()) +} + +// Serve serves the host on the given streams; [Backend.Listen] uses stdin +// and stdout. +func (b *Backend) Serve(input io.Reader, output io.Writer) int { + s := b.shared + s.mu.Lock() + s.state.phase = phaseListening + s.mu.Unlock() + s.outputMu.Lock() + s.output = bufio.NewWriter(output) + s.outputMu.Unlock() + reader := bufio.NewReader(input) + for { + message, err := readFrame(reader) + switch { + case err != nil: + b.Handle().Diagnostics().terminal("notification", errors.New("framing_error"), time.Now()) + return s.finish(1) + case message == nil: + code := 0 + if s.currentPhase() != phaseShuttingDown { + code = 1 + } + return s.finish(code) + case message.malformed: + s.respond(nil, rpcError(rpcParseError, "The message is not valid JSON.")) + default: + if code, exit := b.dispatch(message.value); exit { + return s.finish(code) + } + } + } +} + +// dispatch handles one message; it reports the exit code once the host +// sent exit. +func (b *Backend) dispatch(message any) (int, bool) { + s := b.shared + object, ok := message.(map[string]any) + if !ok { + // Valid JSON that is not a message object, such as null or a batch. + s.respond(nil, rpcError(rpcInvalidRequest, "The message is not a JSON-RPC object.")) + return 0, false + } + id := object["id"] + params := object["params"] + method, isMethod := object["method"].(string) + switch { + case !isMethod && id != nil: + s.settleOutgoing(id, object) + case !isMethod: + case id != nil: + b.handleRequest(id, method, params) + default: + return b.handleNotification(method, params) + } + return 0, false +} + +func (b *Backend) handleRequest(id any, method string, params any) { + s := b.shared + switch method { + case methodInitialize: + b.initialize(id, params) + return + case methodShutdown: + b.shutdown(id) + return + } + switch s.currentPhase() { + case phaseReady: + switch method { + case methodInvoke: + s.invoke(id, params) + case methodKeymapImport: + s.invokeKeymap(id, params) + default: + s.respond(id, rpcError(rpcMethodNotFound, "Unsupported method: "+method)) + } + case phaseIdle, phaseListening, phaseInitializing: + s.respond(id, rpcError(rpcServerNotInitialized, "The backend is not initialized.")) + default: + s.respond(id, rpcError(rpcInvalidRequest, "The backend is shutting down.")) + } +} + +func (b *Backend) handleNotification(method string, params any) (int, bool) { + s := b.shared + switch { + case method == methodExit: + if s.currentPhase() != phaseShuttingDown { + return 1, true + } + return 0, true + case method == methodCancelRequest: + key := requestKey(field(params, "id")) + s.mu.Lock() + call := s.state.incoming[key] + s.mu.Unlock() + if call != nil { + call.cancellation.Cancel() + } + case strings.HasPrefix(method, hostPrefix): + b.hostNotification(method, params) + } + // initialized and anything else a plugin backend is not sent. + return 0, false +} + +// hostNotification routes a host notification. Core checked its shape and +// the session's grant; one this SDK does not know is ignored, as the +// contract asks. +func (b *Backend) hostNotification(method string, params any) { + s := b.shared + object, ok := params.(map[string]any) + if !s.functionsNegotiated() || !ok { + return + } + switch method { + case methodNotify: + s.deliver(object) + case methodCommandRan: + commandID, _ := object["commandID"].(string) + handler := b.commands[commandID] + if handler == nil { + s.failed("notification", "command_unhandled") + return + } + context := workspaceContextFromReference(object["context"]) + s.notifyHandler(func() error { return handler(commandID, context) }) + default: + handler := b.hostNotifications[method] + if method == methodContexts { + handler = b.contextsChanged + } + if handler != nil { + data := raw(params) + s.notifyHandler(func() error { return handler(data) }) + } + } +} + +// runHook runs one initialize hook; it reports the error answer when the +// hook refused or panicked. +func runHook(hook func(*Initialize) error, initialize *Initialize) (refusal map[string]any) { + defer func() { + if recover() != nil { + refusal = internalResponse() + } + }() + if err := hook(initialize); err != nil { + return responseError(err) + } + return nil +} + +func (b *Backend) initialize(id, params any) { + s := b.shared + s.mu.Lock() + if s.state.phase != phaseListening { + s.mu.Unlock() + s.respond(id, rpcError(rpcInvalidRequest, "initialize was already received.")) + return + } + s.state.phase = phaseInitializing + s.mu.Unlock() + + experimentalOffer := pointer(params, "capabilities", "experimental") + keymapOffer, hasKeymapOffer := field(experimentalOffer, "litheKeymapImport"), false + if object, ok := experimentalOffer.(map[string]any); ok { + _, hasKeymapOffer = object["litheKeymapImport"] + } + logging := offers(field(experimentalOffer, "litheLogging"), LoggingVersion) + s.mu.Lock() + s.state.logging = logging + s.state.loggingReady = false + s.state.earlyDiagnostics = nil + if !logging { + s.state.phase = phaseListening + } + existing := sortedKeys(s.state.functions) + s.mu.Unlock() + if !logging { + s.respond(id, rpcError(rpcInvalidRequest, fmt.Sprintf("The backend requires litheLogging version %d.", LoggingVersion))) + return + } + functions := offers(field(experimentalOffer, "litheFunctions"), FunctionsVersion) + init := &Initialize{params: params, functions: functions, existing: existing, added: map[string]FunctionHandler{}} + for _, hook := range b.initializeHooks { + if refusal := runHook(hook, init); refusal != nil { + s.mu.Lock() + s.state.phase = phaseListening + s.mu.Unlock() + s.respond(id, answer{err: refusal}) + return + } + } + + // The state stays locked until the answer is written, so a function + // registered from another goroutine cannot overtake it. + s.mu.Lock() + for functionID, handler := range init.added { + s.state.functions[functionID] = handler + } + s.state.functionsNegotiated = functions + experimental := map[string]any{"litheLogging": map[string]any{"version": LoggingVersion}} + if hasKeymapOffer && offers(keymapOffer, KeymapImportVersion) { + if providers, ok := field(keymapOffer, "providers").([]any); ok && len(providers) <= 8 { + var selected []string + for _, value := range providers { + providerID, ok := value.(string) + if _, registered := s.state.keymapProviders[providerID]; ok && registered && !slices.Contains(selected, providerID) { + selected = append(selected, providerID) + } + } + slices.Sort(selected) + s.state.selectedKeymapProviders = selected + if len(selected) > 0 { + experimental["litheKeymapImport"] = map[string]any{"version": KeymapImportVersion, "providers": selected} + } + } + } + if functions { + declared := []any{} + for _, functionID := range sortedKeys(s.state.functions) { + declared = append(declared, map[string]any{"id": functionID}) + } + experimental["litheFunctions"] = map[string]any{"version": FunctionsVersion, "functions": declared} + } + serverInfo := map[string]any{"name": s.name} + if b.hasVersion { + serverInfo["version"] = b.version + } + s.state.phase = phaseReady + s.respond(id, answer{result: map[string]any{ + "capabilities": map[string]any{"experimental": experimental}, + "serverInfo": serverInfo, + }}) + s.state.loggingReady = true + early := s.state.earlyDiagnostics + s.state.earlyDiagnostics = nil + s.mu.Unlock() + for _, params := range early { + s.write(map[string]any{"jsonrpc": "2.0", "method": methodLog, "params": params}) + } +} + +func (b *Backend) shutdown(id any) { + s := b.shared + s.mu.Lock() + switch s.state.phase { + case phaseListening, phaseInitializing, phaseReady: + default: + s.mu.Unlock() + s.respond(id, rpcError(rpcInvalidRequest, "shutdown was already received.")) + return + } + s.state.phase = phaseShuttingDown + tokens := s.runningCancellations() + s.mu.Unlock() + for _, token := range tokens { + token.Cancel() + } + for _, hook := range b.shutdownHooks { + func() { + defer func() { + if recover() != nil { + s.failed("shutdown", "panic") + } + }() + hook() + }() + } + s.respond(id, answer{result: nil}) +} + +// outcome is how a handler ended. +type outcome struct { + result any + err error + panicked bool +} + +func runCall(handler func() (any, error)) (ended outcome) { + defer func() { + if recover() != nil { + ended = outcome{panicked: true} + } + }() + result, err := handler() + return outcome{result: result, err: err} +} + +func (s *shared) invoke(id, params any) { + functionID, _ := field(params, "functionID").(string) + operationID := field(params, "operationID") + // What nested cross-plugin calls name as the call they belong to. + parent, _ := operationID.(string) + if !isParentOperationID(parent) { + parent = "" + } + callParams := field(params, "params") + if callParams == nil { + callParams = map[string]any{} + } + key := requestKey(id) + cancellation := NewCancellation() + var ( + handler FunctionHandler + workspaceContext *WorkspaceContext + caller *Caller + ) + s.mu.Lock() + if s.state.functionsNegotiated { + workspaceContext = workspaceContextFromReference(field(params, "context")) + caller = callerFromValue(field(params, "caller")) + handler = s.state.functions[functionID] + } + if handler != nil { + s.state.incoming[key] = &running{functionID: functionID, cancellation: cancellation} + } + s.mu.Unlock() + if handler == nil { + s.respond(id, rpcError(rpcInvalidParams, fmt.Sprintf("Function %s is not registered.", functionID))) + return + } + go func() { + // Ends host requests the call left behind, on copies of its host. + ended := NewCancellation() + call := &Context{ + shared: s, + functionID: functionID, + operationID: operationID, + diagnosticOperationID: requestOperationID(operationID, id), + cancellation: cancellation, + host: &Host{shared: s, scope: []*Cancellation{cancellation, ended}, parentOperation: parent}, + workspaceContext: workspaceContext, + caller: caller, + } + call.reporting.Store(true) + started := time.Now() + data := raw(callParams) + result := runCall(func() (any, error) { return handler(data, call) }) + call.reporting.Store(false) + ended.Cancel() + a := s.functionAnswer(call, functionID, result, started) + s.mu.Lock() + delete(s.state.incoming, key) + s.mu.Unlock() + s.respond(id, a) + }() +} + +func (s *shared) invokeKeymap(id, params any) { + object, isObject := params.(map[string]any) + provider, _ := object["providerID"].(string) + snapshot, _ := object["snapshotID"].(string) + if !isObject || len(object) != 2 || !validKeymapProviderID(provider) || !validSnapshotID(snapshot) { + s.respond(id, rpcError(rpcInvalidParams, "Invalid shortcut import request.")) + return + } + callID := "keymap:" + provider + key := requestKey(id) + cancellation := NewCancellation() + var handler KeymapImportHandler + s.mu.Lock() + if slices.Contains(s.state.selectedKeymapProviders, provider) { + handler = s.state.keymapProviders[provider] + } + if handler != nil { + s.state.incoming[key] = &running{functionID: callID, cancellation: cancellation} + } + s.mu.Unlock() + if handler == nil { + s.respond(id, rpcError(rpcInvalidParams, "Shortcut import provider was not negotiated.")) + return + } + go func() { + ended := NewCancellation() + call := &Context{ + shared: s, + functionID: callID, + diagnosticOperationID: requestOperationID(nil, id), + cancellation: cancellation, + host: &Host{shared: s, scope: []*Cancellation{cancellation, ended}}, + } + started := time.Now() + request := KeymapImportRequest{providerID: provider, snapshotID: snapshot} + result := runCall(func() (any, error) { return handler(request, call) }) + ended.Cancel() + // Facts name the wire method Core registered, not the per-provider call ID. + a := s.functionAnswer(call, methodKeymapImport, result, started) + s.mu.Lock() + delete(s.state.incoming, key) + s.mu.Unlock() + s.respond(id, a) + }() +} + +// functionAnswer is the answer to one call. A cancelled call answers as +// cancelled whatever the handler returned, and failures the host never sees +// in full are logged with a fixed category, without their private contents. +func (s *shared) functionAnswer(call *Context, function string, ended outcome, started time.Time) answer { + diagnostics := call.Diagnostics() + switch { + case call.cancellation.IsCancelled(): + return answer{err: cancelledResponse()} + case ended.panicked: + code, duration := "panic", elapsed(started) + _ = diagnostics.record("operationFailed", function, &code, nil, &duration) + return answer{err: internalResponse()} + case ended.err != nil: + if kind, _ := classify(ended.err); kind != kindCancelled { + diagnostics.terminal(function, ended.err, started) + } + return answer{err: responseError(ended.err)} + } + body, err := encodeJSON(ended.result) + if err != nil || len(body) > maxResultBytes { + diagnostics.terminal(function, errors.New("result_limit"), started) + return answer{err: internalResponse()} + } + quiet := call.quietSuccess.Load() + if !quiet { + s.mu.Lock() + quiet = s.state.quietSuccess[function] + s.mu.Unlock() + } + if !quiet { + diagnostics.terminal(function, nil, started) + } + return answer{result: json.RawMessage(body)} +} + +func checkNewFunction(id string, functions map[string]FunctionHandler) error { + if !IsFunctionID(id) { + return newSdkError("sdk.function.invalidID", fmt.Sprintf("Function ID %q must be dot-separated lowerCamelCase segments of at most 128 bytes.", id)) + } + if _, exists := functions[id]; exists { + return newSdkError("sdk.function.duplicate", fmt.Sprintf("Function %s is already declared.", id)) + } + if len(functions) >= MaxFunctions { + return newSdkError("sdk.function.limit", fmt.Sprintf("A backend serves at most %d functions.", MaxFunctions)) + } + return nil +} + +func sortedKeys[V any](values map[string]V) []string { + keys := make([]string, 0, len(values)) + for key := range values { + keys = append(keys, key) + } + slices.Sort(keys) + return keys +} + +// Initialize is what a hook sees of initialize, before the backend answers +// it. +type Initialize struct { + params any + functions bool + existing []string + added map[string]FunctionHandler +} + +// Params are the host's initialize params. +func (i *Initialize) Params() json.RawMessage { return raw(i.params) } + +// FunctionsVersion is the plugin-function protocol version the backend will +// answer, with false when the host did not offer it. +func (i *Initialize) FunctionsVersion() (uint64, bool) { + return FunctionsVersion, i.functions +} + +// RootPath is the rootUri as a path. For a plugin backend this is the +// plugin's ${stateDir}, also the working directory. +func (i *Initialize) RootPath() (string, bool) { + uri, ok := field(i.params, "rootUri").(string) + if !ok { + return "", false + } + return fileURIPath(uri) +} + +// Function adds a function to the initial list, for example one that +// depends on state found at startup. +func (i *Initialize) Function(id string, handler FunctionHandler) error { + if slices.Contains(i.existing, id) { + return newSdkError("sdk.function.duplicate", fmt.Sprintf("Function %s is already declared.", id)) + } + if len(i.existing)+len(i.added) >= MaxFunctions { + return newSdkError("sdk.function.limit", fmt.Sprintf("A backend serves at most %d functions.", MaxFunctions)) + } + if err := checkNewFunction(id, i.added); err != nil { + return err + } + i.added[id] = handler + return nil +} + +// fileURIPath is the path of a file: URI, percent-decoded. +func fileURIPath(uri string) (string, bool) { + rest, ok := strings.CutPrefix(uri, "file://") + if !ok { + return "", false + } + path := strings.TrimPrefix(rest, "localhost") + if !strings.HasPrefix(path, "/") { + return "", false + } + decoded := make([]byte, 0, len(path)) + for index := 0; index < len(path); { + if path[index] == '%' && index+2 < len(path) { + value, err := strconv.ParseUint(path[index+1:index+3], 16, 8) + if err != nil { + return "", false + } + decoded = append(decoded, byte(value)) + index += 3 + continue + } + decoded = append(decoded, path[index]) + index++ + } + if !utf8.Valid(decoded) { + return "", false + } + result := string(decoded) + // /C:/Users on Windows. + if runtime.GOOS == "windows" && len(result) > 2 && result[2] == ':' { + result = result[1:] + } + for len(result) > 1 && strings.HasSuffix(result, "/") { + result = result[:len(result)-1] + } + return result, true +} + +// Context is one running function call. +type Context struct { + shared *shared + functionID string + operationID any + diagnosticOperationID string + cancellation *Cancellation + host *Host + workspaceContext *WorkspaceContext + caller *Caller + reporting atomic.Bool + quietSuccess atomic.Bool +} + +// SuppressSuccessDiagnostics omits only this call's successful terminal +// fact; failures remain visible. +func (c *Context) SuppressSuccessDiagnostics() { c.quietSuccess.Store(true) } + +// Diagnostics records structured facts correlated with the host's original +// operation ID. +func (c *Context) Diagnostics() *Diagnostics { + return &Diagnostics{shared: c.shared, operationID: c.diagnosticOperationID} +} + +// FunctionID is the ID of the function being called. +func (c *Context) FunctionID() string { return c.functionID } + +// Cancellation fires when the host cancels the call, withdraws its +// function, or shuts the backend down. Core has already ended the call by +// then, so a handler should stop its work and return promptly. +func (c *Context) Cancellation() *Cancellation { return c.cancellation } + +// CheckCancelled returns ErrCancelled once the call is cancelled. +func (c *Context) CheckCancelled() error { return c.cancellation.Check() } + +// Progress reports progress of this call; the host shows the latest report. +// message is cut to 1024 bytes. Reports after the call ended are dropped. +func (c *Context) Progress(message string) { c.progress(message, nil) } + +// ProgressPercent reports progress with a percentage, clamped to 0-100. +func (c *Context) ProgressPercent(message string, percentage int) { + percentage = max(0, min(percentage, 100)) + c.progress(message, &percentage) +} + +func (c *Context) progress(message string, percentage *int) { + if !c.reporting.Load() { + return + } + report := map[string]any{ + "operationID": c.operationID, + "message": boundedText(message, maxErrorMessageBytes), + } + if percentage != nil { + report["percentage"] = *percentage + } + c.shared.write(map[string]any{"jsonrpc": "2.0", "method": methodProgress, "params": report}) +} + +// Host is the host services of this call. A request still waiting for the +// host when the call is cancelled or ends fails with sdk.call.cancelled, +// which counts as a cancelled answer when returned; the SDK also cancels it +// on the wire. +func (c *Context) Host() *Host { return c.host } + +// WorkspaceContext is the { contextID, generation } of the window the call +// came from; nil for calls without one, such as from the plugin's own UI. +func (c *Context) WorkspaceContext() *WorkspaceContext { return c.workspaceContext } + +// Caller is the plugin that called this function through Core's relay; nil +// when the host started the call, and for a caller of any other shape. +func (c *Context) Caller() *Caller { return c.caller } + +// Credentials is Host().Credentials(). +func (c *Context) Credentials() *Credentials { return c.host.Credentials() } + +// Backend is a handle to the backend serving the call. +func (c *Context) Backend() *BackendHandle { return &BackendHandle{shared: c.shared} } + +// Caller is the plugin that called a function through Core's relay. Core +// writes it from the identity of the calling session and a caller cannot +// supply it, so a provider may key per-caller state by it. +type Caller struct { + pluginID string +} + +// callerFromValue reads the caller of a relayed call, which is exactly +// { pluginID } with a non-empty string. +func callerFromValue(value any) *Caller { + object, ok := value.(map[string]any) + if !ok || len(object) != 1 { + return nil + } + pluginID, ok := object["pluginID"].(string) + if !ok || pluginID == "" { + return nil + } + return &Caller{pluginID: pluginID} +} + +// PluginID is the calling plugin's ID, such as dev.lithe.fixture.python. +func (c *Caller) PluginID() string { return c.pluginID } + +// KeymapImportRequest is a single host-authorized source snapshot for a +// shortcut import. +type KeymapImportRequest struct { + providerID string + snapshotID string +} + +// KeymapSourceFile is a source file in the host's selected, read-only +// snapshot. Path is relative to the selected source and only a label, never +// authority. +type KeymapSourceFile struct { + ID string + Path string + ByteCount uint64 +} + +// ProviderID is the provider the host called. +func (r KeymapImportRequest) ProviderID() string { return r.providerID } + +// SnapshotID names the snapshot the host captured. +func (r KeymapImportRequest) SnapshotID() string { return r.snapshotID } + +// ListInputs lists the declared files captured for this request. +func (r KeymapImportRequest) ListInputs(host *Host) ([]KeymapSourceFile, error) { + result, err := host.request(methodKeymapInputs, map[string]any{"providerID": r.providerID, "snapshotID": r.snapshotID}) + if err != nil { + return nil, err + } + invalid := newSdkError("sdk.keymap.invalidResponse", "Invalid shortcut source list.") + entries, ok := field(result, "files").([]any) + if !ok || len(entries) > 128 { + return nil, invalid + } + files := make([]KeymapSourceFile, 0, len(entries)) + for _, entry := range entries { + id, ok := field(entry, "id").(string) + if !ok || !validSnapshotID(id) { + return nil, invalid + } + path, ok := field(entry, "path").(string) + if !ok || path == "" || len(path) > 4096 { + return nil, invalid + } + size, ok := unsignedInteger(field(entry, "byteCount")) + if !ok || size > 1_048_576 { + return nil, invalid + } + files = append(files, KeymapSourceFile{ID: id, Path: path, ByteCount: size}) + } + return files, nil +} + +// ReadChunk reads one bounded chunk, at most maximumBytes (1-131072) from +// offset (at most 1 MiB), of a file ID ListInputs returned. +func (r KeymapImportRequest) ReadChunk(host *Host, fileID string, offset uint64, maximumBytes uint32) ([]byte, error) { + invalid := newSdkError("sdk.keymap.invalidChunk", "Invalid shortcut source chunk.") + if !validSnapshotID(fileID) || offset > 1_048_576 || maximumBytes == 0 || maximumBytes > 131_072 { + return nil, invalid + } + result, err := host.request(methodKeymapChunk, map[string]any{ + "providerID": r.providerID, "snapshotID": r.snapshotID, + "fileID": fileID, "offset": offset, "maximumBytes": maximumBytes, + }) + if err != nil { + return nil, err + } + encoded, ok := field(result, "data").(string) + // Standard base64 with padding and nothing else; the decoder would skip + // line breaks. + if !ok || len(encoded) > 174_764 || strings.ContainsAny(encoded, "\r\n") { + return nil, invalid + } + data, err := base64.StdEncoding.Strict().DecodeString(encoded) + if err != nil || len(data) > int(maximumBytes) { + return nil, invalid + } + return data, nil +} + +func validKeymapProviderID(id string) bool { + if id == "" || len(id) > 64 || id[0] < 'a' || id[0] > 'z' { + return false + } + for i := 0; i < len(id); i++ { + c := id[i] + if !(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && c != '-' { + return false + } + } + return true +} + +func validSnapshotID(id string) bool { + if id == "" || len(id) > 128 { + return false + } + for i := 0; i < len(id); i++ { + if !isASCIIAlnum(id[i]) && id[i] != '-' && id[i] != '_' { + return false + } + } + return true +} + +// BackendHandle is a handle to a backend for any goroutine. +type BackendHandle struct { + shared *shared +} + +// Diagnostics records structured facts outside a call; no operation ID is +// fabricated. +func (h *BackendHandle) Diagnostics() *Diagnostics { return &Diagnostics{shared: h.shared} } + +// FunctionsVersion is the negotiated plugin-function protocol version, with +// false before initialize or when the host did not offer it. +func (h *BackendHandle) FunctionsVersion() (uint64, bool) { + return FunctionsVersion, h.shared.functionsNegotiated() +} + +// FunctionIDs are the IDs of the functions the backend currently serves, +// sorted. +func (h *BackendHandle) FunctionIDs() []string { + h.shared.mu.Lock() + defer h.shared.mu.Unlock() + return sortedKeys(h.shared.state.functions) +} + +// RegisterFunction adds a function after initialize and waits until the +// host accepted it. The handler is installed first, because the host may +// invoke it as soon as its registry changed. +func (h *BackendHandle) RegisterFunction(id string, handler FunctionHandler) error { + s := h.shared + s.registrations.Lock() + defer s.registrations.Unlock() + s.mu.Lock() + err := s.requireFunctions() + if err == nil { + err = checkNewFunction(id, s.state.functions) + } + if err != nil { + s.mu.Unlock() + return err + } + s.state.functions[id] = handler + s.mu.Unlock() + if _, err := s.request(methodRegister, map[string]any{"functions": []any{map[string]any{"id": id}}}); err != nil { + s.mu.Lock() + delete(s.state.functions, id) + s.mu.Unlock() + return err + } + return nil +} + +// UnregisterFunction withdraws a function and waits until the host accepted +// it. The host ends the function's running calls as revoked, and the SDK +// cancels them. A handler must not withdraw its own function: that revokes +// the call it runs in. +func (h *BackendHandle) UnregisterFunction(id string) error { + s := h.shared + s.registrations.Lock() + defer s.registrations.Unlock() + s.mu.Lock() + err := s.requireFunctions() + if _, registered := s.state.functions[id]; err == nil && !registered { + err = newSdkError("sdk.function.unknown", fmt.Sprintf("Function %s is not registered.", id)) + } + s.mu.Unlock() + if err != nil { + return err + } + if _, err := s.request(methodUnregister, map[string]any{"ids": []any{id}}); err != nil { + return err + } + s.mu.Lock() + delete(s.state.functions, id) + delete(s.state.quietSuccess, id) + var tokens []*Cancellation + for _, call := range s.state.incoming { + if call.functionID == id { + tokens = append(tokens, call.cancellation) + } + } + s.mu.Unlock() + for _, token := range tokens { + token.Cancel() + } + return nil +} + +// Host is the host services for work outside a function call; usable once +// the session is ready. +func (h *BackendHandle) Host() *Host { return &Host{shared: h.shared} } + +// Credentials is Host().Credentials(). +func (h *BackendHandle) Credentials() *Credentials { return h.Host().Credentials() } diff --git a/shared/plugins/sdk/go/lithe/backend_internal_test.go b/shared/plugins/sdk/go/lithe/backend_internal_test.go new file mode 100644 index 00000000..48b67de0 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/backend_internal_test.go @@ -0,0 +1,115 @@ +package lithe + +import ( + "errors" + "runtime" + "slices" + "sync" + "testing" + "time" +) + +func TestFileURIsBecomePaths(t *testing.T) { + if runtime.GOOS == "windows" { + if path, ok := fileURIPath("file:///C:/Users/me/"); !ok || path != "C:/Users/me" { + t.Errorf("drive path = %q, %t", path, ok) + } + } + for uri, want := range map[string]string{ + "file:///var/state/": "/var/state", + "file://localhost/a%20b/%C3%A9": "/a b/é", + "file:///": "/", + } { + if path, ok := fileURIPath(uri); !ok || path != want { + t.Errorf("%s = %q, %t", uri, path, ok) + } + } + for _, invalid := range []string{"https://example.com/", "file:///bad%zz", "file://host/share", "file:///%FF"} { + if path, ok := fileURIPath(invalid); ok { + t.Errorf("%s = %q", invalid, path) + } + } +} + +func TestCancellationWakesWaitersAndRunsCallbacksOnce(t *testing.T) { + cancellation := NewCancellation() + if cancellation.WaitTimeout(0) { + t.Fatal("a new token is cancelled") + } + var ( + mu sync.Mutex + received []string + ) + record := func(name string) func() { + return func() { + mu.Lock() + received = append(received, name) + mu.Unlock() + } + } + cancellation.OnCancel(record("registered")) + context := cancellation.Context() + if context.Err() != nil { + t.Fatal("the context of a new token is done") + } + woke := make(chan bool, 1) + go func() { woke <- cancellation.WaitTimeout(10 * time.Second) }() + cancellation.Cancel() + cancellation.Cancel() + select { + case cancelled := <-woke: + if !cancelled { + t.Error("the waiter saw no cancellation") + } + case <-time.After(10 * time.Second): + t.Fatal("the waiter did not wake") + } + cancellation.OnCancel(record("late")) + mu.Lock() + got := slices.Clone(received) + mu.Unlock() + if !slices.Equal(got, []string{"registered", "late"}) { + t.Errorf("callbacks = %v", got) + } + if !errors.Is(cancellation.Check(), ErrCancelled) { + t.Error("Check does not report the cancellation") + } + select { + case <-context.Done(): + case <-time.After(10 * time.Second): + t.Fatal("the token's context was not cancelled") + } + if cancellation.Context() != context { + t.Error("Context returns a new context") + } + select { + case <-cancellation.Done(): + default: + t.Error("Done is open after Cancel") + } +} + +func TestAContextOfACancelledTokenIsDone(t *testing.T) { + cancellation := NewCancellation() + cancellation.Cancel() + if cancellation.Context().Err() == nil { + t.Error("the context of a cancelled token is not done") + } +} + +func TestAWatchCanBeWithdrawn(t *testing.T) { + cancellation := NewCancellation() + ran := false + id, ok := cancellation.watch(func() { ran = true }) + if !ok { + t.Fatal("a new token refused a watch") + } + cancellation.unwatch(id) + cancellation.Cancel() + if ran { + t.Error("a withdrawn callback ran") + } + if _, ok := cancellation.watch(func() {}); ok { + t.Error("a cancelled token accepted a watch") + } +} diff --git a/shared/plugins/sdk/go/lithe/cancellation.go b/shared/plugins/sdk/go/lithe/cancellation.go new file mode 100644 index 00000000..3d9b2c1d --- /dev/null +++ b/shared/plugins/sdk/go/lithe/cancellation.go @@ -0,0 +1,133 @@ +package lithe + +import ( + "context" + "sync" + "time" +) + +type watcher struct { + id uint64 + callback func() +} + +// Cancellation is a call's cancellation token. Lithe cancels it when the +// host cancels the call, when the call is unregistered, and when the session +// ends. +type Cancellation struct { + mu sync.Mutex + cancelled bool + done chan struct{} + callbacks []watcher + nextWatch uint64 + ctxOnce sync.Once + ctx context.Context +} + +// NewCancellation returns a token that is not cancelled. +func NewCancellation() *Cancellation { + return &Cancellation{done: make(chan struct{})} +} + +// IsCancelled reports whether the token was cancelled. +func (c *Cancellation) IsCancelled() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.cancelled +} + +// Check returns ErrCancelled once the token was cancelled. +func (c *Cancellation) Check() error { + if c.IsCancelled() { + return ErrCancelled + } + return nil +} + +// Done is closed when the token is cancelled. +func (c *Cancellation) Done() <-chan struct{} { return c.done } + +// Context is a context.Context cancelled with the token, for code that takes +// one, such as exec.CommandContext or http.NewRequestWithContext. Every call +// returns the same context. +func (c *Cancellation) Context() context.Context { + c.ctxOnce.Do(func() { + ctx, cancel := context.WithCancel(context.Background()) + c.ctx = ctx + c.OnCancel(cancel) + }) + return c.ctx +} + +// WaitTimeout waits up to timeout and reports whether the token was +// cancelled. +func (c *Cancellation) WaitTimeout(timeout time.Duration) bool { + timer := time.NewTimer(timeout) + defer timer.Stop() + select { + case <-c.done: + return true + case <-timer.C: + return c.IsCancelled() + } +} + +// OnCancel runs callback once the token is cancelled, at once when it +// already is. +func (c *Cancellation) OnCancel(callback func()) { + c.watch(callback) +} + +// Cancel cancels the token. Only the first call has an effect; callbacks run +// outside the token's lock. +func (c *Cancellation) Cancel() { + c.mu.Lock() + if c.cancelled { + c.mu.Unlock() + return + } + c.cancelled = true + close(c.done) + callbacks := c.callbacks + c.callbacks = nil + c.mu.Unlock() + for _, watch := range callbacks { + watch.callback() + } +} + +// watch registers callback and returns its ID; when the token is already +// cancelled it runs callback and returns false. +func (c *Cancellation) watch(callback func()) (uint64, bool) { + c.mu.Lock() + if c.cancelled { + c.mu.Unlock() + callback() + return 0, false + } + c.nextWatch++ + id := c.nextWatch + c.callbacks = append(c.callbacks, watcher{id, callback}) + c.mu.Unlock() + return id, true +} + +func (c *Cancellation) unwatch(id uint64) { + c.mu.Lock() + for i, watch := range c.callbacks { + if watch.id == id { + c.callbacks = append(c.callbacks[:i:i], c.callbacks[i+1:]...) + break + } + } + c.mu.Unlock() +} + +func anyCancelled(scope []*Cancellation) bool { + for _, token := range scope { + if token.IsCancelled() { + return true + } + } + return false +} diff --git a/shared/plugins/sdk/go/lithe/diagnostics.go b/shared/plugins/sdk/go/lithe/diagnostics.go new file mode 100644 index 00000000..ae9248c3 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/diagnostics.go @@ -0,0 +1,178 @@ +package lithe + +import ( + "slices" + "strconv" + "time" +) + +// operations are the fixed operations a diagnostic may name besides the +// backend's registered functions. +var operations = []string{ + "initialize", + "shutdown", + "notification", + "function-call", + "result-encoding", + "lithe/build/model", + "lithe/build/dependencies", + "lithe/build/execute", + "lithe/build/test", + "lithe/build/discoverTests", + "lithe/build/prepareRun", + "lithe/build/prepareDebug", + "lithe/build/runEntrypoints", + "lithe/vcs/status", + "lithe/vcs/baseContent", + "lithe/vcs/history", + "lithe/vcs/fileHistory", + "lithe/vcs/annotate", + "lithe/vcs/checkin", + "lithe/vcs/rollback", + "lithe/vcs/update", + "lithe/vcs/fileOperation", + "lithe/vcs/resolve", + "lithe/vcs/cleanup", + methodKeymapImport, +} + +// maxEarlyDiagnostics is how many facts recorded during initialize wait for +// its answer. +const maxEarlyDiagnostics = 8 + +// token reports whether value is 1-maximum ASCII letters, digits, ".", "_", +// ":", "/", "-" or "$". +func token(value string, maximum int) bool { + if value == "" || len(value) > maximum { + return false + } + for i := 0; i < len(value); i++ { + c := value[i] + if !isASCIIAlnum(c) && c != '.' && c != '_' && c != ':' && c != '/' && c != '-' && c != '$' { + return false + } + } + return true +} + +// requestOperationID is the operation ID diagnostics carry: the call's +// operationID when it is a token, otherwise its JSON-RPC ID; "" for none. +func requestOperationID(operationID, requestID any) string { + if id, ok := operationID.(string); ok && token(id, 128) { + return id + } + var fallback string + switch id := requestID.(type) { + case string: + fallback = id + default: + number, ok := integer(id) + if !ok || number > maxSafeInteger || number < -maxSafeInteger { + return "" + } + fallback = strconv.FormatInt(number, 10) + } + if !token(fallback, 128) { + return "" + } + return fallback +} + +// Diagnostics records typed facts in the host's litheLogging catalog over +// the protocol stream, without a queue or file I/O. +type Diagnostics struct { + shared *shared + operationID string +} + +// Degraded records a handled degradation. code is a controlled category, +// never an error message; pass at most one count. +func (d *Diagnostics) Degraded(operation, code string, count ...uint64) error { + return d.record("degraded", operation, &code, first(count), nil) +} + +// Recovered records a real recovery, with the same controlled operation +// and category as Degraded. +func (d *Diagnostics) Recovered(operation, code string, count ...uint64) error { + return d.record("recovered", operation, &code, first(count), nil) +} + +func first(values []uint64) *uint64 { + if len(values) == 0 { + return nil + } + return &values[0] +} + +// terminal records how an operation ended; err is nil for success. +func (d *Diagnostics) terminal(operation string, err error, started time.Time) { + kind := "operationFinished" + var code *string + if err != nil { + kind = "operationFailed" + // A plugin error logs its own code; any other failure only its kind. + category := failureKind(err) + if errorKind, plugin := classify(err); errorKind == kindPlugin { + category = plugin.code + } + code = &category + } + duration := elapsed(started) + _ = d.record(kind, operation, code, nil, &duration) +} + +func elapsed(started time.Time) uint64 { + milliseconds := time.Since(started).Milliseconds() + if milliseconds < 0 { + return 0 + } + return min(uint64(milliseconds), maxSafeInteger) +} + +func (d *Diagnostics) record(kind, operation string, code *string, count, duration *uint64) error { + s := d.shared + s.mu.Lock() + _, registered := s.state.functions[operation] + enabled := s.state.logging + s.mu.Unlock() + if !slices.Contains(operations, operation) && !registered { + return newSdkError("sdk.logging.invalidOperation", "Diagnostics need a registered operation.") + } + if code != nil && !token(*code, 64) { + return newSdkError("sdk.logging.invalidCode", "Diagnostics need a controlled code.") + } + if count != nil && *count > maxSafeInteger { + return newSdkError("sdk.logging.invalidCount", "Diagnostics need a safe count.") + } + if !enabled { + return nil + } + named := operation + if len(named) > 64 { + named = "function-call" + } + params := map[string]any{"kind": kind, "operation": named} + if code != nil { + params["code"] = *code + } + if count != nil { + params["count"] = *count + } + if duration != nil { + params["durationMs"] = *duration + } + if token(d.operationID, 128) { + params["operationId"] = d.operationID + } + s.mu.Lock() + if !s.state.loggingReady { + if len(s.state.earlyDiagnostics) < maxEarlyDiagnostics { + s.state.earlyDiagnostics = append(s.state.earlyDiagnostics, params) + } + s.mu.Unlock() + return nil + } + s.mu.Unlock() + s.write(map[string]any{"jsonrpc": "2.0", "method": methodLog, "params": params}) + return nil +} diff --git a/shared/plugins/sdk/go/lithe/errors.go b/shared/plugins/sdk/go/lithe/errors.go new file mode 100644 index 00000000..2e06b155 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/errors.go @@ -0,0 +1,232 @@ +package lithe + +import ( + "errors" + "fmt" + "strings" +) + +// SDK error codes a caller may compare against. +const ( + CodeCallCancelled = "sdk.call.cancelled" + CodeSessionClosed = "sdk.session.closed" +) + +// ErrorCode pairs a host or relay error code with its JSON-RPC number. +type ErrorCode struct { + Code string + Number int64 +} + +// HostErrorCodes are the codes Lithe answers host requests with, and the +// number each one travels as. +var HostErrorCodes = []ErrorCode{ + {"plugin.host.unavailable", -32601}, + {"plugin.host.invalidParams", -32602}, + {"plugin.host.failed", -32603}, + {"plugin.host.cancelled", -32800}, + {"plugin.host.permissionDenied", -32010}, + {"plugin.host.contextExpired", -32011}, + {"plugin.host.authorityUnsupported", -32012}, + {"plugin.host.versionConflict", -32013}, + {"plugin.host.limitExceeded", -32014}, + {"plugin.host.timeout", -32015}, + {"plugin.host.notFound", -32016}, + {"plugin.host.readOnly", -32017}, + {"plugin.host.unsupportedOption", -32018}, + {"plugin.host.preconditionFailed", -32019}, + {"plugin.host.busy", -32020}, + {"plugin.host.rateLimited", -32021}, + {"plugin.host.languageServerUnavailable", -32022}, + {"plugin.host.languageServerError", -32023}, + {"plugin.host.methodNotDeclared", -32024}, + {"plugin.host.toolUnresolved", -32025}, + {"plugin.host.foreignContribution", -32026}, +} + +// RelayErrorCodes are the codes a cross-plugin call fails with. +var RelayErrorCodes = []ErrorCode{ + {"plugin.function.notDeclared", -32027}, + {"plugin.function.notExported", -32028}, + {"plugin.function.providerDisabled", -32029}, + {"plugin.function.versionMismatch", -32030}, + {"plugin.function.callCycle", -32065}, + {"plugin.function.depthExceeded", -32066}, + {"plugin.function.tooManyCalls", -32067}, + {"plugin.function.payloadTooLarge", -32068}, + {"plugin.function.providerUnavailable", -32069}, + {"plugin.function.failed", -32070}, + {"plugin.function.invalidResult", -32071}, +} + +// PluginError is a failure the plugin reports to the caller with its own +// code; the caller sees the code and the message. +type PluginError struct { + code string + message string +} + +// NewPluginError returns a plugin error. It panics when code is not a +// plugin error code: a code is part of the plugin's API, so a malformed one +// is a programming error. +func NewPluginError(code, message string) *PluginError { + if !IsPluginErrorCode(code) { + panic(fmt.Sprintf("Plugin error code %q must start with a letter, use letters, digits, \".\", \"_\" or \"-\", and be at most 64 bytes.", code)) + } + return &PluginError{code: code, message: message} +} + +// Code is the plugin's error code. +func (e *PluginError) Code() string { return e.code } + +// Message is the text the caller sees. +func (e *PluginError) Message() string { return e.message } + +func (e *PluginError) Error() string { return e.code + ": " + e.message } + +// ErrCancelled ends a call that stopped because it was cancelled. Return it +// (or wrap it) from a handler that saw its cancellation. +var ErrCancelled = errors.New("The call was cancelled.") + +// SdkError is a failure of the SDK or of a host request: a host refusal +// keeps the code, JSON-RPC number and details Lithe sent. +type SdkError struct { + code string + message string + rpcCode *int64 + details map[string]any +} + +func newSdkError(code, message string) *SdkError { + return &SdkError{code: code, message: message} +} + +// Code is the error code, such as "plugin.host.permissionDenied". +func (e *SdkError) Code() string { return e.code } + +// Message is the text of the error. +func (e *SdkError) Message() string { return e.message } + +// RPCCode is the JSON-RPC error number of a host refusal. +func (e *SdkError) RPCCode() (int64, bool) { + if e.rpcCode == nil { + return 0, false + } + return *e.rpcCode, true +} + +// Details are the structured details of a host refusal, or nil. +func (e *SdkError) Details() map[string]any { return e.details } + +func (e *SdkError) Error() string { return e.code + ": " + e.message } + +// Is makes errors.Is(err, ErrCancelled) true for a cancelled host request. +func (e *SdkError) Is(target error) bool { + return target == ErrCancelled && e.code == CodeCallCancelled +} + +func unavailable(message string) *SdkError { + number := int64(rpcMethodNotFound) + return &SdkError{code: "plugin.host.unavailable", message: message, rpcCode: &number} +} + +func cancelledError() *SdkError { + return newSdkError(CodeCallCancelled, "The request was cancelled.") +} + +func closedError() *SdkError { + return newSdkError(CodeSessionClosed, "The session ended.") +} + +// sdkErrorFromResponse maps a JSON-RPC error a host request was answered with. +func sdkErrorFromResponse(method string, value any) *SdkError { + object, _ := value.(map[string]any) + var number *int64 + if raw, ok := object["code"]; ok { + if parsed, ok := integer(raw); ok { + number = &parsed + } + } + data, _ := object["data"].(map[string]any) + code, ok := data["code"].(string) + if !ok { + if strings.HasPrefix(method, hostPrefix) { + code = "plugin.host.failed" + if number != nil { + for _, table := range [][]ErrorCode{HostErrorCodes, RelayErrorCodes} { + for _, known := range table { + if known.Number == *number { + code = known.Code + } + } + } + } + } else { + code = "sdk.host.error" + } + } + message, ok := object["message"].(string) + if !ok { + message = method + " failed." + } + details, _ := data["details"].(map[string]any) + return &SdkError{code: code, message: message, rpcCode: number, details: details} +} + +// errorKind sorts a handler error into the three answers a call can give. +type errorKind int + +const ( + kindPlugin errorKind = iota + kindCancelled + kindInternal +) + +func classify(err error) (errorKind, *PluginError) { + var plugin *PluginError + if errors.As(err, &plugin) { + return kindPlugin, plugin + } + if errors.Is(err, ErrCancelled) { + return kindCancelled, nil + } + return kindInternal, nil +} + +// failureKind is the fixed category a failure is logged with; its text can +// hold user data and is never logged. +func failureKind(err error) string { + switch kind, _ := classify(err); kind { + case kindPlugin: + return "plugin_error" + case kindCancelled: + return "cancelled" + default: + return "internal_error" + } +} + +func cancelledResponse() map[string]any { + return map[string]any{"code": rpcRequestCancelled, "message": "The request was cancelled."} +} + +func internalResponse() map[string]any { + return map[string]any{"code": rpcInternalError, "message": "The plugin backend failed unexpectedly."} +} + +// responseError is the JSON-RPC error a failed call is answered with. An +// internal error's text stays in the backend. +func responseError(err error) map[string]any { + switch kind, plugin := classify(err); kind { + case kindCancelled: + return cancelledResponse() + case kindPlugin: + return map[string]any{ + "code": rpcRequestFailed, + "message": boundedText(plugin.message, maxErrorMessageBytes), + "data": map[string]any{"code": plugin.code}, + } + default: + return internalResponse() + } +} diff --git a/shared/plugins/sdk/go/lithe/errors_test.go b/shared/plugins/sdk/go/lithe/errors_test.go new file mode 100644 index 00000000..bb25ba35 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/errors_test.go @@ -0,0 +1,130 @@ +package lithe + +import ( + "errors" + "fmt" + "strings" + "testing" +) + +func TestOnlyPluginErrorsReachTheHostWithTheirMessageAndCode(t *testing.T) { + plugin := responseError(NewPluginError("db.locked", strings.Repeat("é", 600))) + if plugin["code"] != rpcRequestFailed { + t.Errorf("code = %v", plugin["code"]) + } + if code := plugin["data"].(map[string]any)["code"]; code != "db.locked" { + t.Errorf("data.code = %v", code) + } + if message := plugin["message"].(string); len(message) != 1024 { + t.Errorf("message is %d bytes", len(message)) + } + // A wrapped plugin error still reaches the host. + wrapped := responseError(fmt.Errorf("context: %w", NewPluginError("db.locked", "Locked."))) + if wrapped["message"] != "Locked." { + t.Errorf("wrapped = %v", wrapped) + } + assertJSON(t, responseError(errors.New("/home/me/secret: No such file")), canonical(t, internalResponse())) + if responseError(ErrCancelled)["code"] != rpcRequestCancelled { + t.Error("a cancelled call is not answered as cancelled") + } + // A host request cut short by the call's cancellation ends the call as + // cancelled. + if !errors.Is(cancelledError(), ErrCancelled) { + t.Error("a cancelled host request is not ErrCancelled") + } + if responseError(cancelledError())["code"] != rpcRequestCancelled { + t.Error("a cancelled host request is not answered as cancelled") + } +} + +func TestHostFailuresKeepTheirCodeOrTakeItFromTheNumber(t *testing.T) { + coded := sdkErrorFromResponse(methodCredentialsGet, mustValue(t, + `{"code":-32010,"message":"No.","data":{"code":"plugin.host.permissionDenied","details":{"a":1}}}`)) + if coded.Code() != "plugin.host.permissionDenied" { + t.Errorf("code = %s", coded.Code()) + } + if number, ok := coded.RPCCode(); !ok || number != -32010 { + t.Errorf("rpc code = %d, %t", number, ok) + } + assertJSON(t, coded.Details(), `{"a":1}`) + for _, known := range HostErrorCodes { + failure := sdkErrorFromResponse(methodCredentialsGet, mustValue(t, fmt.Sprintf(`{"code":%d}`, known.Number))) + if failure.Code() != known.Code { + t.Errorf("%d: code = %s, want %s", known.Number, failure.Code(), known.Code) + } + if failure.Message() != "lithe/host/credentials/get failed." { + t.Errorf("%d: message = %s", known.Number, failure.Message()) + } + } + later := sdkErrorFromResponse(methodCredentialsGet, mustValue(t, + `{"code":-32050,"message":"x","data":{"details":["not","an","object"]}}`)) + if later.Code() != "plugin.host.failed" || later.Details() != nil { + t.Errorf("later = %s, %v", later.Code(), later.Details()) + } + other := sdkErrorFromResponse(methodRegister, mustValue(t, `{"code":-32602}`)) + if other.Code() != "sdk.host.error" { + t.Errorf("other = %s", other.Code()) + } +} + +func TestTheHostAndRelayTablesHoldEveryDocumentedCodeOnce(t *testing.T) { + if len(HostErrorCodes) != 21 || len(RelayErrorCodes) != 11 { + t.Fatalf("tables hold %d and %d codes", len(HostErrorCodes), len(RelayErrorCodes)) + } + codes := map[string]bool{} + numbers := map[int64]bool{} + for _, table := range []struct { + prefix string + codes []ErrorCode + }{{"plugin.host.", HostErrorCodes}, {"plugin.function.", RelayErrorCodes}} { + for _, known := range table.codes { + if !strings.HasPrefix(known.Code, table.prefix) { + t.Errorf("%s does not start with %s", known.Code, table.prefix) + } + if codes[known.Code] { + t.Errorf("%s is listed twice", known.Code) + } + if numbers[known.Number] { + t.Errorf("%d names two codes", known.Number) + } + codes[known.Code], numbers[known.Number] = true, true + } + } +} + +func TestRelayFailuresKeepTheirCodeNumberAndTheProvidersOwnCode(t *testing.T) { + for _, known := range RelayErrorCodes { + failure := sdkErrorFromResponse(methodRelayInvoke, mustValue(t, fmt.Sprintf(`{"code":%d}`, known.Number))) + number, _ := failure.RPCCode() + if failure.Code() != known.Code || number != known.Number { + t.Errorf("%d: %s, %d", known.Number, failure.Code(), number) + } + if failure.Message() != "lithe/host/functions/invoke failed." { + t.Errorf("%d: message = %s", known.Number, failure.Message()) + } + } + failed := sdkErrorFromResponse(methodRelayInvoke, mustValue(t, `{ + "code": -32070, + "message": "The plugin function failed.", + "data": {"code": "plugin.function.failed", "details": {"pluginErrorCode": "go.noModule"}} + }`)) + if failed.Code() != "plugin.function.failed" || failed.Message() != "The plugin function failed." { + t.Errorf("failed = %s, %s", failed.Code(), failed.Message()) + } + assertJSON(t, failed.Details(), `{"pluginErrorCode":"go.noModule"}`) + // Outside a host method a relay number stays an unnamed answer. + outside := sdkErrorFromResponse(methodRegister, mustValue(t, `{"code":-32070}`)) + if outside.Code() != "sdk.host.error" { + t.Errorf("outside = %s", outside.Code()) + } +} + +func TestAnInvalidPluginErrorCodeIsAProgrammingError(t *testing.T) { + defer func() { + message, _ := recover().(string) + if !strings.Contains(message, "must start with a letter") { + t.Errorf("panic = %q", message) + } + }() + NewPluginError("1bad", "message") +} diff --git a/shared/plugins/sdk/go/lithe/framing.go b/shared/plugins/sdk/go/lithe/framing.go new file mode 100644 index 00000000..bb38eacb --- /dev/null +++ b/shared/plugins/sdk/go/lithe/framing.go @@ -0,0 +1,111 @@ +package lithe + +import ( + "bufio" + "errors" + "fmt" + "io" + "strconv" + "strings" +) + +const ( + maxHeaderBytes = 8192 + maxMessageBytes = 64 << 20 +) + +// framingError ends the session: the stream can no longer be read in step. +type framingError struct{ message string } + +func (e *framingError) Error() string { return e.message } + +// frame is one message read from the host. A body that is not JSON is +// malformed; the stream stays in step and the session goes on. +type frame struct { + value any + malformed bool +} + +// readFrame reads one Content-Length framed message. It returns nil, nil +// when the input ends between messages. +func readFrame(reader *bufio.Reader) (*frame, error) { + var ( + total int + length string + found bool + started bool + line []byte + finished bool + ) + for !finished { + b, err := reader.ReadByte() + if err != nil { + if errors.Is(err, io.EOF) { + if !started { + return nil, nil + } + return nil, &framingError{"The input ended inside a message header."} + } + return nil, &framingError{"The input failed: " + err.Error()} + } + started = true + total++ + if total > maxHeaderBytes { + return nil, &framingError{"The message header is too long."} + } + if b != '\n' { + line = append(line, b) + continue + } + text := strings.TrimSuffix(string(line), "\r") + line = line[:0] + if text == "" { + finished = true + continue + } + name, value, ok := strings.Cut(text, ":") + if ok && !found && strings.EqualFold(strings.TrimSpace(name), "content-length") { + length, found = strings.TrimSpace(value), true + } + } + size, valid := contentLength(length, found) + if !valid { + return nil, &framingError{"A message has no valid Content-Length header."} + } + if size > maxMessageBytes { + return nil, &framingError{fmt.Sprintf("A message of %d bytes exceeds the %d-byte limit.", size, maxMessageBytes)} + } + body := make([]byte, size) + if _, err := io.ReadFull(reader, body); err != nil { + return nil, &framingError{"The input failed: " + err.Error()} + } + value, err := decodeJSON(body) + if err != nil { + return &frame{malformed: true}, nil + } + return &frame{value: value}, nil +} + +func contentLength(value string, found bool) (uint64, bool) { + if !found || value == "" { + return 0, false + } + for i := 0; i < len(value); i++ { + if value[i] < '0' || value[i] > '9' { + return 0, false + } + } + size, err := strconv.ParseUint(value, 10, 64) + return size, err == nil +} + +// writeFrame writes one framed message and flushes it. +func writeFrame(writer *bufio.Writer, body []byte) error { + if _, err := fmt.Fprintf(writer, "Content-Length: %d\r\n\r\n", len(body)); err != nil { + return err + } + if _, err := writer.Write(body); err != nil { + return err + } + return writer.Flush() +} diff --git a/shared/plugins/sdk/go/lithe/framing_test.go b/shared/plugins/sdk/go/lithe/framing_test.go new file mode 100644 index 00000000..124a4dad --- /dev/null +++ b/shared/plugins/sdk/go/lithe/framing_test.go @@ -0,0 +1,126 @@ +package lithe + +import ( + "bufio" + "bytes" + "fmt" + "reflect" + "strings" + "testing" +) + +type readResult struct { + frame *frame + err error +} + +// readAll reads frames until the input ends or a frame fails, through a +// small buffer so headers cross buffer boundaries. +func readAll(input []byte) []readResult { + reader := bufio.NewReaderSize(bytes.NewReader(input), 16) + var results []readResult + for { + message, err := readFrame(reader) + results = append(results, readResult{message, err}) + if err != nil || message == nil { + return results + } + } +} + +func appendFrame(t *testing.T, input *bytes.Buffer, value any) { + t.Helper() + body, err := encodeJSON(value) + if err != nil { + t.Fatal(err) + } + writer := bufio.NewWriter(input) + if err := writeFrame(writer, body); err != nil { + t.Fatal(err) + } +} + +func TestReadFrameDecodesConsecutiveFramesAndReportsMalformedBodiesInPlace(t *testing.T) { + var input bytes.Buffer + appendFrame(t, &input, map[string]any{"id": 1}) + input.WriteString("content-length: 3\r\nContent-Type: x\r\n\r\nnot") + appendFrame(t, &input, map[string]any{"id": "é"}) + results := readAll(input.Bytes()) + if len(results) != 4 { + t.Fatalf("got %d results, want 4", len(results)) + } + for index, result := range results { + if result.err != nil { + t.Fatalf("frame %d failed: %v", index, result.err) + } + } + if got := canonical(t, results[0].frame.value); got != `{"id":1}` { + t.Errorf("first frame = %s", got) + } + if !results[1].frame.malformed { + t.Errorf("second frame is not malformed") + } + if got := canonical(t, results[2].frame.value); got != `{"id":"é"}` { + t.Errorf("third frame = %s", got) + } + if results[3].frame != nil { + t.Errorf("the input end is a frame") + } +} + +func TestReadFrameRefusesFramesItCannotDelimit(t *testing.T) { + cases := []struct{ input, want string }{ + {"Content-Type: x\r\n\r\n{}", "no valid Content-Length"}, + {"Content-Length: -1\r\n\r\n", "no valid Content-Length"}, + {fmt.Sprintf("Content-Length: %d\r\n\r\n", maxMessageBytes+1), "exceeds"}, + {"X: " + strings.Repeat("a", maxHeaderBytes) + "\r\n\r\n", "too long"}, + {"Content-Length: 2\r\n", "inside a message header"}, + {"Content-Length: 4\r\n\r\n{}", "input failed"}, + } + for _, c := range cases { + results := readAll([]byte(c.input)) + last := results[len(results)-1] + if last.err == nil { + t.Errorf("%q: no error", c.input) + continue + } + if !strings.Contains(last.err.Error(), c.want) { + t.Errorf("%q: %v", c.input, last.err) + } + } +} + +// canonical is value as compact JSON with sorted keys. +func canonical(t *testing.T, value any) string { + t.Helper() + data, err := encodeJSON(value) + if err != nil { + t.Fatal(err) + } + decoded, err := decodeJSON(data) + if err != nil { + t.Fatal(err) + } + data, err = encodeJSON(decoded) + if err != nil { + t.Fatal(err) + } + return string(data) +} + +// mustValue decodes JSON text for a test. +func mustValue(t *testing.T, text string) any { + t.Helper() + value, err := decodeJSON([]byte(text)) + if err != nil { + t.Fatalf("%s: %v", text, err) + } + return value +} + +func assertJSON(t *testing.T, got any, want string) { + t.Helper() + if !reflect.DeepEqual(mustValue(t, canonical(t, got)), mustValue(t, want)) { + t.Errorf("got %s, want %s", canonical(t, got), canonical(t, mustValue(t, want))) + } +} diff --git a/shared/plugins/sdk/go/lithe/harness_test.go b/shared/plugins/sdk/go/lithe/harness_test.go new file mode 100644 index 00000000..a37b0049 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/harness_test.go @@ -0,0 +1,326 @@ +package lithe_test + +// A scripted host for driving a backend session over in-process pipes. +// Every wait is bounded, so a broken session fails with the frames it sent +// instead of hanging. + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + "io" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go/lithe" +) + +const wait = 10 * time.Second + +// testHost is the host side of one session. +type testHost struct { + t *testing.T + input *io.PipeWriter + frames chan map[string]any + exit chan int + closed bool +} + +func startHost(t *testing.T, backend *lithe.Backend) *testHost { + t.Helper() + backendInput, input := io.Pipe() + output, backendOutput := io.Pipe() + host := &testHost{t: t, input: input, frames: make(chan map[string]any, 4096), exit: make(chan int, 1)} + go func() { + code := backend.Serve(backendInput, backendOutput) + // Writes after the session ended fail instead of blocking. + backendInput.CloseWithError(errors.New("the backend ended")) + backendOutput.Close() + host.exit <- code + }() + go func() { + reader := bufio.NewReader(output) + for { + frame, ok := readTestFrame(reader) + if !ok { + close(host.frames) + return + } + host.frames <- frame + } + }() + t.Cleanup(func() { + if !host.closed { + host.input.Close() + select { + case <-host.exit: + case <-time.After(wait): + t.Errorf("the backend did not end after its input closed") + } + } + output.Close() + }) + return host +} + +func readTestFrame(reader *bufio.Reader) (map[string]any, bool) { + length := -1 + for { + line, err := reader.ReadString('\n') + if err != nil { + return nil, false + } + line = strings.TrimRight(line, "\r\n") + if line == "" { + break + } + if value, ok := strings.CutPrefix(line, "Content-Length: "); ok { + if parsed, err := strconv.Atoi(value); err == nil { + length = parsed + } + } + } + if length < 0 { + return nil, false + } + body := make([]byte, length) + if _, err := io.ReadFull(reader, body); err != nil { + return nil, false + } + var frame map[string]any + if err := json.Unmarshal(body, &frame); err != nil { + return nil, false + } + return frame, true +} + +func (h *testHost) sendRaw(data string) { + h.t.Helper() + if _, err := io.WriteString(h.input, data); err != nil { + h.t.Fatalf("write to the backend: %v", err) + } +} + +func (h *testHost) send(message any) { + h.t.Helper() + body, err := json.Marshal(message) + if err != nil { + h.t.Fatal(err) + } + h.sendRaw(fmt.Sprintf("Content-Length: %d\r\n\r\n%s", len(body), body)) +} + +func (h *testHost) request(id any, method string, params any) { + h.t.Helper() + h.send(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}) +} + +func (h *testHost) notify(method string, params any) { + h.t.Helper() + h.send(map[string]any{"jsonrpc": "2.0", "method": method, "params": params}) +} + +// reply answers the host request frame with result. +func (h *testHost) reply(frame map[string]any, result any) { + h.t.Helper() + h.send(map[string]any{"jsonrpc": "2.0", "id": frame["id"], "result": result}) +} + +// refuse answers the host request frame with a JSON-RPC error. +func (h *testHost) refuse(frame map[string]any, failure any) { + h.t.Helper() + h.send(map[string]any{"jsonrpc": "2.0", "id": frame["id"], "error": failure}) +} + +func (h *testHost) next() map[string]any { + h.t.Helper() + select { + case frame, ok := <-h.frames: + if !ok { + h.t.Fatalf("the backend closed its output") + } + return frame + case <-time.After(wait): + h.t.Fatalf("no frame from the backend in time") + } + return nil +} + +// nextWithin is the next frame, if the backend sends one within timeout. +func (h *testHost) nextWithin(timeout time.Duration) (map[string]any, bool) { + select { + case frame, ok := <-h.frames: + return frame, ok + case <-time.After(timeout): + return nil, false + } +} + +// assertQuiet fails when the backend sends a frame within a short wait. +func (h *testHost) assertQuiet() { + h.t.Helper() + if frame, ok := h.nextWithin(200 * time.Millisecond); ok { + h.t.Fatalf("unexpected frame: %s", encode(h.t, frame)) + } +} + +// answer is the answer to request id, after any frames before it. +func (h *testHost) answer(id any) (map[string]any, []map[string]any) { + h.t.Helper() + want := normalize(h.t, id) + var before []map[string]any + for { + frame := h.next() + if _, isRequest := frame["method"]; !isRequest && reflect.DeepEqual(frame["id"], want) { + return frame, before + } + before = append(before, frame) + } +} + +func (h *testHost) initialize(versions any) any { + h.t.Helper() + experimental := map[string]any{"litheLogging": map[string]any{"versions": []any{0}}} + if versions != nil { + experimental["litheFunctions"] = map[string]any{"versions": versions} + } + h.request(0, "initialize", map[string]any{ + "rootUri": "file:///tmp/state/", + "capabilities": map[string]any{"experimental": experimental}, + }) + answer, _ := h.answer(0) + return answer["result"] +} + +func (h *testHost) invoke(id int, function string, params any) { + h.t.Helper() + h.invokeWith(id, function, params, nil) +} + +// invokeWith is an invocation with extra top-level fields (context, caller, +// or a different operationID) merged over the ones invoke sends. +func (h *testHost) invokeWith(id int, function string, params any, extra map[string]any) { + h.t.Helper() + call := map[string]any{"functionID": function, "operationID": fmt.Sprintf("op-%d", id), "params": params} + for key, value := range extra { + call[key] = value + } + h.request(id, "lithe/function/invoke", call) +} + +// close ends the input stream and returns the backend's exit code. +func (h *testHost) close() int { + h.t.Helper() + h.closed = true + h.input.Close() + return h.exitCode() +} + +func (h *testHost) exitCode() int { + h.t.Helper() + select { + case code := <-h.exit: + h.closed = true + return code + case <-time.After(wait): + h.t.Fatalf("the backend did not end in time") + } + return 0 +} + +// j parses JSON text written in a test. +func j(t *testing.T, text string) any { + t.Helper() + var value any + if err := json.Unmarshal([]byte(text), &value); err != nil { + t.Fatalf("%s: %v", text, err) + } + return value +} + +// normalize is value as the harness reads frames: encoded and decoded. +func normalize(t *testing.T, value any) any { + t.Helper() + return j(t, encode(t, value)) +} + +func encode(t *testing.T, value any) string { + t.Helper() + data, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return string(data) +} + +// eq fails unless got is the JSON text want. +func eq(t *testing.T, got any, want string) { + t.Helper() + if !reflect.DeepEqual(normalize(t, got), j(t, want)) { + t.Errorf("got %s\nwant %s", encode(t, got), encode(t, j(t, want))) + } +} + +// at follows object keys and array indexes through a decoded frame. +func at(value any, path ...any) any { + for _, step := range path { + switch key := step.(type) { + case string: + object, _ := value.(map[string]any) + value = object[key] + case int: + array, _ := value.([]any) + if frames, ok := value.([]map[string]any); ok { + array = make([]any, len(frames)) + for i, frame := range frames { + array[i] = frame + } + } + if key < 0 || key >= len(array) { + return nil + } + value = array[key] + } + } + return value +} + +// code is the error code of an SDK error, "" for any other error. +func code(err error) string { + var sdk *lithe.SdkError + if errors.As(err, &sdk) { + return sdk.Code() + } + return "" +} + +func must(t *testing.T, err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } +} + +// within receives one value from channel, failing after the bounded wait. +func within[T any](t *testing.T, channel <-chan T) T { + t.Helper() + select { + case value := <-channel: + return value + case <-time.After(wait): + t.Fatalf("no value in time") + } + var zero T + return zero +} + +// decode unmarshals a handler's params. +func decode(params json.RawMessage) map[string]any { + var object map[string]any + _ = json.Unmarshal(params, &object) + return object +} diff --git a/shared/plugins/sdk/go/lithe/host.go b/shared/plugins/sdk/go/lithe/host.go new file mode 100644 index 00000000..96ef1edf --- /dev/null +++ b/shared/plugins/sdk/go/lithe/host.go @@ -0,0 +1,1161 @@ +package lithe + +// Host services of the plugin-function protocol: the lithe/host/* requests a +// backend sends to Lithe, the subscriptions some of them create, and the +// [Host] handlers use. The backend owns the wire; this file owns what Core +// expects of a well-behaved client -- at most 16 unanswered host requests, +// cancellation through $/cancelRequest, and subscription events routed by ID. +// +// Contract: contract/v1/README.md, "Host services" and the host sections +// after it. + +import ( + "encoding/json" + "errors" + "maps" + "math" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" +) + +// notNegotiated is the answer Core gives a host request when it did not +// offer litheFunctions. +const notNegotiated = "The host did not negotiate plugin functions (litheFunctions), which offer host services." + +// settled is how a request this backend sent ended: the host's result, or +// an error. +type settled struct { + value any + err error +} + +// outgoing is one request this backend sent to the host, until the host +// answers it. +type outgoing struct { + method string + reply chan settled + // slot is whether it holds one of the 16 host-request slots. A cancelled + // request keeps its slot until the host answers. + slot bool + // route is where the events of the subscription it creates go. + route *route +} + +// channel is the session's host-request state, guarded by shared.mu. +type channel struct { + inFlight int + // waiting are the requests waiting for a free slot, in call order. + waiting []uint64 + nextTicket uint64 + // subscribing counts subscribing requests not yet answered; early events + // wait only while there are some. + subscribing int + routes map[string]*route + early []earlyEvent +} + +type earlyEvent struct { + subscriptionID string + sequence uint64 + event any +} + +type route struct { + live *atomic.Bool + queue *eventQueue + last uint64 +} + +func (r *route) emit(subscriptionID string, sequence uint64, event any) { + gap := r.last == math.MaxUint64 || r.last+1 != sequence + r.last = sequence + r.queue.push(Event{subscriptionID: subscriptionID, sequence: sequence, gap: gap, event: event}) +} + +// refusal is why the state refuses a new request, if it does. The caller +// holds mu. +func refusal(st *state, scope []*Cancellation) error { + switch st.phase { + case phaseReady: + if anyCancelled(scope) { + return cancelledError() + } + return nil + case phaseExited: + return closedError() + default: + return newSdkError("sdk.session.notReady", "The session is not initialized.") + } +} + +// exchange sends a request to the host and waits for its answer, the end of +// the session, or the cancellation of a token in scope. A request with a +// slot first waits its turn among the 16 the host accepts at once. +func (s *shared) exchange(method string, params any, slot bool, scope []*Cancellation, rt *route) (any, error) { + id := "sdk-" + strconv.FormatUint(s.nextRequest.Add(1), 10) + reply := make(chan settled, 1) + abort := make(chan struct{}) + var once sync.Once + wake := func() { once.Do(func() { close(abort) }) } + type watched struct { + token *Cancellation + id uint64 + } + var watches []watched + for _, token := range scope { + if watchID, ok := token.watch(wake); ok { + watches = append(watches, watched{token, watchID}) + } + } + var live *atomic.Bool + if rt != nil { + live = rt.live + } + result, cancelled := s.sendAndWait(id, method, params, slot, scope, rt, reply, abort) + for _, watch := range watches { + watch.token.unwatch(watch.id) + } + if !cancelled { + return result.value, result.err + } + s.mu.Lock() + if live != nil { + // Answered just before the cancellation won. + for subscriptionID, existing := range s.state.channel.routes { + if existing.live == live { + delete(s.state.channel.routes, subscriptionID) + existing.queue.close() + } + } + } + entry, pending := s.state.outgoing[id] + if pending { + entry.route = nil + } + negotiated := s.state.functionsNegotiated + s.mu.Unlock() + if pending && negotiated { + s.write(map[string]any{"jsonrpc": "2.0", "method": methodCancelRequest, "params": map[string]any{"id": id}}) + } + // A cancelled mutation may already have taken effect; it is never sent + // again. + return nil, cancelledError() +} + +// sendAndWait reports true when a token in scope was cancelled while the +// request was on the wire. +func (s *shared) sendAndWait(id, method string, params any, slot bool, scope []*Cancellation, rt *route, reply chan settled, abort chan struct{}) (settled, bool) { + s.mu.Lock() + if slot { + ticket := s.state.channel.nextTicket + s.state.channel.nextTicket++ + s.state.channel.waiting = append(s.state.channel.waiting, ticket) + for { + if err := refusal(&s.state, scope); err != nil { + s.state.channel.waiting = slices.DeleteFunc(s.state.channel.waiting, func(waiting uint64) bool { return waiting == ticket }) + s.notifySlots() + s.mu.Unlock() + return settled{err: err}, false + } + if s.state.channel.inFlight < maxPendingHostCalls && s.state.channel.waiting[0] == ticket { + break + } + signal := s.state.slotSignal + s.mu.Unlock() + select { + case <-signal: + case <-abort: + } + s.mu.Lock() + } + s.state.channel.waiting = s.state.channel.waiting[1:] + s.state.channel.inFlight++ + s.notifySlots() + } else if err := refusal(&s.state, scope); err != nil { + s.mu.Unlock() + return settled{err: err}, false + } + s.state.outgoing[id] = &outgoing{method: method, reply: reply, slot: slot, route: rt} + s.mu.Unlock() + message := map[string]any{"jsonrpc": "2.0", "id": id, "method": method} + if params != nil { + message["params"] = params + } + s.write(message) + select { + case result := <-reply: + return result, false + case <-abort: + select { + case result := <-reply: + return result, false + default: + return settled{}, true + } + } +} + +// settleOutgoing settles the request a host response answers. +func (s *shared) settleOutgoing(id any, message map[string]any) { + key, ok := id.(string) + if !ok { + return + } + s.mu.Lock() + entry, ok := s.state.outgoing[key] + if !ok { + s.mu.Unlock() + return + } + delete(s.state.outgoing, key) + if entry.slot { + s.state.channel.inFlight-- + s.notifySlots() + } + var result settled + if failure := message["error"]; failure != nil { + result.err = sdkErrorFromResponse(entry.method, failure) + } else { + result.value = message["result"] + } + if result.err == nil && entry.route != nil { + subscriptionID, ok := field(result.value, "subscriptionID").(string) + if ok && IsCredentialKey(subscriptionID) { + ch := &s.state.channel + var rest []earlyEvent + // Events the host sent before this answer. + for _, early := range ch.early { + if early.subscriptionID == subscriptionID { + entry.route.emit(subscriptionID, early.sequence, early.event) + } else { + rest = append(rest, early) + } + } + ch.early = rest + if old := ch.routes[subscriptionID]; old != nil { + old.queue.close() + } + ch.routes[subscriptionID] = entry.route + } else { + result = settled{err: newSdkError("sdk.host.invalidResult", entry.method+" answered without a subscriptionID.")} + } + } + s.mu.Unlock() + entry.reply <- result +} + +// deliver routes one lithe/host/subscriptions/notify. +func (s *shared) deliver(params map[string]any) { + subscriptionID, ok := params["subscriptionID"].(string) + if !ok { + return + } + sequence, _ := unsignedInteger(params["sequence"]) + event := params["event"] + s.mu.Lock() + ch := &s.state.channel + if rt := ch.routes[subscriptionID]; rt != nil { + rt.emit(subscriptionID, sequence, event) + } else if ch.subscribing > 0 { + if len(ch.early) >= maxEarlyEvents { + s.mu.Unlock() + s.failed("notification", "subscription_queue_full") + return + } + ch.early = append(ch.early, earlyEvent{subscriptionID, sequence, event}) + } + // Otherwise the subscription was disposed; nothing follows a disposal. + s.mu.Unlock() +} + +// closeChannel ends every host request and subscription with the session. +// The caller holds mu. +func (s *shared) closeChannel() { + for id, entry := range s.state.outgoing { + delete(s.state.outgoing, id) + entry.reply <- settled{err: closedError()} + } + for id, rt := range s.state.channel.routes { + delete(s.state.channel.routes, id) + rt.live.Store(false) + rt.queue.close() + } + s.state.channel.early = nil + s.notifySlots() +} + +// dispose stops routing a subscription's events at once and asks the host +// to dispose it. live limits the first step to one subscription object. +func (s *shared) dispose(subscriptionID string, live *atomic.Bool) error { + s.mu.Lock() + routes := s.state.channel.routes + if rt := routes[subscriptionID]; rt != nil && (live == nil || rt.live == live) { + delete(routes, subscriptionID) + rt.live.Store(false) + rt.queue.close() + } + ready := s.state.phase == phaseReady + s.mu.Unlock() + if !ready { + return nil + } + _, err := (&Host{shared: s}).request(methodDispose, map[string]any{"subscriptionID": subscriptionID}) + return err +} + +// Host is the host services (lithe/host/*): credentials; workspace contexts, +// files, documents, the editor, previews, the browser, messages, terminals +// and capability discovery; calls to other plugins' functions. They are +// available when the host offered litheFunctions. Every method blocks until +// the host answers; failures the host reports carry its error.data.code, +// such as plugin.host.contextExpired. +// +// [BackendHandle.Host] is usable once the session is ready. A handler's +// [Context.Host] belongs to its call: requests still unanswered when the +// call is cancelled or ends fail with sdk.call.cancelled and are cancelled +// on the wire. At most 16 requests are on the wire at once; the rest wait +// their turn. +// +// Results are JSON as the host sent it; unmarshal them into the types you +// need. +type Host struct { + shared *shared + scope []*Cancellation + // parentOperation is the operationID of the relayed call this host + // serves, if any; the default parentOperationID of its cross-plugin + // calls. + parentOperation string +} + +// Negotiated reports whether the host offered litheFunctions, and with it +// host services, in this session; false before initialize. +func (h *Host) Negotiated() bool { return h.shared.functionsNegotiated() } + +// WithCancellation returns the same services, with requests also cancelled +// by cancellation, for work a plugin may stop for its own reasons. +func (h *Host) WithCancellation(cancellation *Cancellation) *Host { + scope := append(slices.Clone(h.scope), cancellation) + return &Host{shared: h.shared, scope: scope, parentOperation: h.parentOperation} +} + +// Request sends any lithe/host/* request, including methods a later host +// adds; [Host.Supports] says whether the session may call it. params is +// any JSON-serializable value; nil sends no params. +func (h *Host) Request(method string, params any) (json.RawMessage, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + result, err := h.request(method, value) + if err != nil { + return nil, err + } + return raw(result), nil +} + +// Subscribe sends a request that answers { subscriptionID } and routes the +// subscription's events to the returned [Subscription]. +func (h *Host) Subscribe(method string, params any) (*Subscription, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + return h.subscribe(method, value) +} + +// Capabilities is { protocolVersion, backendAuthority, services, limits }, +// asked once per session. +func (h *Host) Capabilities() (json.RawMessage, error) { + capabilities, err := h.capabilitiesValue() + if err != nil { + return nil, err + } + return raw(capabilities), nil +} + +// Supports reports whether this session may call method, from +// [Host.Capabilities]. A missing grant still fails the request. Without +// litheFunctions nothing is supported. +func (h *Host) Supports(method string) (bool, error) { + if !h.Negotiated() { + return false, nil + } + capabilities, err := h.capabilitiesValue() + if err != nil { + return false, err + } + services, _ := field(capabilities, "services").(map[string]any) + for _, service := range services { + methods, _ := field(service, "methods").([]any) + for _, entry := range methods { + if name, ok := entry.(string); ok && name == method { + return true, nil + } + } + } + return false, nil +} + +func (h *Host) capabilitiesValue() (any, error) { + if !h.Negotiated() { + return nil, unavailable(notNegotiated) + } + s := h.shared + // Held during the request, so concurrent callers share one answer. + s.capabilitiesMu.Lock() + defer s.capabilitiesMu.Unlock() + if s.capabilities != nil { + return s.capabilities, nil + } + capabilities, err := h.request(methodCapabilities, nil) + if err != nil { + return nil, err + } + if _, ok := capabilities.(map[string]any); !ok { + return nil, newSdkError("sdk.host.invalidResult", "lithe/host/getCapabilities answered with something other than an object.") + } + s.capabilities = capabilities + return capabilities, nil +} + +// Credentials is the host's credentials service. +func (h *Host) Credentials() *Credentials { return &Credentials{host: h} } + +// Subscriptions disposes subscriptions by ID. +func (h *Host) Subscriptions() *Subscriptions { return &Subscriptions{host: h} } + +// Workspace is workspace contexts and files. +func (h *Host) Workspace() *Workspace { return &Workspace{host: h} } + +// Documents is open documents, read from their live buffers. +func (h *Host) Documents() *Documents { return &Documents{host: h} } + +// Editor is the text editor. +func (h *Host) Editor() *Editor { return &Editor{host: h} } + +// Preview is HTML previews. +func (h *Host) Preview() *Preview { return &Preview{host: h} } + +// Browser is the system browser. +func (h *Host) Browser() *Browser { return &Browser{host: h} } + +// Terminal is integrated native terminals. +func (h *Host) Terminal() *Terminal { return &Terminal{host: h} } + +// Window is messages in the window. +func (h *Host) Window() *Window { return &Window{host: h} } + +// Functions is calls to other plugins' functions through Core. +func (h *Host) Functions() *Functions { return &Functions{host: h} } + +// request sends a host request whose params are already in the SDK's +// dynamic form. +func (h *Host) request(method string, params any) (any, error) { + return h.send(method, params, nil) +} + +func (h *Host) subscribe(method string, params any) (*Subscription, error) { + live := &atomic.Bool{} + live.Store(true) + rt := &route{live: live, queue: newEventQueue()} + s := h.shared + s.mu.Lock() + s.state.channel.subscribing++ + s.mu.Unlock() + result, err := h.send(method, params, rt) + s.mu.Lock() + s.state.channel.subscribing-- + if s.state.channel.subscribing == 0 { + s.state.channel.early = nil + } + s.mu.Unlock() + if err != nil { + return nil, err + } + id, _ := field(result, "subscriptionID").(string) + return &Subscription{id: id, shared: s, live: live, queue: rt.queue}, nil +} + +func (h *Host) send(method string, params any, rt *route) (any, error) { + if !strings.HasPrefix(method, hostPrefix) { + return nil, newSdkError("sdk.host.method", method+" is not a host method; host requests are lithe/host/*.") + } + s := h.shared + s.mu.Lock() + err := refusal(&s.state, nil) + s.mu.Unlock() + if err != nil { + return nil, err + } + if !h.Negotiated() { + // The answer Core would give, without the round trip. + return nil, unavailable(notNegotiated) + } + if anyCancelled(h.scope) { + return nil, cancelledError() + } + return s.exchange(method, params, true, h.scope, rt) +} + +// scoped sends a method whose params name a workspace context; it answers +// an object or null. +func (h *Host) scoped(method string, context WorkspaceContext, params any) (json.RawMessage, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + if value, err = withContext(context, value); err != nil { + return nil, err + } + return h.objectOrNull(method, value) +} + +func (h *Host) objectOrNull(method string, params any) (json.RawMessage, error) { + result, err := h.request(method, params) + if err != nil { + return nil, err + } + switch result.(type) { + case nil, map[string]any: + return raw(result), nil + } + return nil, invalidResult(method) +} + +// requestObject sends a method that always answers an object. +func (h *Host) requestObject(method string, params any) (json.RawMessage, error) { + result, err := h.request(method, params) + if err != nil { + return nil, err + } + if _, ok := result.(map[string]any); !ok { + return nil, invalidResult(method) + } + return raw(result), nil +} + +func invalidResult(method string) *SdkError { + return newSdkError("sdk.host.invalidResult", method+" answered with something other than an object.") +} + +func invalidHostParams() *SdkError { + return newSdkError("sdk.host.invalidParams", "Host request params are an object.") +} + +// withContext is params with context added; params are an object or nil. +func withContext(context WorkspaceContext, params any) (any, error) { + var object map[string]any + switch value := params.(type) { + case nil: + object = map[string]any{} + case map[string]any: + object = maps.Clone(value) + default: + return nil, invalidHostParams() + } + object["context"] = context.toValue() + return object, nil +} + +// WorkspaceContext is a workspace context reference, { contextID, +// generation }: the window a call or command ran in, or one from +// ListContexts. A context is replaced when its window's folders change; +// requests with an old generation fail with plugin.host.contextExpired. +type WorkspaceContext struct { + contextID string + generation uint64 +} + +func invalidContext() *SdkError { + return newSdkError("sdk.host.invalidContext", "A context is { contextID, generation }: an ID of 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\", and a positive generation.") +} + +// NewWorkspaceContext returns a context reference. contextID is 1-128 ASCII +// letters, digits, ".", "_", ":" or "-"; generation is positive. +func NewWorkspaceContext(contextID string, generation uint64) (WorkspaceContext, error) { + return ParseWorkspaceContext(map[string]any{"contextID": contextID, "generation": generation}) +} + +// ParseWorkspaceContext reads the reference of a context reference or of a +// full context from ListContexts or GetContext -- a json.RawMessage, a map, +// or any value that serializes to one -- so either can be passed on. +func ParseWorkspaceContext(value any) (WorkspaceContext, error) { + decoded, err := toValue(value) + if err != nil { + return WorkspaceContext{}, invalidContext() + } + return workspaceContextFromValue(decoded) +} + +func workspaceContextFromValue(value any) (WorkspaceContext, error) { + contextID, ok := field(value, "contextID").(string) + if !ok || !IsCredentialKey(contextID) { + return WorkspaceContext{}, invalidContext() + } + number, ok := generation(field(value, "generation")) + if !ok { + return WorkspaceContext{}, invalidContext() + } + return WorkspaceContext{contextID: contextID, generation: number}, nil +} + +// workspaceContextFromReference reads the context of an invocation or +// command: exactly a reference. +func workspaceContextFromReference(value any) *WorkspaceContext { + object, ok := value.(map[string]any) + if !ok || len(object) != 2 { + return nil + } + context, err := workspaceContextFromValue(object) + if err != nil { + return nil + } + return &context +} + +// ID is the context's ID. +func (c WorkspaceContext) ID() string { return c.contextID } + +// Generation is the context's generation. +func (c WorkspaceContext) Generation() uint64 { return c.generation } + +func (c WorkspaceContext) toValue() map[string]any { + return map[string]any{"contextID": c.contextID, "generation": c.generation} +} + +// MarshalJSON writes { "contextID": ..., "generation": ... }. +func (c WorkspaceContext) MarshalJSON() ([]byte, error) { return encodeJSON(c.toValue()) } + +// UnmarshalJSON reads a context reference or a full context. +func (c *WorkspaceContext) UnmarshalJSON(data []byte) error { + value, err := decodeJSON(data) + if err != nil { + return invalidContext() + } + context, err := workspaceContextFromValue(value) + if err != nil { + return err + } + *c = context + return nil +} + +// Event is one lithe/host/subscriptions/notify. +type Event struct { + subscriptionID string + sequence uint64 + gap bool + event any +} + +// SubscriptionID is the subscription the event belongs to. +func (e Event) SubscriptionID() string { return e.subscriptionID } + +// Sequence starts at 1 and grows by one per event of the subscription. +func (e Event) Sequence() uint64 { return e.sequence } + +// Gap is true when events before this one were lost, so state built from +// earlier events should be refreshed, for example by rescanning. +func (e Event) Gap() bool { return e.gap } + +// Event is the event, usually an object. +func (e Event) Event() json.RawMessage { return raw(e.event) } + +// Errors of [Subscription.RecvTimeout]. +var ( + // ErrSubscriptionDisposed: the subscription was disposed or the session + // ended. + ErrSubscriptionDisposed = errors.New("The subscription was disposed.") + // ErrRecvTimeout: no event arrived in time. + ErrRecvTimeout = errors.New("No subscription event arrived in time.") +) + +// eventQueue is an unbounded queue of one subscription's events, in order. +type eventQueue struct { + mu sync.Mutex + items []Event + closed bool + // signal is closed, and replaced, when the queue changes. + signal chan struct{} +} + +func newEventQueue() *eventQueue { + return &eventQueue{signal: make(chan struct{})} +} + +func (q *eventQueue) changed() { + close(q.signal) + q.signal = make(chan struct{}) +} + +func (q *eventQueue) push(event Event) { + q.mu.Lock() + defer q.mu.Unlock() + if q.closed { + return + } + q.items = append(q.items, event) + q.changed() +} + +func (q *eventQueue) close() { + q.mu.Lock() + defer q.mu.Unlock() + if q.closed { + return + } + q.closed = true + q.changed() +} + +// pop waits for the next event: at most timeout when it is positive, else +// without a limit. It fails with ErrSubscriptionDisposed once the queue is +// closed and empty, and ErrRecvTimeout when the time ran out. +func (q *eventQueue) pop(timeout time.Duration) (Event, error) { + var expired <-chan time.Time + if timeout > 0 { + timer := time.NewTimer(timeout) + defer timer.Stop() + expired = timer.C + } + for { + q.mu.Lock() + if len(q.items) > 0 { + event := q.items[0] + q.items[0] = Event{} + q.items = q.items[1:] + q.mu.Unlock() + return event, nil + } + if q.closed { + q.mu.Unlock() + return Event{}, ErrSubscriptionDisposed + } + signal := q.signal + q.mu.Unlock() + select { + case <-signal: + case <-expired: + return Event{}, ErrRecvTimeout + } + } +} + +// Subscription is a host subscription, such as a file watch or registered +// editor actions. Events queue in order until read; dropping the +// subscription does not dispose it on the host, [Subscription.Dispose] does. +type Subscription struct { + id string + shared *shared + live *atomic.Bool + queue *eventQueue +} + +// ID is the subscription's ID. +func (s *Subscription) ID() string { return s.id } + +// IsDisposed is true once disposed here or the session ended. +func (s *Subscription) IsDisposed() bool { return !s.live.Load() } + +// Recv waits for the next event; false once disposed or the session ended. +func (s *Subscription) Recv() (Event, bool) { + event, err := s.queue.pop(0) + if err != nil || s.IsDisposed() { + return Event{}, false + } + return event, true +} + +// RecvTimeout waits at most timeout for the next event. It fails with +// ErrSubscriptionDisposed once disposed or the session ended, and with +// ErrRecvTimeout when no event arrived in time. +func (s *Subscription) RecvTimeout(timeout time.Duration) (Event, error) { + if s.IsDisposed() { + return Event{}, ErrSubscriptionDisposed + } + if timeout <= 0 { + timeout = time.Nanosecond + } + event, err := s.queue.pop(timeout) + if err != nil { + return Event{}, err + } + if s.IsDisposed() { + return Event{}, ErrSubscriptionDisposed + } + return event, nil +} + +// Dispose stops routing events at once and asks the host to dispose the +// subscription. After the session ended there is nothing to ask. +func (s *Subscription) Dispose() error { return s.shared.dispose(s.id, s.live) } + +// Credentials is the host's credentials service: secrets private to this +// plugin, kept in the platform's secret store, never in ${stateDir}. It +// needs the credentials.store permission; without it every request fails +// with plugin.host.permissionDenied. +type Credentials struct{ host *Host } + +// Get returns the secret stored under key, with false when there is none. +func (c *Credentials) Get(key string) (string, bool, error) { + if err := checkCredentialKey(key); err != nil { + return "", false, err + } + result, err := c.host.request(methodCredentialsGet, map[string]any{"key": key}) + if err != nil { + return "", false, err + } + switch value := result.(type) { + case nil: + return "", false, nil + case map[string]any: + if secret, ok := value["secret"].(string); ok { + return secret, true, nil + } + } + return "", false, newSdkError("sdk.host.invalidResult", "The host answered credentials/get without a secret.") +} + +// Set stores secret (at most 16 KiB) under key, replacing any value. +func (c *Credentials) Set(key, secret string) error { + if err := checkCredentialKey(key); err != nil { + return err + } + if len(secret) > maxSecretBytes { + return newSdkError("sdk.credentials.invalidSecret", "A secret is a string of at most 16 KiB.") + } + _, err := c.host.request(methodCredentialsSet, map[string]any{"key": key, "secret": secret}) + return err +} + +// Delete removes the secret under key; it succeeds when nothing was stored. +func (c *Credentials) Delete(key string) error { + if err := checkCredentialKey(key); err != nil { + return err + } + _, err := c.host.request(methodCredentialsDel, map[string]any{"key": key}) + return err +} + +func checkCredentialKey(key string) error { + if IsCredentialKey(key) { + return nil + } + return newSdkError("sdk.credentials.invalidKey", "A credential key is 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\".") +} + +// Subscriptions disposes subscriptions by ID. +type Subscriptions struct{ host *Host } + +// Dispose disposes a subscription by ID; it also succeeds for an unknown or +// disposed one. +func (s *Subscriptions) Dispose(subscriptionID string) error { + return s.host.shared.dispose(subscriptionID, nil) +} + +// Workspace is workspace contexts and files. Every method but ListContexts +// names a context: the call's [Context.WorkspaceContext], or one from +// ListContexts read with [ParseWorkspaceContext]. params is any +// JSON-serializable object, nil for none. +type Workspace struct{ host *Host } + +// ListContexts answers { revision, contexts }. +func (w *Workspace) ListContexts() (json.RawMessage, error) { + return w.host.objectOrNull(methodListContexts, map[string]any{}) +} + +// GetContext answers the context. +func (w *Workspace) GetContext(context WorkspaceContext) (json.RawMessage, error) { + return w.host.scoped(methodGetContext, context, nil) +} + +// GetFolders answers { folders }. +func (w *Workspace) GetFolders(context WorkspaceContext) (json.RawMessage, error) { + return w.host.scoped(methodGetFolders, context, nil) +} + +// ReadDirectory takes resource, cursor?, limit?. +func (w *Workspace) ReadDirectory(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodReadDirectory, context, params) +} + +// Stat takes resource. +func (w *Workspace) Stat(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodStat, context, params) +} + +// ReadFile takes resource, maximumBytes?. +func (w *Workspace) ReadFile(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodReadFile, context, params) +} + +// Watch watches resource, recursive?; events are { rootID, changedPaths, +// requiresRescan }. +func (w *Workspace) Watch(context WorkspaceContext, params any) (*Subscription, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + if value, err = withContext(context, value); err != nil { + return nil, err + } + return w.host.subscribe(methodWatch, value) +} + +// FindFiles takes a root resource, query, fileMask?, cursor?, limit?. +func (w *Workspace) FindFiles(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodFindFiles, context, params) +} + +// FindText takes a root resource, pattern, and optional search options. +func (w *Workspace) FindText(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodFindText, context, params) +} + +// Documents is open documents, read from their live buffers. +type Documents struct{ host *Host } + +// List answers { documents }. +func (d *Documents) List(context WorkspaceContext) (json.RawMessage, error) { + return d.host.scoped(methodDocumentsList, context, nil) +} + +// GetSnapshot takes documentID and answers { document, text }. +func (d *Documents) GetSnapshot(context WorkspaceContext, params any) (json.RawMessage, error) { + return d.host.scoped(methodDocumentsSnap, context, params) +} + +// Editor is the text editor. +type Editor struct{ host *Host } + +// GetActive answers the foreground text tab's document summary, or null. +func (e *Editor) GetActive(context WorkspaceContext) (json.RawMessage, error) { + return e.host.scoped(methodEditorActive, context, nil) +} + +// GetSelections takes documentID. +func (e *Editor) GetSelections(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorSelect, context, params) +} + +// ApplyEdits takes documentID, expectedVersion, edits. +func (e *Editor) ApplyEdits(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorApply, context, params) +} + +// ReplaceSelections takes documentID, expectedVersion, selections, +// replacements. +func (e *Editor) ReplaceSelections(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorReplace, context, params) +} + +// InsertText takes documentID, expectedVersion, at, text. +func (e *Editor) InsertText(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorInsert, context, params) +} + +// Open takes resource, activation?, range?, tab?. +func (e *Editor) Open(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorOpen, context, params) +} + +// Reveal takes resource, activation?, range?, tab?. +func (e *Editor) Reveal(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorReveal, context, params) +} + +// RegisterActions registers editor actions (id, function, selector) that +// invoke one of the backend's functions; disposing the subscription removes +// them. +func (e *Editor) RegisterActions(context WorkspaceContext, params any) (*Subscription, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + if value, err = withContext(context, value); err != nil { + return nil, err + } + return e.host.subscribe(methodEditorActions, value) +} + +// Preview is HTML previews. +type Preview struct{ host *Host } + +// OpenHTML takes an HTML resource, presentation?, range?. +func (p *Preview) OpenHTML(context WorkspaceContext, params any) (json.RawMessage, error) { + return p.host.scoped(methodPreviewHTML, context, params) +} + +// Browser is the system browser. +type Browser struct{ host *Host } + +// OpenExternal takes exactly one of an HTTP(S) url or an HTML resource. +func (b *Browser) OpenExternal(context WorkspaceContext, params any) (json.RawMessage, error) { + return b.host.scoped(methodBrowserOpen, context, params) +} + +// Window is messages in the window. params: text, actions?; each method +// answers { selectedIndex }, null on dismissal. +type Window struct{ host *Host } + +// ShowInformation shows an information message. +func (w *Window) ShowInformation(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodShowInfo, context, params) +} + +// ShowWarning shows a warning message. +func (w *Window) ShowWarning(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodShowWarning, context, params) +} + +// ShowError shows an error message. +func (w *Window) ShowError(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodShowError, context, params) +} + +// Terminal is integrated native terminals owned by this backend session and +// workspace. Permission terminal.create; discover each method with +// [Host.Supports]. Input and output stay in the host terminal, not in the +// plugin's web page. +type Terminal struct{ host *Host } + +// Create launches executable and arguments directly. params: executable, +// optional arguments, title, cwd resource, environment, and show (true). +func (t *Terminal) Create(context WorkspaceContext, params any) (json.RawMessage, error) { + return t.host.scoped(methodTerminalCreate, context, params) +} + +// Show shows an owned terminal in its original window without raising the +// window. +func (t *Terminal) Show(context WorkspaceContext, terminalID string) (json.RawMessage, error) { + return t.host.scoped(methodTerminalShow, context, map[string]any{"terminalID": terminalID}) +} + +// Close stops the native process, keeping a bounded display suffix for +// reopen. One retainedContextBytes (0-262144) overrides the create-time +// choice. +func (t *Terminal) Close(context WorkspaceContext, terminalID string, retainedContextBytes ...uint64) (json.RawMessage, error) { + params := map[string]any{"terminalID": terminalID} + if len(retainedContextBytes) > 0 { + params["retainedContextBytes"] = retainedContextBytes[0] + } + return t.host.scoped(methodTerminalClose, context, params) +} + +// Reopen starts the saved argv again and restores plain display history, +// never input. +func (t *Terminal) Reopen(context WorkspaceContext, terminalID string) (json.RawMessage, error) { + return t.host.scoped(methodTerminalReopen, context, map[string]any{"terminalID": terminalID}) +} + +// Dispose permanently forgets an owned handle and its history, also closing +// it if live. +func (t *Terminal) Dispose(context WorkspaceContext, terminalID string) (json.RawMessage, error) { + return t.host.scoped(methodTerminalDrop, context, map[string]any{"terminalID": terminalID}) +} + +// OnExit subscribes to one exit event per process generation, including the +// latest recorded outcome when subscribing after exit. Disposing the +// subscription stops notifications, not the terminal itself. +func (t *Terminal) OnExit(context WorkspaceContext, terminalID string) (*Subscription, error) { + params, err := withContext(context, map[string]any{"terminalID": terminalID}) + if err != nil { + return nil, err + } + return t.host.subscribe(methodTerminalExit, params) +} + +// Functions is calls to the functions other plugins export, relayed by +// Core. It needs a call the plugin declares as pluginFunctions.calls in its +// manifest; discover the methods with [Host.Supports]. The relay accepts +// local workspaces only. +type Functions struct{ host *Host } + +// Providers answers { providers }: the enabled plugins other than this one +// that export functionID, sorted by plugin ID, each { pluginID, version }. +// This plugin must have declared the function. +func (f *Functions) Providers(functionID string) (json.RawMessage, error) { + if !IsFunctionID(functionID) { + return nil, invalidCall("functionID is a plugin function ID.") + } + return f.host.requestObject(methodProviders, map[string]any{"functionID": functionID}) +} + +// Invoke calls one provider and answers { value }, the provider's result. +// call is an object with pluginID and functionID, and optionally params (an +// object), timeoutMilliseconds (a positive integer; the host defaults it +// and caps it at 600000), and parentOperationID; any other key is not sent. +// context is a workspace context this backend learned from the workspace +// service. +// +// Inside a handler, parentOperationID defaults to the operationID of the +// call the handler serves, which tells Core the new call belongs to it. A +// [BackendHandle.Host] serves no call, so it sends the field only when call +// sets it. Cancelling the handler's call cancels the relayed call. +func (f *Functions) Invoke(context WorkspaceContext, call any) (json.RawMessage, error) { + value, err := toValue(call) + if err != nil { + return nil, invalidCall("A cross-plugin call is an object.") + } + relayed, err := relayParams(value, f.host.parentOperation) + if err != nil { + return nil, err + } + params, err := withContext(context, relayed) + if err != nil { + return nil, err + } + return f.host.requestObject(methodRelayInvoke, params) +} + +func invalidCall(message string) *SdkError { + return newSdkError("sdk.functions.invalidCall", message) +} + +// relayParams is the params of lithe/host/functions/invoke for call, +// without its context: the fields the method defines and no other, so the +// host never answers -32018. serving is the operationID parentOperationID +// defaults to, "" for none. +func relayParams(call any, serving string) (map[string]any, error) { + object, ok := call.(map[string]any) + if !ok { + return nil, invalidCall("A cross-plugin call is an object.") + } + relayed := map[string]any{} + pluginID, ok := object["pluginID"].(string) + if !ok || pluginID == "" { + return nil, invalidCall("pluginID is a non-empty string.") + } + relayed["pluginID"] = pluginID + functionID, ok := object["functionID"].(string) + if !ok || !IsFunctionID(functionID) { + return nil, invalidCall("functionID is a plugin function ID.") + } + relayed["functionID"] = functionID + if params, present := object["params"]; present { + if _, ok := params.(map[string]any); !ok { + return nil, invalidCall("params is an object.") + } + relayed["params"] = params + } + if timeout, present := object["timeoutMilliseconds"]; present { + if milliseconds, ok := unsignedInteger(timeout); !ok || milliseconds == 0 { + return nil, invalidCall("timeoutMilliseconds is a positive integer.") + } + relayed["timeoutMilliseconds"] = timeout + } + if parent, present := object["parentOperationID"]; present { + text, ok := parent.(string) + if !ok || !isParentOperationID(text) { + return nil, invalidCall("parentOperationID is a 1-128 byte string.") + } + relayed["parentOperationID"] = text + } else if serving != "" { + relayed["parentOperationID"] = serving + } + return relayed, nil +} diff --git a/shared/plugins/sdk/go/lithe/host_internal_test.go b/shared/plugins/sdk/go/lithe/host_internal_test.go new file mode 100644 index 00000000..0279ae9b --- /dev/null +++ b/shared/plugins/sdk/go/lithe/host_internal_test.go @@ -0,0 +1,140 @@ +package lithe + +import ( + "encoding/json" + "errors" + "strings" + "testing" +) + +func errorCode(err error) string { + var sdk *SdkError + if errors.As(err, &sdk) { + return sdk.Code() + } + return "" +} + +func TestContextsAreReferencesOrFullContexts(t *testing.T) { + full := mustValue(t, `{"contextID": "w1", "generation": 2, "name": "orders"}`) + context, err := ParseWorkspaceContext(full) + if err != nil { + t.Fatal(err) + } + assertJSON(t, context, `{"contextID": "w1", "generation": 2}`) + made, err := NewWorkspaceContext("w1", 2) + if err != nil || made != context { + t.Errorf("NewWorkspaceContext = %+v, %v", made, err) + } + // Raw JSON from a host answer is read too. + fromRaw, err := ParseWorkspaceContext(json.RawMessage(`{"contextID":"w1","generation":2.0,"roots":[]}`)) + if err != nil || fromRaw != context { + t.Errorf("from raw = %+v, %v", fromRaw, err) + } + var unmarshalled WorkspaceContext + if err := json.Unmarshal([]byte(`{"contextID":"w1","generation":2}`), &unmarshalled); err != nil || unmarshalled != context { + t.Errorf("unmarshalled = %+v, %v", unmarshalled, err) + } + // An invocation's context is exactly a reference. + if workspaceContextFromReference(full) != nil { + t.Error("a full context is accepted as a reference") + } + if reference := workspaceContextFromReference(mustValue(t, canonical(t, context))); reference == nil || *reference != context { + t.Errorf("reference = %v", reference) + } + for _, invalid := range []string{ + `{"contextID": "w1"}`, + `{"contextID": "w1", "generation": 0}`, + `{"contextID": "../w", "generation": 1}`, + `null`, + } { + if _, err := ParseWorkspaceContext(json.RawMessage(invalid)); errorCode(err) != "sdk.host.invalidContext" { + t.Errorf("%s: %v", invalid, err) + } + } + if _, err := NewWorkspaceContext("", 1); err == nil { + t.Error("an empty context ID is accepted") + } + if err := json.Unmarshal([]byte(`{"contextID":"w1"}`), &unmarshalled); errorCode(err) != "sdk.host.invalidContext" { + t.Errorf("unmarshal invalid = %v", err) + } +} + +func TestARelayedCallKeepsOnlyTheFieldsTheMethodDefines(t *testing.T) { + call := mustValue(t, `{ + "pluginID": "dev.lithe.fixture.java", "functionID": "project.describe", + "params": {"caller": "data"}, "timeoutMilliseconds": 900000, + "parentOperationID": "17", "caller": {"pluginID": "forged"}, + "context": {"contextID": "x"}, "extra": true + }`) + relayed, err := relayParams(call, "served") + if err != nil { + t.Fatal(err) + } + // Core passes a caller inside params unchanged; only a top-level one is + // dropped. + assertJSON(t, relayed, `{ + "pluginID": "dev.lithe.fixture.java", "functionID": "project.describe", + "params": {"caller": "data"}, "timeoutMilliseconds": 900000, + "parentOperationID": "17" + }`) +} + +func TestOptionalFieldsStayOutAndTheParentDefaultsToTheCallBeingServed(t *testing.T) { + call := `{"pluginID": "a.b", "functionID": "x.y"}` + relayed, err := relayParams(mustValue(t, call), "") + if err != nil { + t.Fatal(err) + } + assertJSON(t, relayed, call) + served, err := relayParams(mustValue(t, call), "op-7") + if err != nil { + t.Fatal(err) + } + assertJSON(t, served, `{"pluginID": "a.b", "functionID": "x.y", "parentOperationID": "op-7"}`) + named, err := relayParams(mustValue(t, `{"pluginID": "a.b", "functionID": "x.y", "parentOperationID": "own"}`), "op-7") + if err != nil || named["parentOperationID"] != "own" { + t.Errorf("named = %v, %v", named, err) + } + // The host caps the timeout; the SDK sends what the plugin chose. + slow, err := relayParams(mustValue(t, `{"pluginID": "a.b", "functionID": "x.y", "timeoutMilliseconds": 700000}`), "") + if err != nil { + t.Fatal(err) + } + assertJSON(t, slow["timeoutMilliseconds"], `700000`) +} + +func TestAnInvalidRelayedCallIsRefusedBeforeAnythingIsSent(t *testing.T) { + with := func(key, value string) string { + call := mustValue(t, `{"pluginID": "a.b", "functionID": "x.y"}`).(map[string]any) + call[key] = mustValue(t, value) + return canonical(t, call) + } + without := func(key string) string { + call := mustValue(t, `{"pluginID": "a.b", "functionID": "x.y"}`).(map[string]any) + delete(call, key) + return canonical(t, call) + } + for _, invalid := range []string{ + `"x.y"`, + `null`, + without("pluginID"), + with("pluginID", `""`), + with("pluginID", `7`), + without("functionID"), + with("functionID", `"Not-Valid"`), + with("params", `[]`), + with("params", `null`), + with("timeoutMilliseconds", `0`), + with("timeoutMilliseconds", `-1`), + with("timeoutMilliseconds", `1.5`), + with("timeoutMilliseconds", `"5000"`), + with("parentOperationID", `""`), + with("parentOperationID", `"`+strings.Repeat("p", 129)+`"`), + with("parentOperationID", `12`), + } { + if _, err := relayParams(mustValue(t, invalid), "op-1"); errorCode(err) != "sdk.functions.invalidCall" { + t.Errorf("%s: %v", invalid, err) + } + } +} diff --git a/shared/plugins/sdk/go/lithe/host_services_test.go b/shared/plugins/sdk/go/lithe/host_services_test.go new file mode 100644 index 00000000..f93e9aa9 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/host_services_test.go @@ -0,0 +1,1130 @@ +package lithe_test + +// Host services of the plugin-function protocol, driven by a scripted host +// and the contract fixture; mirrors the Rust SDK's tests/host_services.rs. + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" + "time" + + "github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go/lithe" +) + +const quiet = 200 * time.Millisecond + +func fixture(t *testing.T) map[string]any { + t.Helper() + // Read at run time: the published module has no contract directory. + path := filepath.Join("..", "..", "..", "contract", "v1", "fixtures", "backend", "function-protocol.json") + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("%s: %v", path, err) + } + var value map[string]any + if err := json.Unmarshal(data, &value); err != nil { + t.Fatalf("%s: %v", path, err) + } + return value +} + +func cases(t *testing.T, fixture map[string]any, key string) []map[string]any { + t.Helper() + list, ok := fixture[key].([]any) + if !ok { + t.Fatalf("the fixture has no %s cases", key) + } + result := make([]map[string]any, 0, len(list)) + for _, entry := range list { + result = append(result, entry.(map[string]any)) + } + return result +} + +func testContext() lithe.WorkspaceContext { + context, err := lithe.NewWorkspaceContext("w1", 2) + if err != nil { + panic(err) + } + return context +} + +// outcome is what blocking SDK work returned. +type outcome[T any] struct { + value T + err error +} + +// background runs blocking SDK work off the test goroutine. +func background[T any](work func() (T, error)) <-chan outcome[T] { + result := make(chan outcome[T], 1) + go func() { + value, err := work() + result <- outcome[T]{value, err} + }() + return result +} + +// done is the outcome of background work, failing after the bounded wait. +func done[T any](t *testing.T, pending <-chan outcome[T]) outcome[T] { + t.Helper() + return within(t, pending) +} + +// refusal is the SDK error background work failed with. +func refusal[T any](t *testing.T, pending <-chan outcome[T]) *lithe.SdkError { + t.Helper() + result := done(t, pending) + var sdk *lithe.SdkError + if !errors.As(result.err, &sdk) { + t.Fatalf("the host request did not fail with an SDK error: %v, %v", result.value, result.err) + } + return sdk +} + +func rpcCode(t *testing.T, err *lithe.SdkError) any { + t.Helper() + if number, ok := err.RPCCode(); ok { + return number + } + return nil +} + +func number(value any) int64 { + n, _ := value.(float64) + return int64(n) +} + +// session is a host whose session negotiated plugin functions (or did not), +// and every frame the backend sent. +type session struct { + *testHost + log []map[string]any + unread []map[string]any +} + +// startSession initializes with litheFunctions versions, or none for nil. +func startSession(t *testing.T, backend *lithe.Backend, versions any) *session { + t.Helper() + host := startHost(t, backend) + host.initialize(versions) + return &session{testHost: host} +} + +func (s *session) pull(timeout time.Duration) (map[string]any, bool) { + frame, ok := s.nextWithin(timeout) + if ok { + s.log = append(s.log, frame) + } + return frame, ok +} + +// takeWhere is the next frame the test has not taken that matches. +func (s *session) takeWhere(matches func(map[string]any) bool) map[string]any { + s.t.Helper() + for index, frame := range s.unread { + if matches(frame) { + s.unread = slices.Delete(s.unread, index, index+1) + return frame + } + } + for { + frame, ok := s.pull(wait) + if !ok { + s.t.Fatalf("no matching frame; unread: %s", encode(s.t, s.unread)) + } + if matches(frame) { + return frame + } + s.unread = append(s.unread, frame) + } +} + +// take is the next host request with method. +func (s *session) take(method string) map[string]any { + s.t.Helper() + return s.takeWhere(func(frame map[string]any) bool { + _, isRequest := frame["id"] + return frame["method"] == method && isRequest + }) +} + +// response is the backend's answer to request id. +func (s *session) response(id any) map[string]any { + s.t.Helper() + want := normalize(s.t, id) + return s.takeWhere(func(frame map[string]any) bool { + _, isRequest := frame["method"] + return !isRequest && reflect.DeepEqual(frame["id"], want) + }) +} + +// sent is every frame with method the backend sent, once it went quiet. +func (s *session) sent(method string) []map[string]any { + for { + frame, ok := s.pull(quiet) + if !ok { + break + } + s.unread = append(s.unread, frame) + } + var frames []map[string]any + for _, frame := range s.log { + if frame["method"] == method { + frames = append(frames, frame) + } + } + return frames +} + +func TestTheSDKAnswersPluginFunctionsOnlyWhenTheHostOffersVersionZero(t *testing.T) { + for _, c := range []struct { + offered []any + negotiated bool + }{ + {[]any{0}, true}, + {[]any{0, 99}, true}, + {[]any{1}, false}, + {[]any{99}, false}, + {[]any{}, false}, + } { + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("query.run", func(json.RawMessage, *lithe.Context) (any, error) { return nil, nil })) + handle := backend.Handle() + host := startHost(t, backend) + answer := at(host.initialize(c.offered), "capabilities", "experimental", "litheFunctions") + version, ok := handle.FunctionsVersion() + if c.negotiated { + eq(t, answer, `{"version": 0, "functions": [{"id": "query.run"}]}`) + if !ok || version != 0 { + t.Errorf("%v: functions version = %d, %t", c.offered, version, ok) + } + } else { + if answer != nil { + t.Errorf("%v: litheFunctions = %s", c.offered, encode(t, answer)) + } + if ok { + t.Errorf("%v: functions version = %d", c.offered, version) + } + } + if handle.Host().Negotiated() != c.negotiated { + t.Errorf("%v: negotiated = %t", c.offered, !c.negotiated) + } + host.close() + } +} + +func TestCredentialsRoundTripThroughTheHostWithTheContractShapes(t *testing.T) { + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + type secret struct { + value string + found bool + } + read := func() <-chan outcome[secret] { + return background(func() (secret, error) { + value, found, err := host.Credentials().Get("connection.prod") + return secret{value, found}, err + }) + } + + reading := read() + get := s.take("lithe/host/credentials/get") + eq(t, get["params"], `{"key": "connection.prod"}`) + s.reply(get, map[string]any{"secret": "s3cret"}) + if result := done(t, reading); result.err != nil || result.value != (secret{"s3cret", true}) { + t.Errorf("get = %+v, %v", result.value, result.err) + } + + missing := read() + s.reply(s.take("lithe/host/credentials/get"), nil) + if result := done(t, missing); result.err != nil || result.value.found { + t.Errorf("missing = %+v, %v", result.value, result.err) + } + + malformed := read() + s.reply(s.take("lithe/host/credentials/get"), map[string]any{}) + if got := code(done(t, malformed).err); got != "sdk.host.invalidResult" { + t.Errorf("malformed = %q", got) + } + + writing := background(func() (struct{}, error) { + return struct{}{}, host.Credentials().Set("connection.prod:password", "s3cret") + }) + set := s.take("lithe/host/credentials/set") + eq(t, set["params"], `{"key": "connection.prod:password", "secret": "s3cret"}`) + s.reply(set, nil) + must(t, done(t, writing).err) + + deleting := background(func() (struct{}, error) { + return struct{}{}, host.Credentials().Delete("connection.prod") + }) + remove := s.take("lithe/host/credentials/delete") + eq(t, remove["params"], `{"key": "connection.prod"}`) + s.reply(remove, nil) + must(t, done(t, deleting).err) + + // Malformed arguments fail locally and never reach the host. + for _, key := range []string{"", "has space", strings.Repeat("k", 129)} { + if _, _, err := host.Credentials().Get(key); code(err) != "sdk.credentials.invalidKey" { + t.Errorf("%q: %v", key, err) + } + } + if err := host.Credentials().Set("key", strings.Repeat("x", 16*1024+1)); code(err) != "sdk.credentials.invalidSecret" { + t.Errorf("an oversized secret: %v", err) + } + s.assertQuiet() + s.close() +} + +func TestLocalKeyAndContextChecksAgreeWithTheFixtureCasesCoreRefusesOrForwards(t *testing.T) { + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + keys, contexts := 0, 0 + for _, c := range cases(t, fixture(t), "hostRequests") { + name, _ := c["name"].(string) + method, _ := c["method"].(string) + expected, _ := c["expected"].(map[string]any) + if strings.HasPrefix(method, "lithe/host/credentials/") { + key, _ := at(c, "params", "key").(string) + if _, forward := expected["forward"]; forward { + if !lithe.IsCredentialKey(key) { + t.Errorf("%s: the key is refused", name) + } + } else if strings.Contains(name, "key") { + if _, _, err := host.Credentials().Get(key); code(err) != "sdk.credentials.invalidKey" { + t.Errorf("%s: %v", name, err) + } + keys++ + } + } + for _, pattern := range []string{"context without", "context ID outside", "generation is positive"} { + if strings.Contains(name, pattern) { + if _, err := lithe.ParseWorkspaceContext(at(c, "params", "context")); code(err) != "sdk.host.invalidContext" { + t.Errorf("%s: %v", name, err) + } + contexts++ + break + } + } + } + if keys != 2 || contexts != 3 { + t.Errorf("checked %d keys and %d contexts, want 2 and 3", keys, contexts) + } + s.assertQuiet() + + // A full context from listContexts is passed on as its reference. + workspace, err := lithe.ParseWorkspaceContext(j(t, `{"contextID": "w1", "generation": 2, "name": "orders", "folders": []}`)) + must(t, err) + asking := background(func() (json.RawMessage, error) { return host.Workspace().GetFolders(workspace) }) + request := s.take("lithe/host/workspace/getFolders") + eq(t, request["params"], `{"context": {"contextID": "w1", "generation": 2}}`) + s.reply(request, map[string]any{"folders": []any{}}) + result := done(t, asking) + must(t, result.err) + eq(t, result.value, `{"folders": []}`) + s.close() +} + +func TestHostRefusalsKeepTheCodeNumberAndDetailsCoreSent(t *testing.T) { + f := fixture(t) + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + answer := func(wire any) *lithe.SdkError { + t.Helper() + pending := background(func() (json.RawMessage, error) { + return host.Request("lithe/host/workspace/listContexts", nil) + }) + s.refuse(s.take("lithe/host/workspace/listContexts"), wire) + return refusal(t, pending) + } + refusals := 0 + for _, c := range cases(t, f, "hostRequests") { + expected, _ := c["expected"].(map[string]any) + expectedCode, ok := expected["code"].(string) + if !ok { + continue + } + data := map[string]any{"code": expectedCode} + if details := expected["details"]; details != nil { + data["details"] = details + } + err := answer(map[string]any{"code": expected["rpcCode"], "message": "Refused.", "data": data}) + if err.Code() != expectedCode { + t.Errorf("%s: code = %q", c["name"], err.Code()) + } + eq(t, rpcCode(t, err), encode(t, expected["rpcCode"])) + if details := expected["details"]; details == nil { + if err.Details() != nil { + t.Errorf("%s: details = %v", c["name"], err.Details()) + } + } else { + eq(t, err.Details(), encode(t, details)) + } + if err.Message() != "Refused." { + t.Errorf("%s: message = %q", c["name"], err.Message()) + } + refusals++ + } + if refusals == 0 { + t.Error("the fixture has no refusals") + } + failures := cases(t, f, "hostFailures") + if len(failures) == 0 { + t.Error("the fixture has no host failures") + } + for _, c := range failures { + expected := c["expected"].(map[string]any) + wireNumber := number(expected["rpcCode"]) + index := slices.IndexFunc(lithe.HostErrorCodes, func(entry lithe.ErrorCode) bool { return entry.Code == expected["code"] }) + if index < 0 || lithe.HostErrorCodes[index].Number != wireNumber { + t.Errorf("%s: %v is not listed with %d", c["name"], expected["code"], wireNumber) + } + // The number alone names the code. + if err := answer(map[string]any{"code": wireNumber, "message": "Failed."}); err.Code() != expected["code"] { + t.Errorf("%s: code = %q", c["name"], err.Code()) + } + } + later := answer(j(t, `{"code": -32050, "message": "Later code.", "data": {"details": ["not", "an", "object"]}}`)) + if later.Code() != "plugin.host.failed" || later.Details() != nil { + t.Errorf("a later code = %q, %v", later.Code(), later.Details()) + } + s.close() +} + +func TestWithoutPluginFunctionsTheHostOffersNoServiceAndHostRequestsStayWithinLitheHost(t *testing.T) { + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, nil) + unavailable := func(label string, err error) { + t.Helper() + var sdk *lithe.SdkError + if !errors.As(err, &sdk) || sdk.Code() != "plugin.host.unavailable" { + t.Errorf("%s: %v", label, err) + return + } + if number, ok := sdk.RPCCode(); !ok || number != -32601 { + t.Errorf("%s: rpc code = %d, %t", label, number, ok) + } + } + _, _, err := host.Credentials().Get("connection.prod") + unavailable("credentials", err) + _, err = host.Capabilities() + unavailable("capabilities", err) + if supported, err := host.Supports("lithe/host/credentials/get"); supported || err != nil { + t.Errorf("supports = %t, %v", supported, err) + } + // The relay is a host service too, and so is the generic request. + call := map[string]any{"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings"} + _, err = host.Functions().Providers("languageImport.settings") + unavailable("providers", err) + _, err = host.Functions().Invoke(testContext(), call) + unavailable("invoke", err) + _, err = host.Request("lithe/host/functions/invoke", map[string]any{}) + unavailable("request", err) + if _, err := host.Request("lithe/function/invoke", map[string]any{}); code(err) != "sdk.host.method" { + t.Errorf("a backend method: %v", err) + } + s.assertQuiet() + s.close() + + idle := lithe.NewBackend("idle").Handle().Host() + if _, _, err := idle.Credentials().Get("key"); code(err) != "sdk.session.notReady" { + t.Errorf("an idle backend: %v", err) + } +} + +func TestCapabilitiesAreAskedForOnceAndSupportsReadsThem(t *testing.T) { + var answer any + for _, c := range cases(t, fixture(t), "hostRequests") { + if value, ok := c["expected"].(map[string]any)["answer"]; ok { + answer = value + break + } + } + if answer == nil { + t.Fatal("the fixture has no capabilities answer") + } + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + first := background(func() (bool, error) { return host.Supports("lithe/host/workspace/getFolders") }) + second := background(func() (bool, error) { return host.Supports("lithe/host/workspace/readFile") }) + request := s.take("lithe/host/getCapabilities") + if _, present := request["params"]; present { + t.Errorf("the capabilities request has params: %s", encode(t, request)) + } + s.reply(request, answer) + if result := done(t, first); !result.value || result.err != nil { + t.Errorf("getFolders = %t, %v", result.value, result.err) + } + if result := done(t, second); result.value || result.err != nil { + t.Errorf("readFile = %t, %v", result.value, result.err) + } + capabilities, err := host.Capabilities() + must(t, err) + eq(t, at(j(t, string(capabilities)), "limits", "pendingHostRequests"), `16`) + if asked := len(s.sent("lithe/host/getCapabilities")); asked != 1 { + t.Errorf("capabilities were asked for %d times", asked) + } + s.close() +} + +func TestACallCarriesItsWorkspaceContextToTheHandler(t *testing.T) { + checked := 0 + for _, c := range cases(t, fixture(t), "invocationContexts") { + params, _ := at(c, "expected", "params").(map[string]any) + if params == nil { + continue + } + seen := make(chan *lithe.WorkspaceContext, 1) + backend := lithe.NewBackend("test-backend") + must(t, backend.Function(params["functionID"].(string), func(_ json.RawMessage, call *lithe.Context) (any, error) { + seen <- call.WorkspaceContext() + return nil, nil + })) + s := startSession(t, backend, []any{0}) + s.request(9, "lithe/function/invoke", params) + if response := s.response(9); response["error"] != nil { + t.Errorf("%s: %s", c["name"], encode(t, response)) + } + eq(t, within(t, seen), encode(t, params["context"])) + s.close() + checked++ + } + if checked == 0 { + t.Error("the fixture has no invocation contexts") + } +} + +func TestCancellingACallCancelsItsHostRequestsAtCore(t *testing.T) { + failure := make(chan string, 1) + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("secret.read", func(_ json.RawMessage, call *lithe.Context) (any, error) { + secret, _, err := call.Host().Credentials().Get("connection.prod") + failure <- code(err) + if err != nil { + return nil, err + } + return secret, nil + })) + s := startSession(t, backend, []any{0}) + s.request(41, "lithe/function/invoke", map[string]any{"functionID": "secret.read", "operationID": "c"}) + request := s.take("lithe/host/credentials/get") + s.notify("$/cancelRequest", map[string]any{"id": 41}) + eq(t, at(s.response(41), "error", "code"), `-32800`) + // The host request fails with the call's cancellation. + if got := within(t, failure); got != "sdk.call.cancelled" { + t.Errorf("the host request failed with %q", got) + } + var cancels []any + for _, frame := range s.sent("$/cancelRequest") { + cancels = append(cancels, frame["params"]) + } + eq(t, cancels, encode(t, []any{map[string]any{"id": request["id"]}})) + // Core's late answer is dropped; the session continues. + s.refuse(request, j(t, `{"code": -32800, "message": "Cancelled.", "data": {"code": "plugin.host.cancelled"}}`)) + if exit := s.close(); exit != 1 { + t.Errorf("exit code = %d", exit) + } +} + +func TestACancelledTokenEndsItsRequestWhichIsNeverSentAgain(t *testing.T) { + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + stop := lithe.NewCancellation() + cancellable := host.WithCancellation(stop) + edit := j(t, `{"documentID": "d1", "expectedVersion": 4, "edits": []}`) + pending := background(func() (json.RawMessage, error) { + return cancellable.Editor().ApplyEdits(testContext(), edit) + }) + request := s.take("lithe/host/editor/applyEdits") + eq(t, request["params"], `{ + "documentID": "d1", "expectedVersion": 4, "edits": [], + "context": {"contextID": "w1", "generation": 2} + }`) + stop.Cancel() + if got := code(done(t, pending).err); got != "sdk.call.cancelled" { + t.Errorf("the cancelled request failed with %q", got) + } + cancel := s.takeWhere(func(frame map[string]any) bool { return frame["method"] == "$/cancelRequest" }) + eq(t, cancel["params"], encode(t, map[string]any{"id": request["id"]})) + s.reply(request, j(t, `{"documentID": "d1", "version": 5, "applied": true}`)) + if _, err := cancellable.Request("lithe/host/editor/applyEdits", map[string]any{}); code(err) != "sdk.call.cancelled" { + t.Errorf("a later request: %v", err) + } + if sent := len(s.sent("lithe/host/editor/applyEdits")); sent != 1 { + t.Errorf("applyEdits was sent %d times", sent) + } + s.close() +} + +func TestAtMostSixteenHostRequestsAreUnansweredLaterOnesWaitForAFreeSlot(t *testing.T) { + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + var calls []<-chan outcome[json.RawMessage] + for range 18 { + calls = append(calls, background(func() (json.RawMessage, error) { return host.Workspace().ListContexts() })) + } + first := s.sent("lithe/host/workspace/listContexts") + if len(first) != 16 { + t.Fatalf("%d requests were sent, want 16", len(first)) + } + s.reply(first[0], j(t, `{"revision": 1, "contexts": []}`)) + if sent := len(s.sent("lithe/host/workspace/listContexts")); sent != 17 { + t.Errorf("%d requests were sent after one answer, want 17", sent) + } + // Ending the session fails the queued request too. + s.close() + var outcomes []string + for _, call := range calls { + result := done(t, call) + if result.err != nil { + outcomes = append(outcomes, code(result.err)) + } else { + outcomes = append(outcomes, encode(t, normalize(t, result.value))) + } + } + slices.Sort(outcomes) + expected := []string{encode(t, j(t, `{"revision": 1, "contexts": []}`))} + for range 17 { + expected = append(expected, "sdk.session.closed") + } + slices.Sort(expected) + if !slices.Equal(outcomes, expected) { + t.Errorf("outcomes = %v", outcomes) + } +} + +func TestSubscriptionEventsArriveInOrderAlsoWhenSentBeforeTheAnswer(t *testing.T) { + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + watched := j(t, `{"resource": {"rootID": "r1", "path": ""}, "recursive": true}`) + watching := background(func() (*lithe.Subscription, error) { + return host.Workspace().Watch(testContext(), watched) + }) + request := s.take("lithe/host/workspace/watch") + eq(t, request["params"], `{ + "resource": {"rootID": "r1", "path": ""}, "recursive": true, + "context": {"contextID": "w1", "generation": 2} + }`) + notify := func(sequence int) { + s.notify("lithe/host/subscriptions/notify", map[string]any{ + "subscriptionID": "s1", "sequence": sequence, + "event": map[string]any{"rootID": "r1", "changedPaths": []any{fmt.Sprintf("f%d", sequence)}, "requiresRescan": false}, + }) + } + notify(1) + s.reply(request, map[string]any{"subscriptionID": "s1"}) + answered := done(t, watching) + must(t, answered.err) + subscription := answered.value + notify(2) + notify(4) + var seen []any + for range 3 { + event, err := subscription.RecvTimeout(wait) + must(t, err) + changed := at(j(t, string(event.Event())), "changedPaths") + seen = append(seen, []any{event.SubscriptionID(), event.Sequence(), event.Gap(), changed}) + } + eq(t, seen, `[["s1", 1, false, ["f1"]], ["s1", 2, false, ["f2"]], ["s1", 4, true, ["f4"]]]`) + if subscription.ID() != "s1" || subscription.IsDisposed() { + t.Errorf("subscription %q, disposed %t", subscription.ID(), subscription.IsDisposed()) + } + + disposing := background(func() (struct{}, error) { return struct{}{}, subscription.Dispose() }) + dispose := s.take("lithe/host/subscriptions/dispose") + if !subscription.IsDisposed() { + t.Error("the subscription is live while it is disposed") + } + eq(t, dispose["params"], `{"subscriptionID": "s1"}`) + notify(5) + s.reply(dispose, nil) + must(t, done(t, disposing).err) + // Event 5 came after the disposal; it was dropped. + if _, err := subscription.RecvTimeout(quiet); !errors.Is(err, lithe.ErrSubscriptionDisposed) { + t.Errorf("RecvTimeout after the disposal = %v", err) + } + if _, ok := subscription.Recv(); ok { + t.Error("Recv after the disposal received an event") + } + s.close() +} + +func TestCommandsContextChangesAndLaterHostNotificationsReachTheirHandlers(t *testing.T) { + var delivered []map[string]any + for _, c := range cases(t, fixture(t), "hostNotifications") { + if at(c, "expected", "delivered") == true && c["method"] != "lithe/host/subscriptions/notify" { + delivered = append(delivered, c) + } + } + key := func(entry []any) string { return encode(t, normalize(t, entry)) } + expected := map[string]bool{} + for _, c := range delivered { + params := c["params"] + switch method := c["method"].(string); method { + case "lithe/host/commands/didRun": + expected[key([]any{"command", at(params, "commandID"), at(params, "context")})] = true + case "lithe/host/workspace/didChangeContexts": + expected[key([]any{"contexts", params})] = true + default: + expected[key([]any{"notification", method, params})] = true + } + } + expected[key([]any{"later", map[string]any{"value": 1}})] = true + // Every delivered case is told apart by its method and params. + if len(expected) != len(delivered)+1 { + t.Fatalf("%d distinct notifications for %d cases", len(expected), len(delivered)) + } + + seen := make(chan []any, 64) + backend := lithe.NewBackend("test-backend") + must(t, backend.OnCommand("db.refresh", func(commandID string, context *lithe.WorkspaceContext) error { + var reference any + if context != nil { + reference = *context + } + seen <- []any{"command", commandID, reference} + return nil + })) + backend.OnContextsChanged(func(params json.RawMessage) error { + seen <- []any{"contexts", params} + return nil + }) + must(t, backend.OnHostNotification("lithe/host/later/didSomething", func(params json.RawMessage) error { + seen <- []any{"later", params} + return nil + })) + // The other delivered methods (run exits, language server changes and + // forwarded notifications) use the generic registration, once each. + generic := map[string]bool{} + for _, c := range delivered { + method := c["method"].(string) + if method != "lithe/host/commands/didRun" && method != "lithe/host/workspace/didChangeContexts" { + generic[method] = true + } + } + if len(generic) != 3 { + t.Fatalf("%d generic methods, want 3", len(generic)) + } + for method := range generic { + must(t, backend.OnHostNotification(method, func(params json.RawMessage) error { + seen <- []any{"notification", method, params} + return nil + })) + } + if err := backend.OnHostNotification("lithe/host/commands/didRun", func(json.RawMessage) error { return nil }); code(err) != "sdk.method.reserved" { + t.Errorf("a routed method: %v", err) + } + if err := backend.OnHostNotification("workspace/didChange", func(json.RawMessage) error { return nil }); code(err) != "sdk.method.invalid" { + t.Errorf("a method outside lithe/host: %v", err) + } + if err := backend.OnCommand("DB_Refresh", func(string, *lithe.WorkspaceContext) error { return nil }); code(err) != "sdk.command.invalidID" { + t.Errorf("an invalid command ID: %v", err) + } + + s := startSession(t, backend, []any{0}) + for _, c := range delivered { + s.notify(c["method"].(string), c["params"]) + } + // A notification this SDK does not know is ignored, as the contract asks. + s.notify("lithe/host/unknown/ignored", map[string]any{"anything": true}) + s.notify("lithe/host/later/didSomething", map[string]any{"value": 1}) + // Handlers run on their own goroutines, so only the set is fixed. + received := map[string]bool{} + for range len(expected) { + received[key(within(t, seen))] = true + } + if !reflect.DeepEqual(received, expected) { + t.Errorf("received %v\nexpected %v", received, expected) + } + select { + case extra := <-seen: + t.Errorf("an extra notification: %s", encode(t, extra)) + case <-time.After(quiet): + } + s.assertQuiet() + s.close() +} + +func TestNativeTerminalMethodsKeepContextAndLiteralArguments(t *testing.T) { + backend := lithe.NewBackend("terminal-test") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + creating := background(func() (json.RawMessage, error) { + return host.Terminal().Create(testContext(), map[string]any{ + "executable": "example-client", "arguments": []string{"literal;$(value)", "space value"}, + }) + }) + create := s.take("lithe/host/terminal/create") + eq(t, at(create, "params", "context"), `{"contextID": "w1", "generation": 2}`) + eq(t, at(create, "params", "arguments"), `["literal;$(value)", "space value"]`) + s.reply(create, map[string]any{"terminalID": "owned"}) + created := done(t, creating) + must(t, created.err) + eq(t, created.value, `{"terminalID": "owned"}`) + for _, method := range []string{"show", "close", "reopen", "dispose"} { + operation := background(func() (json.RawMessage, error) { + terminal := host.Terminal() + switch method { + case "show": + return terminal.Show(testContext(), "owned") + case "close": + return terminal.Close(testContext(), "owned", 4096) + case "reopen": + return terminal.Reopen(testContext(), "owned") + } + return terminal.Dispose(testContext(), "owned") + }) + request := s.take("lithe/host/terminal/" + method) + eq(t, at(request, "params", "terminalID"), `"owned"`) + if method == "close" { + eq(t, at(request, "params", "retainedContextBytes"), `4096`) + } + s.reply(request, nil) + result := done(t, operation) + must(t, result.err) + eq(t, result.value, `null`) + } + s.close() +} + +func TestARelayedCallNamesThePluginThatCalledItAndAHostCallNamesNone(t *testing.T) { + checked := 0 + for _, c := range cases(t, fixture(t), "invocationCallers") { + params := at(c, "expected", "params").(map[string]any) + seen := make(chan *lithe.Caller, 1) + backend := lithe.NewBackend("test-backend") + must(t, backend.Function(params["functionID"].(string), func(_ json.RawMessage, call *lithe.Context) (any, error) { + seen <- call.Caller() + return nil, nil + })) + s := startSession(t, backend, []any{0}) + s.request(9, "lithe/function/invoke", params) + if response := s.response(9); response["error"] != nil { + t.Errorf("%s: %s", c["name"], encode(t, response)) + } + caller := within(t, seen) + want, named := at(params, "caller", "pluginID").(string) + if named != (caller != nil) || caller != nil && caller.PluginID() != want { + t.Errorf("%s: caller = %v, want %q", c["name"], caller, want) + } + s.close() + checked++ + } + if checked == 0 { + t.Error("the fixture has no invocation callers") + } +} + +func TestACallerThatIsNotExactlyAPluginIDIsNotReported(t *testing.T) { + seen := make(chan *lithe.Caller, 1) + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("languageImport.settings", func(_ json.RawMessage, call *lithe.Context) (any, error) { + seen <- call.Caller() + return nil, nil + })) + s := startSession(t, backend, []any{0}) + python := "dev.lithe.fixture.python" + attempts := []struct { + caller any + want string + }{ + {map[string]any{"pluginID": python}, python}, + {map[string]any{"pluginID": ""}, ""}, + {map[string]any{"pluginID": 7}, ""}, + {map[string]any{}, ""}, + {map[string]any{"pluginID": python, "extra": true}, ""}, + {python, ""}, + {nil, ""}, + } + for index, attempt := range attempts { + id := 10 + index + s.invokeWith(id, "languageImport.settings", map[string]any{}, map[string]any{"caller": attempt.caller}) + response := s.response(id) + if response["error"] != nil || response["result"] != nil { + t.Errorf("%s: %s", encode(t, attempt.caller), encode(t, response)) + } + caller := within(t, seen) + reported := "" + if caller != nil { + reported = caller.PluginID() + } + if reported != attempt.want { + t.Errorf("%s: reported %q", encode(t, attempt.caller), reported) + } + } + s.close() +} + +func TestRelayRequestsCarryTheFixtureParamsAndOnlyTheFieldsTheMethodsDefine(t *testing.T) { + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + forwarded := 0 + for _, c := range cases(t, fixture(t), "hostRequests") { + if at(c, "expected", "relay") != true { + continue + } + method := c["method"].(string) + params := c["params"].(map[string]any) + providers := strings.HasSuffix(method, "/providers") + answer := j(t, `{"value": {"settings": []}}`) + if providers { + answer = j(t, `{"providers": [{"pluginID": "dev.lithe.fixture.go", "version": 1}]}`) + } + sending := background(func() (json.RawMessage, error) { + if providers { + return host.Functions().Providers(params["functionID"].(string)) + } + context, err := lithe.ParseWorkspaceContext(params["context"]) + if err != nil { + return nil, err + } + return host.Functions().Invoke(context, params) + }) + request := s.take(method) + eq(t, request["params"], encode(t, params)) + s.reply(request, answer) + result := done(t, sending) + if result.err != nil { + t.Errorf("%s: %v", c["name"], result.err) + } + eq(t, result.value, encode(t, answer)) + forwarded++ + } + if forwarded != 3 { + t.Errorf("%d relay cases, want 3", forwarded) + } + + // Fields the method does not define are not sent: Core would refuse a + // top-level caller, and the call's context is the argument. + call := j(t, `{ + "pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", + "caller": {"pluginID": "dev.lithe.fixture.other"}, + "context": {"contextID": "other", "generation": 9}, "extra": true + }`) + sending := background(func() (json.RawMessage, error) { return host.Functions().Invoke(testContext(), call) }) + request := s.take("lithe/host/functions/invoke") + eq(t, request["params"], `{ + "pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", + "context": {"contextID": "w1", "generation": 2} + }`) + s.reply(request, map[string]any{"value": nil}) + must(t, done(t, sending).err) + s.close() +} + +func TestARelayedCallFromAHandlerBelongsToTheCallItServesUnlessItNamesAnother(t *testing.T) { + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("project.collect", func(params json.RawMessage, served *lithe.Context) (any, error) { + value, err := served.Host().Functions().Invoke(testContext(), params) + if err != nil { + return nil, err + } + return value, nil + })) + s := startSession(t, backend, []any{0}) + call := func(extra string) any { + return j(t, `{"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings"`+extra+`}`) + } + + s.invoke(5, "project.collect", call("")) + request := s.take("lithe/host/functions/invoke") + eq(t, at(request, "params", "parentOperationID"), `"op-5"`) + s.reply(request, j(t, `{"value": {"files": 3}}`)) + eq(t, s.response(5)["result"], `{"value": {"files": 3}}`) + + s.invoke(6, "project.collect", call(`, "parentOperationID": "op-elsewhere"`)) + request = s.take("lithe/host/functions/invoke") + eq(t, at(request, "params", "parentOperationID"), `"op-elsewhere"`) + s.reply(request, map[string]any{"value": nil}) + eq(t, s.response(6)["result"], `{"value": null}`) + + // A parent the contract would refuse never leaves the SDK. + s.invoke(7, "project.collect", call(`, "parentOperationID": ""`)) + if response := s.response(7); response["error"] == nil { + t.Errorf("an invalid parent: %s", encode(t, response)) + } + if sent := len(s.sent("lithe/host/functions/invoke")); sent != 2 { + t.Errorf("%d relayed calls were sent, want 2", sent) + } + s.close() +} + +func TestRelayRefusalsKeepTheCodeNumberAndTheProvidersOwnCode(t *testing.T) { + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + call := map[string]any{"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings"} + refused := func(wire any) *lithe.SdkError { + t.Helper() + pending := background(func() (json.RawMessage, error) { return host.Functions().Invoke(testContext(), call) }) + s.refuse(s.take("lithe/host/functions/invoke"), wire) + return refusal(t, pending) + } + relayErrors := cases(t, fixture(t), "relayErrors") + if len(relayErrors) != 15 { + t.Errorf("%d relay errors, want 15", len(relayErrors)) + } + for _, c := range relayErrors { + expected := c["code"].(string) + wireNumber := number(c["rpcCode"]) + named := refused(map[string]any{"code": wireNumber, "message": "Refused.", "data": map[string]any{"code": expected}}) + // The number alone names the code. + numbered := refused(map[string]any{"code": wireNumber, "message": "Refused."}) + for _, err := range []*lithe.SdkError{named, numbered} { + if got, ok := err.RPCCode(); err.Code() != expected || !ok || got != wireNumber { + t.Errorf("%s: %q, %d", c["name"], err.Code(), got) + } + } + } + failed := refused(j(t, `{ + "code": -32070, "message": "The provider failed.", + "data": {"code": "plugin.function.failed", "details": {"pluginErrorCode": "db.locked"}} + }`)) + if failed.Code() != "plugin.function.failed" { + t.Errorf("code = %q", failed.Code()) + } + eq(t, failed.Details(), `{"pluginErrorCode": "db.locked"}`) + s.close() +} + +func TestAnInvalidRelayedCallFailsLocallyAndNothingIsSent(t *testing.T) { + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + functions := host.Functions() + invalid := func(label string, err error) { + t.Helper() + if code(err) != "sdk.functions.invalidCall" { + t.Errorf("%s: %v", label, err) + } + } + for _, attempt := range []struct { + field string + bad any + }{ + {"pluginID", ""}, + {"pluginID", 7}, + {"functionID", "Not-Valid"}, + {"params", []any{1}}, + {"timeoutMilliseconds", 0}, + {"timeoutMilliseconds", -5}, + {"timeoutMilliseconds", 1.5}, + {"timeoutMilliseconds", "5"}, + {"parentOperationID", 17}, + {"parentOperationID", ""}, + {"parentOperationID", strings.Repeat("p", 129)}, + } { + call := map[string]any{"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings"} + call[attempt.field] = attempt.bad + _, err := functions.Invoke(testContext(), call) + invalid(fmt.Sprintf("%s: %v", attempt.field, attempt.bad), err) + } + for _, call := range []string{ + `[]`, + `{"functionID": "languageImport.settings"}`, + `{"pluginID": "dev.lithe.fixture.go"}`, + } { + _, err := functions.Invoke(testContext(), j(t, call)) + invalid(call, err) + } + for _, bad := range []string{"", "Not-Valid", "UPPER", "a..b"} { + _, err := functions.Providers(bad) + invalid(fmt.Sprintf("providers %q", bad), err) + } + + // The fixture's cases Core refuses as invalid params agree with these + // checks, whenever the call names a context. + refused := 0 + for _, c := range cases(t, fixture(t), "hostRequests") { + params, _ := c["params"].(map[string]any) + if _, named := params["context"]; c["method"] != "lithe/host/functions/invoke" || + at(c, "expected", "code") != "plugin.host.invalidParams" || !named { + continue + } + workspace, err := lithe.ParseWorkspaceContext(params["context"]) + must(t, err) + _, err = functions.Invoke(workspace, params) + invalid(c["name"].(string), err) + refused++ + } + if refused != 4 { + t.Errorf("%d invalid relay cases, want 4", refused) + } + s.assertQuiet() + s.close() +} + +func TestRelayAnswersAreTheHostsObjectsAndANullValueStaysInsideValue(t *testing.T) { + backend := lithe.NewBackend("test-backend") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + providers := func() <-chan outcome[json.RawMessage] { + return background(func() (json.RawMessage, error) { return host.Functions().Providers("languageImport.settings") }) + } + listing := providers() + answer := `{"providers": [{"pluginID": "dev.lithe.fixture.go", "version": 1}]}` + s.reply(s.take("lithe/host/functions/providers"), j(t, answer)) + listed := done(t, listing) + must(t, listed.err) + eq(t, listed.value, answer) + + call := map[string]any{"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings"} + calling := background(func() (json.RawMessage, error) { return host.Functions().Invoke(testContext(), call) }) + s.reply(s.take("lithe/host/functions/invoke"), map[string]any{"value": nil}) + called := done(t, calling) + must(t, called.err) + eq(t, called.value, `{"value": null}`) + + // An answer that is not an object is the host's mistake, not a value. + broken := providers() + s.reply(s.take("lithe/host/functions/providers"), []any{}) + if got := code(done(t, broken).err); got != "sdk.host.invalidResult" { + t.Errorf("a non-object answer: %q", got) + } + s.close() +} + +func TestCancellingACallCancelsTheRelayedCallItWaitsOn(t *testing.T) { + failure := make(chan string, 1) + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("project.collect", func(params json.RawMessage, served *lithe.Context) (any, error) { + value, err := served.Host().Functions().Invoke(testContext(), params) + failure <- code(err) + if err != nil { + return nil, err + } + return value, nil + })) + s := startSession(t, backend, []any{0}) + s.invoke(41, "project.collect", map[string]any{"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings"}) + request := s.take("lithe/host/functions/invoke") + s.notify("$/cancelRequest", map[string]any{"id": 41}) + eq(t, at(s.response(41), "error", "code"), `-32800`) + // The relayed request fails with the call's cancellation, and Core is told. + if got := within(t, failure); got != "sdk.call.cancelled" { + t.Errorf("the relayed call failed with %q", got) + } + var cancels []any + for _, frame := range s.sent("$/cancelRequest") { + cancels = append(cancels, frame["params"]) + } + eq(t, cancels, encode(t, []any{map[string]any{"id": request["id"]}})) + s.close() +} diff --git a/shared/plugins/sdk/go/lithe/keymap_test.go b/shared/plugins/sdk/go/lithe/keymap_test.go new file mode 100644 index 00000000..1f1d55b1 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/keymap_test.go @@ -0,0 +1,143 @@ +package lithe_test + +// Shortcut providers negotiate independently of plugin functions. + +import ( + "encoding/json" + "fmt" + "testing" + "time" + + "github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go/lithe" +) + +func initializeKeymap(t *testing.T, host *testHost, experimental string) any { + t.Helper() + host.request(0, "initialize", j(t, `{"capabilities": {"experimental": `+experimental+`}}`)) + answer, _ := host.answer(0) + return answer["result"] +} + +func TestNegotiatesOnlyOfferedProvidersAndInvokesTheTypedDomainRequest(t *testing.T) { + requests := make(chan [2]string, 1) + backend := lithe.NewBackend("test-backend") + must(t, backend.KeymapImportProvider("first", func(request lithe.KeymapImportRequest, _ *lithe.Context) (any, error) { + requests <- [2]string{request.ProviderID(), request.SnapshotID()} + return map[string]any{"bindings": []any{}}, nil + })) + must(t, backend.KeymapImportProvider("not-offered", func(lithe.KeymapImportRequest, *lithe.Context) (any, error) { + return map[string]any{"bindings": []any{}}, nil + })) + host := startHost(t, backend) + result := initializeKeymap(t, host, `{ + "litheLogging": {"versions": [0]}, + "litheKeymapImport": {"versions": [0], "providers": ["first", "unknown"]} + }`) + eq(t, at(result, "capabilities", "experimental", "litheKeymapImport"), `{"version": 0, "providers": ["first"]}`) + + host.request(1, "lithe/keymap/import", map[string]any{"providerID": "first", "snapshotID": "snapshot-1"}) + answer, before := host.answer(1) + eq(t, answer["result"], `{"bindings": []}`) + if got := within(t, requests); got != [2]string{"first", "snapshot-1"} { + t.Errorf("the provider saw %v", got) + } + // The fact names the wire method Core accepts, never the provider-scoped call ID. + var facts []map[string]any + for _, frame := range before { + if frame["method"] == "lithe/log" { + facts = append(facts, frame) + } + } + if len(facts) != 1 { + t.Fatalf("%d facts before the answer: %s", len(facts), encode(t, before)) + } + eq(t, at(facts[0], "params", "kind"), `"operationFinished"`) + eq(t, at(facts[0], "params", "operation"), `"lithe/keymap/import"`) + + host.request(2, "lithe/keymap/import", map[string]any{"providerID": "not-offered", "snapshotID": "snapshot-1"}) + if answer, _ := host.answer(2); at(answer, "error") == nil { + t.Errorf("a provider the host did not offer answered: %s", encode(t, answer)) + } + host.request(3, "lithe/keymap/import", map[string]any{"providerID": "first", "snapshotID": "../private"}) + if answer, _ := host.answer(3); at(answer, "error") == nil { + t.Errorf("an invalid snapshot ID answered: %s", encode(t, answer)) + } + host.request(4, "shutdown", nil) + answer, _ = host.answer(4) + if result, present := answer["result"]; !present || result != nil { + t.Errorf("shutdown answered %s", encode(t, answer)) + } + host.notify("exit", nil) + if exit := host.exitCode(); exit != 0 { + t.Errorf("exit code = %d", exit) + } +} + +func TestCancellationReachesARunningProvider(t *testing.T) { + entered := make(chan struct{}, 1) + cancelled := make(chan struct{}, 1) + backend := lithe.NewBackend("test-backend") + must(t, backend.KeymapImportProvider("first", func(_ lithe.KeymapImportRequest, call *lithe.Context) (any, error) { + release := make(chan struct{}, 1) + call.Cancellation().OnCancel(func() { + cancelled <- struct{}{} + release <- struct{}{} + }) + entered <- struct{}{} + select { + case <-release: + case <-time.After(wait): + return nil, fmt.Errorf("the provider was not cancelled") + } + if err := call.CheckCancelled(); err != nil { + return nil, err + } + return map[string]any{"bindings": []any{}}, nil + })) + host := startHost(t, backend) + initializeKeymap(t, host, `{ + "litheLogging": {"versions": [0]}, + "litheKeymapImport": {"versions": [0], "providers": ["first"]} + }`) + host.request(1, "lithe/keymap/import", map[string]any{"providerID": "first", "snapshotID": "snapshot-1"}) + within(t, entered) + host.notify("$/cancelRequest", map[string]any{"id": 1}) + within(t, cancelled) + answer, _ := host.answer(1) + eq(t, at(answer, "error", "code"), `-32800`) + host.close() +} + +func TestAProviderListsAndReadsSelectedFilesThroughTheScopedHost(t *testing.T) { + backend := lithe.NewBackend("test-backend") + must(t, backend.KeymapImportProvider("first", func(request lithe.KeymapImportRequest, call *lithe.Context) (any, error) { + files, err := request.ListInputs(call.Host()) + if err != nil { + return nil, err + } + data, err := request.ReadChunk(call.Host(), files[0].ID, 0, 4) + if err != nil { + return nil, err + } + if string(data) != "data" || files[0].Path != "keys.json" || files[0].ByteCount != 4 { + return nil, fmt.Errorf("read %q from %+v", data, files[0]) + } + return json.RawMessage(`{"bindings": [{"commandID": "find-next", "keys": [{"key": "f3", "modifiers": []}]}]}`), nil + })) + host := startHost(t, backend) + initializeKeymap(t, host, `{ + "litheLogging": {"versions": [0]}, "litheFunctions": {"versions": [0]}, + "litheKeymapImport": {"versions": [0], "providers": ["first"]} + }`) + host.request(1, "lithe/keymap/import", map[string]any{"providerID": "first", "snapshotID": "snapshot-1"}) + list := host.next() + eq(t, list["method"], `"lithe/host/keymapImport/listInputs"`) + host.reply(list, j(t, `{"files": [{"id": "file-0", "path": "keys.json", "byteCount": 4}]}`)) + read := host.next() + eq(t, read["method"], `"lithe/host/keymapImport/readChunk"`) + eq(t, at(read, "params", "fileID"), `"file-0"`) + host.reply(read, map[string]any{"data": "ZGF0YQ=="}) + answer, _ := host.answer(1) + eq(t, answer["result"], `{"bindings": [{"commandID": "find-next", "keys": [{"key": "f3", "modifiers": []}]}]}`) + host.close() +} diff --git a/shared/plugins/sdk/go/lithe/protocol.go b/shared/plugins/sdk/go/lithe/protocol.go new file mode 100644 index 00000000..c2b7938f --- /dev/null +++ b/shared/plugins/sdk/go/lithe/protocol.go @@ -0,0 +1,327 @@ +package lithe + +import ( + "bytes" + "encoding/json" + "errors" + "math" + "strconv" + "strings" + "unicode/utf8" +) + +// Protocol versions this SDK speaks. +const ( + FunctionsVersion = 0 + LoggingVersion = 0 + KeymapImportVersion = 0 +) + +// JSON-RPC methods of the backend protocol. +const ( + methodInitialize = "initialize" + methodShutdown = "shutdown" + methodExit = "exit" + methodCancelRequest = "$/cancelRequest" + methodLog = "lithe/log" + methodInvoke = "lithe/function/invoke" + methodRegister = "lithe/function/register" + methodUnregister = "lithe/function/unregister" + methodProgress = "lithe/function/progress" + methodKeymapImport = "lithe/keymap/import" + methodKeymapInputs = "lithe/host/keymapImport/listInputs" + methodKeymapChunk = "lithe/host/keymapImport/readChunk" + methodCredentialsGet = "lithe/host/credentials/get" + methodCredentialsSet = "lithe/host/credentials/set" + methodCredentialsDel = "lithe/host/credentials/delete" + methodCapabilities = "lithe/host/getCapabilities" + methodDispose = "lithe/host/subscriptions/dispose" + methodListContexts = "lithe/host/workspace/listContexts" + methodGetContext = "lithe/host/workspace/getContext" + methodGetFolders = "lithe/host/workspace/getFolders" + methodReadDirectory = "lithe/host/workspace/readDirectory" + methodStat = "lithe/host/workspace/stat" + methodReadFile = "lithe/host/workspace/readFile" + methodWatch = "lithe/host/workspace/watch" + methodFindFiles = "lithe/host/workspace/findFiles" + methodFindText = "lithe/host/workspace/findText" + methodDocumentsList = "lithe/host/documents/list" + methodDocumentsSnap = "lithe/host/documents/getSnapshot" + methodEditorActions = "lithe/host/editor/registerActions" + methodEditorActive = "lithe/host/editor/getActive" + methodEditorSelect = "lithe/host/editor/getSelections" + methodEditorApply = "lithe/host/editor/applyEdits" + methodEditorReplace = "lithe/host/editor/replaceSelections" + methodEditorInsert = "lithe/host/editor/insertText" + methodEditorOpen = "lithe/host/editor/open" + methodEditorReveal = "lithe/host/editor/reveal" + methodPreviewHTML = "lithe/host/preview/openHTML" + methodBrowserOpen = "lithe/host/browser/openExternal" + methodShowInfo = "lithe/host/window/showInformation" + methodShowWarning = "lithe/host/window/showWarning" + methodShowError = "lithe/host/window/showError" + methodTerminalCreate = "lithe/host/terminal/create" + methodTerminalShow = "lithe/host/terminal/show" + methodTerminalClose = "lithe/host/terminal/close" + methodTerminalReopen = "lithe/host/terminal/reopen" + methodTerminalDrop = "lithe/host/terminal/dispose" + methodTerminalExit = "lithe/host/terminal/onExit" + methodProviders = "lithe/host/functions/providers" + methodRelayInvoke = "lithe/host/functions/invoke" + methodContexts = "lithe/host/workspace/didChangeContexts" + methodNotify = "lithe/host/subscriptions/notify" + methodCommandRan = "lithe/host/commands/didRun" + hostPrefix = "lithe/host/" +) + +// JSON-RPC error numbers. +const ( + rpcParseError = -32700 + rpcInvalidRequest = -32600 + rpcMethodNotFound = -32601 + rpcInvalidParams = -32602 + rpcInternalError = -32603 + rpcServerNotInitialized = -32002 + rpcRequestFailed = -32000 + rpcRequestCancelled = -32800 +) + +// Protocol limits. +const ( + MaxFunctions = 256 + maxFunctionIDBytes = 128 + maxPluginErrorCode = 64 + maxErrorMessageBytes = 1024 + maxResultBytes = 1 << 20 + maxCredentialKeyBytes = 128 + maxSecretBytes = 16 << 10 + maxPendingHostCalls = 16 + maxEarlyEvents = 128 + maxCommandIDBytes = 128 + maxParentOperation = 128 + maxSafeInteger = 1<<53 - 1 +) + +// IsFunctionID reports whether id is dot-separated lowerCamelCase segments +// of at most 128 bytes, the form of a plugin function ID. +func IsFunctionID(id string) bool { + if id == "" || len(id) > maxFunctionIDBytes { + return false + } + for _, segment := range strings.Split(id, ".") { + if segment == "" || segment[0] < 'a' || segment[0] > 'z' { + return false + } + for i := 1; i < len(segment); i++ { + if !isASCIIAlnum(segment[i]) { + return false + } + } + } + return true +} + +// IsPluginErrorCode reports whether code can name a plugin error: a letter, +// then letters, digits, ".", "_" or "-", at most 64 bytes. +func IsPluginErrorCode(code string) bool { + if code == "" || len(code) > maxPluginErrorCode || !isASCIILetter(code[0]) { + return false + } + for i := 1; i < len(code); i++ { + if !isASCIIAlnum(code[i]) && !strings.ContainsRune("._-", rune(code[i])) { + return false + } + } + return true +} + +// IsCredentialKey reports whether key is 1-128 ASCII letters, digits, ".", +// "_", ":" or "-". Context and subscription IDs use the same form. +func IsCredentialKey(key string) bool { + if key == "" || len(key) > maxCredentialKeyBytes { + return false + } + for i := 0; i < len(key); i++ { + if !isASCIIAlnum(key[i]) && !strings.ContainsRune("._:-", rune(key[i])) { + return false + } + } + return true +} + +// IsCommandID reports whether id is 1-128 lowercase letters, digits, "." or +// "-", the form of a contributed command. +func IsCommandID(id string) bool { + if id == "" || len(id) > maxCommandIDBytes { + return false + } + for i := 0; i < len(id); i++ { + c := id[i] + if !(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && c != '.' && c != '-' { + return false + } + } + return true +} + +// isParentOperationID reports whether id can name the call a cross-plugin +// call belongs to: 1-128 bytes. +func isParentOperationID(id string) bool { + return id != "" && len(id) <= maxParentOperation +} + +func isASCIILetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' } + +func isASCIIAlnum(c byte) bool { return isASCIILetter(c) || c >= '0' && c <= '9' } + +// offers reports whether a capability offer lists protocol version exactly. +func offers(offer any, version int64) bool { + object, ok := offer.(map[string]any) + if !ok { + return false + } + versions, ok := object["versions"].([]any) + if !ok { + return false + } + for _, value := range versions { + if number, ok := value.(json.Number); ok { + if parsed, err := strconv.ParseInt(string(number), 10, 64); err == nil && parsed == version { + return true + } + } + } + return false +} + +// generation reads a positive safe integer; 2 and 2.0 both count. +func generation(value any) (uint64, bool) { + number, ok := value.(json.Number) + if !ok { + return 0, false + } + text := string(number) + var parsed uint64 + if unsigned, err := strconv.ParseUint(text, 10, 64); err == nil { + parsed = unsigned + } else if strings.ContainsAny(text, ".eE") { + float, err := strconv.ParseFloat(text, 64) + if err != nil || float < 1 || float > maxSafeInteger || float != math.Trunc(float) { + return 0, false + } + parsed = uint64(float) + } else { + return 0, false + } + if parsed < 1 || parsed > maxSafeInteger { + return 0, false + } + return parsed, true +} + +// unsignedInteger reads a non-negative JSON integer. +func unsignedInteger(value any) (uint64, bool) { + number, ok := value.(json.Number) + if !ok { + return 0, false + } + parsed, err := strconv.ParseUint(string(number), 10, 64) + return parsed, err == nil +} + +// integer reads a JSON integer that fits in int64. +func integer(value any) (int64, bool) { + number, ok := value.(json.Number) + if !ok { + return 0, false + } + parsed, err := strconv.ParseInt(string(number), 10, 64) + return parsed, err == nil +} + +var errTrailingData = errors.New("trailing data after the JSON value") + +// boundedText cuts text to at most limit bytes on a character boundary. +func boundedText(text string, limit int) string { + if len(text) <= limit { + return text + } + end := limit + for end > 0 && !utf8.RuneStart(text[end]) { + end-- + } + return text[:end] +} + +// decodeJSON parses JSON keeping numbers exact. +func decodeJSON(data []byte) (any, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value any + if err := decoder.Decode(&value); err != nil { + return nil, err + } + if decoder.More() { + return nil, errTrailingData + } + return value, nil +} + +// encodeJSON serializes value as compact JSON without HTML escaping, the +// bytes the host receives. +func encodeJSON(value any) ([]byte, error) { + var buffer bytes.Buffer + encoder := json.NewEncoder(&buffer) + encoder.SetEscapeHTML(false) + if err := encoder.Encode(value); err != nil { + return nil, err + } + return bytes.TrimSuffix(buffer.Bytes(), []byte("\n")), nil +} + +// raw serializes a decoded value for a caller that unmarshals it. +func raw(value any) json.RawMessage { + data, err := encodeJSON(value) + if err != nil { + return json.RawMessage("null") + } + return data +} + +// toValue converts any JSON-serializable Go value into the SDK's dynamic +// form -- map[string]any, []any, string, json.Number, bool and nil -- by +// encoding and decoding it, so nested numbers are exact too. +func toValue(value any) (any, error) { + if value == nil { + return nil, nil + } + data, err := encodeJSON(value) + if err != nil { + return nil, err + } + return decodeJSON(data) +} + +// field is value[key] when value is an object, else nil. +func field(value any, key string) any { + object, _ := value.(map[string]any) + return object[key] +} + +// pointer follows keys through nested objects. +func pointer(value any, keys ...string) any { + for _, key := range keys { + value = field(value, key) + } + return value +} + +// requestKey is a JSON-RPC ID as a map key; numbers and strings never +// collide. +func requestKey(id any) string { + data, err := encodeJSON(id) + if err != nil { + return "null" + } + return string(data) +} diff --git a/shared/plugins/sdk/go/lithe/protocol_test.go b/shared/plugins/sdk/go/lithe/protocol_test.go new file mode 100644 index 00000000..e20e461b --- /dev/null +++ b/shared/plugins/sdk/go/lithe/protocol_test.go @@ -0,0 +1,135 @@ +package lithe + +import ( + "fmt" + "strings" + "testing" +) + +func TestEveryProtocolThisSDKSpeaksIsVersionZero(t *testing.T) { + if FunctionsVersion != 0 || LoggingVersion != 0 || KeymapImportVersion != 0 { + t.Fatalf("versions = %d, %d, %d", FunctionsVersion, LoggingVersion, KeymapImportVersion) + } +} + +func TestAnOfferListsTheVersionExactly(t *testing.T) { + for _, valid := range []string{`{"versions":[0]}`, `{"versions":[99,0]}`} { + if !offers(mustValue(t, valid), 0) { + t.Errorf("%s is not an offer of 0", valid) + } + } + for _, invalid := range []string{ + `{"versions":[1]}`, + `{"versions":[]}`, + `{"versions":["0",true,null,0.5]}`, + `{"versions":0}`, + `{"version":0}`, + `0`, + `null`, + } { + if offers(mustValue(t, invalid), 0) { + t.Errorf("%s is an offer of 0", invalid) + } + } + if offers(nil, 0) { + t.Error("an absent offer offers 0") + } +} + +func TestFunctionIDsAreDotSeparatedLowerCamelCase(t *testing.T) { + for _, valid := range []string{"snapshot.refresh", "query.runAll2"} { + if !IsFunctionID(valid) { + t.Errorf("%q is refused", valid) + } + } + for _, invalid := range []string{"", "Snapshot", "snapshot.", ".a", "a..b", "a-b", "a.B", "1a", strings.Repeat("a", 129)} { + if IsFunctionID(invalid) { + t.Errorf("%q is accepted", invalid) + } + } +} + +func TestPluginErrorCodesAndCredentialKeysUseTheirAlphabets(t *testing.T) { + if !IsPluginErrorCode("db.connection-failed_2") { + t.Error("a valid plugin error code is refused") + } + if IsPluginErrorCode("2db") || IsPluginErrorCode(strings.Repeat("a", 65)) { + t.Error("an invalid plugin error code is accepted") + } + if !IsCredentialKey("connection:prod.password") { + t.Error("a valid credential key is refused") + } + for _, invalid := range []string{"", "has space", strings.Repeat("k", 129)} { + if IsCredentialKey(invalid) { + t.Errorf("credential key %q is accepted", invalid) + } + } + if !IsCommandID("db.refresh-all2") { + t.Error("a valid command ID is refused") + } + for _, invalid := range []string{"", "DB.refresh", "db_refresh", "db refresh", strings.Repeat("a", 129)} { + if IsCommandID(invalid) { + t.Errorf("command ID %q is accepted", invalid) + } + } +} + +func TestParentOperationIDsAreOneToOneHundredTwentyEightBytes(t *testing.T) { + for _, valid := range []string{"17", strings.Repeat("o", 128), strings.Repeat("é", 64)} { + if !isParentOperationID(valid) { + t.Errorf("%q is refused", valid) + } + } + for _, invalid := range []string{"", strings.Repeat("o", 129), strings.Repeat("é", 65)} { + if isParentOperationID(invalid) { + t.Errorf("%q is accepted", invalid) + } + } +} + +func TestGenerationsArePositiveIntegersJSONCarriesExactly(t *testing.T) { + for text, want := range map[string]uint64{ + "2": 2, + "2.0": 2, + fmt.Sprint(maxSafeInteger): maxSafeInteger, + fmt.Sprintf("%de0", 3): 3, + fmt.Sprint(maxSafeInteger) + ".0": maxSafeInteger, + } { + got, ok := generation(mustValue(t, text)) + if !ok || got != want { + t.Errorf("generation(%s) = %d, %t", text, got, ok) + } + } + for _, invalid := range []string{"0", "-1", "1.5", `"2"`, "null", fmt.Sprint(maxSafeInteger + 1)} { + if got, ok := generation(mustValue(t, invalid)); ok { + t.Errorf("generation(%s) = %d", invalid, got) + } + } +} + +func TestBoundedTextNeverSplitsACharacter(t *testing.T) { + for _, c := range []struct { + text string + limit int + want string + }{ + {"abc", 8, "abc"}, + {"aé", 2, "a"}, + {"日本語", 7, "日本"}, + } { + if got := boundedText(c.text, c.limit); got != c.want { + t.Errorf("boundedText(%q, %d) = %q", c.text, c.limit, got) + } + } +} + +func TestDecodeJSONKeepsNumbersExactAndRefusesTrailingData(t *testing.T) { + assertJSON(t, mustValue(t, `{"big":9007199254740993}`), `{"big":9007199254740993}`) + if _, err := decodeJSON([]byte(`{} {}`)); err == nil { + t.Error("trailing data is accepted") + } + data, err := encodeJSON(map[string]any{"html": ""}) + if err != nil || string(data) != `{"html":""}` { + t.Errorf("encodeJSON escapes HTML: %s, %v", data, err) + } +} diff --git a/shared/plugins/sdk/go/lithe/session_test.go b/shared/plugins/sdk/go/lithe/session_test.go new file mode 100644 index 00000000..9217d3c7 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/session_test.go @@ -0,0 +1,524 @@ +package lithe_test + +// The backend session driven by a scripted host over in-process pipes. + +import ( + "encoding/json" + "errors" + "slices" + "sort" + "strings" + "testing" + "time" + + "github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go/lithe" +) + +func echoBackend(t *testing.T) *lithe.Backend { + t.Helper() + backend := lithe.NewBackend("test-backend").Version("1.2.3") + must(t, backend.Function("echo.value", func(params json.RawMessage, _ *lithe.Context) (any, error) { + return params, nil + })) + return backend +} + +func TestNegotiatesVersionZeroAndListsTheFunctions(t *testing.T) { + host := startHost(t, echoBackend(t)) + eq(t, host.initialize([]any{0}), `{ + "capabilities": {"experimental": { + "litheLogging": {"version": 0}, + "litheFunctions": {"version": 0, "functions": [{"id": "echo.value"}]} + }}, + "serverInfo": {"name": "test-backend", "version": "1.2.3"} + }`) + host.invoke(1, "echo.value", j(t, `{"a": 1}`)) + answer, _ := host.answer(1) + eq(t, answer["result"], `{"a": 1}`) + if code := host.close(); code != 1 { + t.Errorf("exit code = %d", code) + } +} + +func TestAHostWithoutPluginFunctionsGetsNoFunctions(t *testing.T) { + host := startHost(t, echoBackend(t)) + eq(t, at(host.initialize(nil), "capabilities"), `{"experimental": {"litheLogging": {"version": 0}}}`) + host.invoke(1, "echo.value", map[string]any{}) + answer, _ := host.answer(1) + eq(t, at(answer, "error", "code"), `-32602`) + host.close() +} + +func TestFollowsTheLSPLifecycle(t *testing.T) { + host := startHost(t, echoBackend(t)) + host.invoke(1, "echo.value", map[string]any{}) + answer, _ := host.answer(1) + eq(t, at(answer, "error", "code"), `-32002`) + host.sendRaw("Content-Length: 3\r\n\r\nnot") + malformed := host.next() + if id, present := malformed["id"]; !present || id != nil { + t.Errorf("malformed answer id = %v, %t", id, present) + } + eq(t, at(malformed, "error", "code"), `-32700`) + host.send([]any{1, 2}) + eq(t, at(host.next(), "error", "code"), `-32600`) + + host.initialize([]any{0}) + host.request(2, "initialize", map[string]any{}) + answer, _ = host.answer(2) + eq(t, at(answer, "error", "code"), `-32600`) + host.request(3, "textDocument/hover", map[string]any{}) + answer, _ = host.answer(3) + eq(t, at(answer, "error", "code"), `-32601`) + host.request(4, "shutdown", nil) + answer, _ = host.answer(4) + eq(t, answer, `{"jsonrpc": "2.0", "id": 4, "result": null}`) + host.invoke(5, "echo.value", map[string]any{}) + answer, _ = host.answer(5) + eq(t, at(answer, "error", "code"), `-32600`) + host.notify("exit", nil) + if code := host.exitCode(); code != 0 { + t.Errorf("exit code = %d", code) + } +} + +func TestExitWithoutShutdownAndABrokenFrameEndWithAFailure(t *testing.T) { + host := startHost(t, echoBackend(t)) + host.notify("exit", nil) + if code := host.exitCode(); code != 1 { + t.Errorf("exit without shutdown = %d", code) + } + host = startHost(t, echoBackend(t)) + host.sendRaw("Content-Length: nope\r\n\r\n") + if code := host.exitCode(); code != 1 { + t.Errorf("broken frame = %d", code) + } +} + +func TestMapsResultsFailuresAndPanics(t *testing.T) { + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("work.run", func(params json.RawMessage, call *lithe.Context) (any, error) { + call.ProgressPercent("Halfway", 150) + switch decode(params)["mode"] { + case "plugin": + return nil, lithe.NewPluginError("work.failed", "The work failed.") + case "internal": + return nil, errors.New("/private/path: denied") + case "panic": + panic("secret detail") + case "large": + return strings.Repeat("x", 1<<20), nil + } + return map[string]any{"done": true}, nil + })) + host := startHost(t, backend) + host.initialize([]any{0}) + + host.invoke(1, "work.run", map[string]any{}) + answer, before := host.answer(1) + eq(t, answer["result"], `{"done": true}`) + if len(before) != 2 { + t.Fatalf("frames before the answer: %s", encode(t, before)) + } + eq(t, before[0], `{ + "jsonrpc": "2.0", "method": "lithe/function/progress", + "params": {"operationID": "op-1", "message": "Halfway", "percentage": 100} + }`) + eq(t, before[1]["method"], `"lithe/log"`) + eq(t, at(before[1], "params", "kind"), `"operationFinished"`) + eq(t, at(before[1], "params", "operationId"), `"op-1"`) + + host.invoke(2, "work.run", map[string]any{"mode": "plugin"}) + answer, _ = host.answer(2) + eq(t, answer["error"], `{"code": -32000, "message": "The work failed.", "data": {"code": "work.failed"}}`) + for id, mode := range map[int]string{3: "internal", 4: "panic", 5: "large"} { + host.invoke(id, "work.run", map[string]any{"mode": mode}) + answer, _ := host.answer(id) + if !strings.Contains(encode(t, answer["error"]), "The plugin backend failed unexpectedly.") { + t.Errorf("%s: %s", mode, encode(t, answer)) + } + eq(t, answer["error"], `{"code": -32603, "message": "The plugin backend failed unexpectedly."}`) + } + // The session survives a panicking call. + host.invoke(6, "work.run", map[string]any{}) + answer, _ = host.answer(6) + eq(t, answer["result"], `{"done": true}`) + host.close() +} + +func TestCancelRequestCancelsTheRunningCall(t *testing.T) { + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("work.wait", func(_ json.RawMessage, call *lithe.Context) (any, error) { + call.Progress("Waiting") + if call.Cancellation().WaitTimeout(30 * time.Second) { + if err := call.CheckCancelled(); err != nil { + return nil, err + } + } + return "not cancelled", nil + })) + host := startHost(t, backend) + host.initialize([]any{0}) + host.invoke(7, "work.wait", map[string]any{}) + eq(t, host.next()["method"], `"lithe/function/progress"`) + host.notify("$/cancelRequest", map[string]any{"id": 7}) + answer, _ := host.answer(7) + eq(t, answer["error"], `{"code": -32800, "message": "The request was cancelled."}`) + host.close() +} + +func TestAHandlersContextEndsWithTheCall(t *testing.T) { + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("work.wait", func(_ json.RawMessage, call *lithe.Context) (any, error) { + call.Progress("Waiting") + select { + case <-call.Cancellation().Context().Done(): + return nil, lithe.ErrCancelled + case <-time.After(30 * time.Second): + return "not cancelled", nil + } + })) + host := startHost(t, backend) + host.initialize([]any{0}) + host.invoke(1, "work.wait", map[string]any{}) + eq(t, host.next()["method"], `"lithe/function/progress"`) + host.notify("$/cancelRequest", map[string]any{"id": 1}) + answer, _ := host.answer(1) + eq(t, at(answer, "error", "code"), `-32800`) + host.close() +} + +func TestShutdownCancelsRunningCalls(t *testing.T) { + backend := lithe.NewBackend("test-backend") + hook := make(chan string, 1) + must(t, backend.Function("work.wait", func(_ json.RawMessage, call *lithe.Context) (any, error) { + call.Progress("Waiting") + call.Cancellation().WaitTimeout(30 * time.Second) + return nil, call.CheckCancelled() + })) + backend.OnShutdown(func() { hook <- "shutdown hook" }) + host := startHost(t, backend) + host.initialize([]any{0}) + host.invoke(1, "work.wait", map[string]any{}) + eq(t, host.next()["method"], `"lithe/function/progress"`) + host.request(2, "shutdown", nil) + answers := []map[string]any{host.next(), host.next()} + sort.Slice(answers, func(a, b int) bool { + return answers[a]["id"].(float64) < answers[b]["id"].(float64) + }) + eq(t, at(answers[0], "error", "code"), `-32800`) + if result, present := answers[1]["result"]; !present || result != nil { + t.Errorf("shutdown answer = %s", encode(t, answers[1])) + } + if got := within(t, hook); got != "shutdown hook" { + t.Errorf("hook = %s", got) + } + host.close() +} + +// credentialsBackend has a function that stores, reads, and deletes a +// credential. +func credentialsBackend(t *testing.T) *lithe.Backend { + t.Helper() + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("secret.roundTrip", func(params json.RawMessage, call *lithe.Context) (any, error) { + credentials := call.Credentials() + key, _ := decode(params)["key"].(string) + if err := credentials.Set(key, "s3cr3t"); err != nil { + return nil, lithe.NewPluginError("test.credentials", code(err)) + } + stored, _, err := credentials.Get(key) + if err != nil { + return nil, err + } + if err := credentials.Delete(key); err != nil { + return nil, err + } + return map[string]any{"stored": stored}, nil + })) + return backend +} + +func TestCredentialsAreHostRequests(t *testing.T) { + host := startHost(t, credentialsBackend(t)) + host.initialize([]any{0}) + host.invoke(1, "secret.roundTrip", map[string]any{"key": "db:main"}) + set := host.next() + eq(t, set["method"], `"lithe/host/credentials/set"`) + eq(t, set["params"], `{"key": "db:main", "secret": "s3cr3t"}`) + host.reply(set, nil) + get := host.next() + eq(t, get["method"], `"lithe/host/credentials/get"`) + eq(t, get["params"], `{"key": "db:main"}`) + host.reply(get, map[string]any{"secret": "s3cr3t"}) + remove := host.next() + eq(t, remove["method"], `"lithe/host/credentials/delete"`) + host.reply(remove, nil) + answer, _ := host.answer(1) + eq(t, answer["result"], `{"stored": "s3cr3t"}`) + + // Core's refusal reaches the handler with its code. + host.invoke(2, "secret.roundTrip", map[string]any{"key": "db:main"}) + set = host.next() + host.refuse(set, j(t, `{"code": -32601, "message": "Not granted.", "data": {"code": "plugin.host.permissionDenied"}}`)) + answer, _ = host.answer(2) + eq(t, at(answer, "error", "message"), `"plugin.host.permissionDenied"`) + + // A malformed key never reaches the host. + host.invoke(3, "secret.roundTrip", map[string]any{"key": "has space"}) + answer, _ = host.answer(3) + eq(t, at(answer, "error", "message"), `"sdk.credentials.invalidKey"`) + host.close() +} + +func TestCancellingACallEndsItsWaitingHostRequest(t *testing.T) { + host := startHost(t, credentialsBackend(t)) + host.initialize([]any{0}) + host.invoke(1, "secret.roundTrip", map[string]any{"key": "db:main"}) + eq(t, host.next()["method"], `"lithe/host/credentials/set"`) + host.notify("$/cancelRequest", map[string]any{"id": 1}) + answer, _ := host.answer(1) + eq(t, at(answer, "error", "code"), `-32800`) + host.close() +} + +func TestFunctionsAreRegisteredAndWithdrawnAtRuntime(t *testing.T) { + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("extra.add", func(_ json.RawMessage, call *lithe.Context) (any, error) { + err := call.Backend().RegisterFunction("extra.value", func(json.RawMessage, *lithe.Context) (any, error) { + return 42, nil + }) + if err != nil { + return nil, err + } + return call.Backend().FunctionIDs(), nil + })) + must(t, backend.Function("extra.remove", func(_ json.RawMessage, call *lithe.Context) (any, error) { + return nil, call.Backend().UnregisterFunction("extra.value") + })) + handle := backend.Handle() + host := startHost(t, backend) + host.initialize([]any{0}) + + host.invoke(1, "extra.add", map[string]any{}) + register := host.next() + eq(t, register["method"], `"lithe/function/register"`) + eq(t, register["params"], `{"functions": [{"id": "extra.value"}]}`) + host.reply(register, nil) + answer, _ := host.answer(1) + eq(t, answer["result"], `["extra.add", "extra.remove", "extra.value"]`) + host.invoke(2, "extra.value", map[string]any{}) + answer, _ = host.answer(2) + eq(t, answer["result"], `42`) + + host.invoke(3, "extra.remove", map[string]any{}) + unregister := host.next() + eq(t, unregister["method"], `"lithe/function/unregister"`) + eq(t, unregister["params"], `{"ids": ["extra.value"]}`) + host.reply(unregister, nil) + answer, _ = host.answer(3) + if result, present := answer["result"]; !present || result != nil { + t.Errorf("unregister answer = %s", encode(t, answer)) + } + host.invoke(4, "extra.value", map[string]any{}) + answer, _ = host.answer(4) + eq(t, at(answer, "error", "code"), `-32602`) + + // A refused registration leaves the function out. + refused := make(chan error, 1) + go func() { + refused <- handle.RegisterFunction("extra.refused", func(json.RawMessage, *lithe.Context) (any, error) { + return nil, nil + }) + }() + register = host.next() + host.refuse(register, j(t, `{"code": -32602, "message": "No.", "data": {"code": "plugin.function.invalidRegistration"}}`)) + if err := within(t, refused); code(err) != "plugin.function.invalidRegistration" { + t.Errorf("refused registration = %v", err) + } + if slices.Contains(handle.FunctionIDs(), "extra.refused") { + t.Error("a refused function is served") + } + host.close() + // After the session, requests fail instead of waiting. + late := handle.RegisterFunction("extra.late", func(json.RawMessage, *lithe.Context) (any, error) { return nil, nil }) + if code(late) != lithe.CodeSessionClosed { + t.Errorf("late registration = %v", late) + } +} + +func TestFunctionDeclarationsAreChecked(t *testing.T) { + backend := lithe.NewBackend("test-backend") + nothing := func(json.RawMessage, *lithe.Context) (any, error) { return nil, nil } + if err := backend.Function("Bad", nothing); code(err) != "sdk.function.invalidID" { + t.Errorf("invalid ID = %v", err) + } + must(t, backend.Function("a.b", nothing)) + if err := backend.Function("a.b", nothing); code(err) != "sdk.function.duplicate" { + t.Errorf("duplicate = %v", err) + } + if err := backend.Handle().RegisterFunction("c.d", nothing); code(err) != "sdk.functions.unavailable" { + t.Errorf("register before the session = %v", err) + } +} + +func TestInitializeHooksSeeTheRootAndAddFunctions(t *testing.T) { + backend := lithe.NewBackend("test-backend") + roots := make(chan string, 1) + backend.OnInitialize(func(initialize *lithe.Initialize) error { + root, _ := initialize.RootPath() + roots <- root + return initialize.Function("late.added", func(json.RawMessage, *lithe.Context) (any, error) { + return "added", nil + }) + }) + host := startHost(t, backend) + result := host.initialize([]any{0}) + eq(t, at(result, "capabilities", "experimental", "litheFunctions", "functions"), `[{"id": "late.added"}]`) + if root := within(t, roots); root != "/tmp/state" { + t.Errorf("root = %q", root) + } + + refusing := lithe.NewBackend("test-backend") + refusing.OnInitialize(func(*lithe.Initialize) error { + return lithe.NewPluginError("test.notReady", "Not ready.") + }) + host = startHost(t, refusing) + host.request(0, "initialize", j(t, `{"capabilities": {"experimental": {"litheLogging": {"versions": [0]}}}}`)) + answer, _ := host.answer(0) + eq(t, at(answer, "error", "data", "code"), `"test.notReady"`) + host.close() +} + +func TestTypedDiagnosticsPreserveOperationAndSuppressOnlySuccess(t *testing.T) { + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("work.inspect", func(params json.RawMessage, call *lithe.Context) (any, error) { + if err := call.Diagnostics().Degraded("work.inspect", "cache_unavailable", 2); err != nil { + return nil, err + } + if err := call.Diagnostics().Recovered("work.inspect", "cache_restored"); err != nil { + return nil, err + } + if decode(params)["fail"] == true { + return nil, lithe.NewPluginError("work.failed", "private explanation") + } + return nil, nil + })) + must(t, backend.SuppressSuccessDiagnostics("work.inspect")) + host := startHost(t, backend) + host.initialize([]any{0}) + host.invoke(1, "work.inspect", map[string]any{"fail": false}) + _, success := host.answer(1) + if len(success) != 2 { + t.Fatalf("success facts: %s", encode(t, success)) + } + eq(t, at(success[0], "params", "operationId"), `"op-1"`) + eq(t, at(success[0], "params", "kind"), `"degraded"`) + eq(t, at(success[0], "params", "count"), `2`) + eq(t, at(success[1], "params", "kind"), `"recovered"`) + host.invoke(2, "work.inspect", map[string]any{"fail": true}) + _, failure := host.answer(2) + if len(failure) != 3 { + t.Fatalf("failure facts: %s", encode(t, failure)) + } + eq(t, at(failure[2], "params", "kind"), `"operationFailed"`) + eq(t, at(failure[2], "params", "code"), `"work.failed"`) + if _, ok := at(failure[2], "params", "durationMs").(float64); !ok { + t.Errorf("no duration: %s", encode(t, failure[2])) + } + if strings.Contains(encode(t, failure[2]), "private explanation") { + t.Errorf("the failure fact holds the message: %s", encode(t, failure[2])) + } + host.close() +} + +func TestPerCallSuppressionKeepsUserSuccessAndFailures(t *testing.T) { + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("database.call", func(params json.RawMessage, call *lithe.Context) (any, error) { + object := decode(params) + if object["readOnly"] == true { + call.SuppressSuccessDiagnostics() + } + if object["fail"] == true { + return nil, errors.New("private failure") + } + return nil, nil + })) + host := startHost(t, backend) + host.initialize([]any{0}) + host.invoke(1, "database.call", map[string]any{"readOnly": true}) + if _, before := host.answer(1); len(before) != 0 { + t.Errorf("a suppressed success logged: %s", encode(t, before)) + } + host.invoke(2, "database.call", map[string]any{}) + _, before := host.answer(2) + eq(t, at(before, 0, "params", "kind"), `"operationFinished"`) + host.invoke(3, "database.call", map[string]any{"readOnly": true, "fail": true}) + _, before = host.answer(3) + eq(t, at(before, 0, "params", "kind"), `"operationFailed"`) + eq(t, at(before, 0, "params", "code"), `"internal_error"`) + host.close() +} + +func TestInitializeDiagnosticsWaitForTheCapabilityAnswerAndStayBounded(t *testing.T) { + backend := lithe.NewBackend("test-backend") + diagnostics := backend.Handle().Diagnostics() + backend.OnInitialize(func(*lithe.Initialize) error { + for count := range uint64(10) { + if err := diagnostics.Degraded("initialize", "snapshot_unavailable", count); err != nil { + return err + } + } + return nil + }) + host := startHost(t, backend) + host.request(0, "initialize", j(t, `{"capabilities": {"experimental": {"litheLogging": {"versions": [0]}}}}`)) + answer := host.next() + eq(t, answer["id"], `0`) + eq(t, at(answer, "result", "capabilities", "experimental", "litheLogging", "version"), `0`) + for count := range 8 { + fact := host.next() + eq(t, fact["method"], `"lithe/log"`) + eq(t, at(fact, "params", "count"), encode(t, count)) + } + host.request(1, "shutdown", nil) + // The initialization buffer is bounded to eight facts. + eq(t, host.next()["id"], `1`) + host.close() +} + +func TestDiagnosticsUseTheOriginalRPCIDWhenTheOperationIDIsAbsent(t *testing.T) { + backend := lithe.NewBackend("test-backend") + must(t, backend.Function("work.inspect", func(_ json.RawMessage, call *lithe.Context) (any, error) { + return nil, call.Diagnostics().Degraded("work.inspect", "cache_unavailable") + })) + host := startHost(t, backend) + host.initialize([]any{0}) + host.request(42, "lithe/function/invoke", j(t, `{"functionID": "work.inspect"}`)) + _, facts := host.answer(42) + if len(facts) != 2 { + t.Fatalf("facts: %s", encode(t, facts)) + } + for _, fact := range facts { + eq(t, at(fact, "params", "operationId"), `"42"`) + } + host.request("rpc-second", "lithe/function/invoke", j(t, `{"functionID": "work.inspect", "operationID": "wire-original"}`)) + _, facts = host.answer("rpc-second") + for _, fact := range facts { + eq(t, at(fact, "params", "operationId"), `"wire-original"`) + } + host.close() +} + +func TestADiagnosticNeedsARegisteredOperationAndAControlledCode(t *testing.T) { + diagnostics := lithe.NewBackend("test-backend").Handle().Diagnostics() + if err := diagnostics.Degraded("not.registered", "code"); code(err) != "sdk.logging.invalidOperation" { + t.Errorf("unregistered operation = %v", err) + } + if err := diagnostics.Degraded("initialize", "has space"); code(err) != "sdk.logging.invalidCode" { + t.Errorf("free-form code = %v", err) + } + if err := diagnostics.Degraded("initialize", "ok", 1<<60); code(err) != "sdk.logging.invalidCount" { + t.Errorf("unsafe count = %v", err) + } +} diff --git a/shared/plugins/sdk/go/lithe/stdio_dup2.go b/shared/plugins/sdk/go/lithe/stdio_dup2.go new file mode 100644 index 00000000..07dec513 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/stdio_dup2.go @@ -0,0 +1,30 @@ +//go:build darwin || dragonfly || freebsd || netbsd || openbsd + +package lithe + +import ( + "io" + "os" + "syscall" +) + +// protocolOutput is the stream the protocol is written to: a duplicate of +// the original stdout descriptor, with descriptor 1 pointed at stderr, so +// output printed by plugin code, its dependencies or the processes it starts +// cannot corrupt the protocol. The duplicate is close-on-exec, so child +// processes do not hold the protocol pipe open. +func protocolOutput() io.Writer { + syscall.ForkLock.RLock() + protocol, err := syscall.Dup(1) + if err == nil { + syscall.CloseOnExec(protocol) + } + syscall.ForkLock.RUnlock() + if err != nil { + return os.Stdout + } + if err := syscall.Dup2(2, 1); err != nil { + os.Exit(1) + } + return os.NewFile(uintptr(protocol), "lithe-protocol") +} diff --git a/shared/plugins/sdk/go/lithe/stdio_linux.go b/shared/plugins/sdk/go/lithe/stdio_linux.go new file mode 100644 index 00000000..90d8b492 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/stdio_linux.go @@ -0,0 +1,31 @@ +//go:build linux + +package lithe + +import ( + "io" + "os" + "syscall" +) + +// protocolOutput is the stream the protocol is written to: a duplicate of +// the original stdout descriptor, with descriptor 1 pointed at stderr, so +// output printed by plugin code, its dependencies or the processes it starts +// cannot corrupt the protocol. The duplicate is close-on-exec, so child +// processes do not hold the protocol pipe open. +func protocolOutput() io.Writer { + syscall.ForkLock.RLock() + protocol, err := syscall.Dup(1) + if err == nil { + syscall.CloseOnExec(protocol) + } + syscall.ForkLock.RUnlock() + if err != nil { + return os.Stdout + } + // linux/arm64 has no dup2; dup3 with no flags is the same. + if err := syscall.Dup3(2, 1, 0); err != nil { + os.Exit(1) + } + return os.NewFile(uintptr(protocol), "lithe-protocol") +} diff --git a/shared/plugins/sdk/go/lithe/stdio_other.go b/shared/plugins/sdk/go/lithe/stdio_other.go new file mode 100644 index 00000000..4c5d3cea --- /dev/null +++ b/shared/plugins/sdk/go/lithe/stdio_other.go @@ -0,0 +1,13 @@ +//go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd + +package lithe + +import ( + "io" + "os" +) + +// protocolOutput is the stream the protocol is written to: stdout itself. +// Here descriptor 1 cannot be redirected, so plugin code must not print to +// stdout; write to stderr or record diagnostics instead. +func protocolOutput() io.Writer { return os.Stdout } diff --git a/shared/plugins/sdk/go/lithe/view.go b/shared/plugins/sdk/go/lithe/view.go new file mode 100644 index 00000000..0e62fbf4 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/view.go @@ -0,0 +1,338 @@ +package lithe + +import ( + "encoding/json" + "maps" + "strconv" +) + +// Plugin views: the event a view function receives and the result it +// returns. A tool window or settings region names a view function in +// view.function (contract v1, "Plugin views"). Declare it with +// [Backend.View]: the SDK reads the params into a [ViewEvent] and answers +// the handler's [ViewResult]. View and canvas nodes are JSON values -- maps, +// structs, or json.RawMessage -- shaped as plugin-ui.schema.json describes; +// Core checks every result before the host draws it. + +const codeInvalidViewEvent = "sdk.view.invalidEvent" + +// ViewEventKind is why the host called the view function. +type ViewEventKind string + +const ( + // ViewOpen: the view became visible; answer a whole view. + ViewOpen ViewEventKind = "open" + // ViewClose: the view went away; the result is ignored. + ViewClose ViewEventKind = "close" + ViewClick ViewEventKind = "click" + ViewChange ViewEventKind = "change" + ViewSelect ViewEventKind = "select" + ViewActivate ViewEventKind = "activate" + ViewViewport ViewEventKind = "viewport" + // ViewResize: the view's width stopped changing, for a view with a + // canvas whose on lists resize; ViewEvent.Width is the new width. + ViewResize ViewEventKind = "resize" + // ViewSettings: the effective or draft setting values changed. + ViewSettings ViewEventKind = "settings" +) + +func parseViewEventKind(name string) (ViewEventKind, bool) { + switch kind := ViewEventKind(name); kind { + case ViewOpen, ViewClose, ViewClick, ViewChange, ViewSelect, ViewActivate, ViewViewport, ViewResize, ViewSettings: + return kind, true + } + return "", false +} + +// SurfaceKind is the kind of declaration being drawn. +type SurfaceKind string + +const ( + SurfaceToolWindow SurfaceKind = "toolWindow" + SurfaceSettingRegion SurfaceKind = "settingRegion" +) + +// ViewSurface is the declaration being drawn: a tool window or a settings +// region, by its ID. +type ViewSurface struct { + Kind SurfaceKind + ID string +} + +// Viewport is the visible part of a canvas, in view-box coordinates. +type Viewport struct { + X, Y, Width, Height float64 +} + +// ViewEvent is the params of one call to a view function. An optional +// string field is "" when the host did not send it. +type ViewEvent struct { + Kind ViewEventKind + // Instance is host-chosen; each ViewOpen starts a new instance. + Instance string + Surface ViewSurface + // Language is the interface language tag, such as en or zh-Hans; + // return view text in it. + Language string + // Effective holds the saved setting values in force, by setting ID. + Effective map[string]any + // Draft holds values changed in the open settings window but not + // applied; empty in a tool window. + Draft map[string]any + // Node is the node acted on: the group inside a canvas, the tree for an + // item. + Node string + // Canvas is the canvas ID of a click inside a canvas and of a viewport + // event. + Canvas string + // Value is a change's value: a string, a bool for a toggle, or the bound + // setting's new draft value (a json.Number for a number); nil when + // absent. + Value any + // Setting is the setting ID of a change of a control bound to one. + Setting string + // Item is the tree item ID of a select or activate event. + Item string + Viewport *Viewport + // Width is the width in points the host lays the view out in, on every + // event from a host that reports it. List resize in a canvas's on only + // when it is present: a host without it may refuse the canvas. + Width *float64 +} + +// ParseViewEvent reads the params the host sent; it fails with +// sdk.view.invalidEvent when a required field is missing or a field has the +// wrong type. An optional field that is null counts as absent. +func ParseViewEvent(params json.RawMessage) (*ViewEvent, error) { + value, err := decodeJSON(params) + if err != nil { + return nil, invalidViewEvent() + } + return parseViewEvent(value) +} + +func invalidViewEvent() *SdkError { + return newSdkError(codeInvalidViewEvent, "Invalid view event.") +} + +// optionalString reads fields[key]: absent or null is "", a string is +// itself, and anything else is invalid. +func optionalString(fields map[string]any, key string) (string, bool, error) { + switch value := fields[key].(type) { + case nil: + return "", false, nil + case string: + return value, true, nil + default: + return "", false, invalidViewEvent() + } +} + +func number(value any) (float64, bool) { + text, ok := value.(json.Number) + if !ok { + return 0, false + } + parsed, err := strconv.ParseFloat(string(text), 64) + return parsed, err == nil +} + +func parseViewEvent(params any) (*ViewEvent, error) { + object, ok := params.(map[string]any) + if !ok { + return nil, invalidViewEvent() + } + name, _ := object["event"].(string) + kind, ok := parseViewEventKind(name) + if !ok { + return nil, invalidViewEvent() + } + surfaceFields, ok := object["surface"].(map[string]any) + if !ok { + return nil, invalidViewEvent() + } + toolWindow, isToolWindow, err := optionalString(surfaceFields, "toolWindowID") + if err != nil { + return nil, err + } + region, isRegion, err := optionalString(surfaceFields, "settingRegionID") + if err != nil { + return nil, err + } + var surface ViewSurface + switch { + case isToolWindow && !isRegion: + surface = ViewSurface{SurfaceToolWindow, toolWindow} + case isRegion && !isToolWindow: + surface = ViewSurface{SurfaceSettingRegion, region} + default: + return nil, invalidViewEvent() + } + settings, ok := object["settings"].(map[string]any) + if !ok { + return nil, invalidViewEvent() + } + effective, ok := settings["effective"].(map[string]any) + if !ok { + return nil, invalidViewEvent() + } + draft, ok := settings["draft"].(map[string]any) + if !ok { + return nil, invalidViewEvent() + } + event := &ViewEvent{Kind: kind, Surface: surface, Effective: maps.Clone(effective), Draft: maps.Clone(draft)} + if event.Instance, ok = object["instance"].(string); !ok { + return nil, invalidViewEvent() + } + if event.Language, ok = object["language"].(string); !ok { + return nil, invalidViewEvent() + } + switch viewport := object["viewport"].(type) { + case nil: + case map[string]any: + var fields [4]float64 + for i, key := range []string{"x", "y", "width", "height"} { + if fields[i], ok = number(viewport[key]); !ok { + return nil, invalidViewEvent() + } + } + event.Viewport = &Viewport{fields[0], fields[1], fields[2], fields[3]} + default: + return nil, invalidViewEvent() + } + if width, present := object["width"]; present && width != nil { + parsed, ok := number(width) + if !ok { + return nil, invalidViewEvent() + } + event.Width = &parsed + } + switch value := object["value"].(type) { + case nil: + case string, bool, json.Number: + event.Value = value + default: + return nil, invalidViewEvent() + } + for key, target := range map[string]*string{"node": &event.Node, "canvas": &event.Canvas, "setting": &event.Setting, "item": &event.Item} { + if *target, _, err = optionalString(object, key); err != nil { + return nil, err + } + } + return event, nil +} + +// ViewResult is what a view function answers. The first result after +// ViewOpen is a whole view. The zero value is [Unchanged]. +type ViewResult struct { + kind resultKind + nodes []any + patches []Patch +} + +type resultKind int + +const ( + resultUnchanged resultKind = iota + resultView + resultPatches +) + +// View answers the whole view: its nodes, top to bottom. +func View(nodes ...any) ViewResult { + return ViewResult{kind: resultView, nodes: nodes} +} + +// Patches answers edits to the view the host is drawing, applied in order. +func Patches(patches ...Patch) ViewResult { + return ViewResult{kind: resultPatches, patches: patches} +} + +// Unchanged answers that nothing changed. +func Unchanged() ViewResult { return ViewResult{} } + +// MarshalJSON writes {"view": [...]}, {"patches": [...]}, or {}. +func (r ViewResult) MarshalJSON() ([]byte, error) { + switch r.kind { + case resultView: + nodes := r.nodes + if nodes == nil { + nodes = []any{} + } + return encodeJSON(map[string]any{"view": nodes}) + case resultPatches: + patches := r.patches + if patches == nil { + patches = []Patch{} + } + return encodeJSON(map[string]any{"patches": patches}) + default: + return []byte("{}"), nil + } +} + +// Patch is one edit, addressed by node ID within the host controls, or +// within one canvas scene ([Patch.InCanvas]) or one tree's items +// ([Patch.InTree]). Each method returns a new patch. +type Patch struct { + fields map[string]any +} + +func newPatch(op, id string, hasID bool) Patch { + fields := map[string]any{"op": op} + if hasID { + fields["id"] = id + } + return Patch{fields} +} + +func (p Patch) with(key string, value any) Patch { + fields := maps.Clone(p.fields) + if fields == nil { + fields = map[string]any{} + } + fields[key] = value + return Patch{fields} +} + +// PatchSet merges fields, a JSON object, into the node; a null field +// removes it. +func PatchSet(id string, fields any) Patch { + return newPatch("set", id, true).with("fields", fields) +} + +// PatchReplace swaps the node, with its subtree, for node. +func PatchReplace(id string, node any) Patch { + return newPatch("replace", id, true).with("node", node) +} + +// PatchRemove deletes the node and its subtree. +func PatchRemove(id string) Patch { + return newPatch("remove", id, true) +} + +// PatchInsert adds node at the end of the top level; see [Patch.Under] and +// [Patch.At]. +func PatchInsert(node any) Patch { + return newPatch("insert", "", false).with("node", node) +} + +// Under makes an insert go into the children of parent. +func (p Patch) Under(parent string) Patch { return p.with("parent", parent) } + +// At makes an insert go at index instead of the end. +func (p Patch) At(index int) Patch { return p.with("index", index) } + +// InCanvas addresses the nodes of canvas canvas. +func (p Patch) InCanvas(canvas string) Patch { return p.with("canvas", canvas) } + +// InTree addresses the items of tree tree. +func (p Patch) InTree(tree string) Patch { return p.with("tree", tree) } + +// MarshalJSON writes the patch object. +func (p Patch) MarshalJSON() ([]byte, error) { + if p.fields == nil { + return []byte("{}"), nil + } + return encodeJSON(p.fields) +} diff --git a/shared/plugins/sdk/go/lithe/view_session_test.go b/shared/plugins/sdk/go/lithe/view_session_test.go new file mode 100644 index 00000000..e5542d8e --- /dev/null +++ b/shared/plugins/sdk/go/lithe/view_session_test.go @@ -0,0 +1,64 @@ +package lithe_test + +// A view function is a plugin function whose params are a view event. + +import ( + "testing" + + "github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go/lithe" +) + +func viewParams(event string) map[string]any { + return map[string]any{ + "event": event, + "instance": "i1", + "surface": map[string]any{"toolWindowID": "dev.example.explorer"}, + "language": "zh-Hans", + "settings": map[string]any{"effective": map[string]any{}, "draft": map[string]any{}}, + "node": "refresh", + } +} + +func TestAViewFunctionAnswersViewsPatchesAndNothing(t *testing.T) { + surfaces := make(chan lithe.ViewSurface, 4) + backend := lithe.NewBackend("test-backend") + must(t, backend.View("explorer.draw", func(event *lithe.ViewEvent, _ *lithe.Context) (lithe.ViewResult, error) { + surfaces <- event.Surface + switch event.Kind { + case lithe.ViewOpen: + return lithe.View(map[string]any{"type": "label", "text": event.Language}), nil + case lithe.ViewClick: + return lithe.Patches(lithe.PatchSet(event.Node, map[string]any{"enabled": false})), nil + } + return lithe.Unchanged(), nil + })) + host := startHost(t, backend) + eq(t, at(host.initialize([]any{0}), "capabilities", "experimental", "litheFunctions", "functions"), `[{"id": "explorer.draw"}]`) + + host.invoke(1, "explorer.draw", viewParams("open")) + answer, _ := host.answer(1) + eq(t, answer["result"], `{"view": [{"type": "label", "text": "zh-Hans"}]}`) + host.invoke(2, "explorer.draw", viewParams("click")) + answer, _ = host.answer(2) + eq(t, answer["result"], `{"patches": [{"op": "set", "id": "refresh", "fields": {"enabled": false}}]}`) + host.invoke(3, "explorer.draw", viewParams("close")) + answer, _ = host.answer(3) + eq(t, answer["result"], `{}`) + for range 3 { + if surface := within(t, surfaces); surface != (lithe.ViewSurface{Kind: lithe.SurfaceToolWindow, ID: "dev.example.explorer"}) { + t.Errorf("surface = %+v", surface) + } + } + // Params that are not a view event never reach the handler. + host.invoke(4, "explorer.draw", map[string]any{"event": "open"}) + answer, _ = host.answer(4) + eq(t, at(answer, "error", "code"), `-32603`) + if exit := host.close(); exit != 1 { + t.Errorf("exit code = %d", exit) + } + select { + case surface := <-surfaces: + t.Errorf("an invalid event reached the handler: %+v", surface) + default: + } +} diff --git a/shared/plugins/sdk/go/lithe/view_test.go b/shared/plugins/sdk/go/lithe/view_test.go new file mode 100644 index 00000000..1fd46e2a --- /dev/null +++ b/shared/plugins/sdk/go/lithe/view_test.go @@ -0,0 +1,124 @@ +package lithe + +import ( + "encoding/json" + "errors" + "testing" +) + +// viewEvent is a change event with extra fields merged over it. +func viewEvent(t *testing.T, extra string) json.RawMessage { + t.Helper() + params := mustValue(t, `{ + "event": "change", + "instance": "i1", + "surface": {"settingRegionID": "otp"}, + "language": "zh-Hans", + "settings": {"effective": {"otpRelease": "26"}, "draft": {"otpRelease": "27"}} + }`).(map[string]any) + for key, value := range mustValue(t, extra).(map[string]any) { + params[key] = value + } + return raw(params) +} + +func TestParseViewEventReadsEveryFieldTheHostSends(t *testing.T) { + parsed, err := ParseViewEvent(viewEvent(t, `{ + "node": "otp", "setting": "otpRelease", "value": "27", + "viewport": {"x": 0, "y": 10.5, "width": 1200, "height": 640}, + "width": 612 + }`)) + if err != nil { + t.Fatal(err) + } + if parsed.Kind != ViewChange || parsed.Instance != "i1" || parsed.Language != "zh-Hans" { + t.Errorf("kind, instance, language = %s, %s, %s", parsed.Kind, parsed.Instance, parsed.Language) + } + if parsed.Surface != (ViewSurface{SurfaceSettingRegion, "otp"}) { + t.Errorf("surface = %+v", parsed.Surface) + } + if parsed.Draft["otpRelease"] != "27" || parsed.Effective["otpRelease"] != "26" { + t.Errorf("settings = %v, %v", parsed.Effective, parsed.Draft) + } + if parsed.Node != "otp" || parsed.Setting != "otpRelease" || parsed.Value != "27" || parsed.Item != "" { + t.Errorf("node, setting, value, item = %q, %q, %v, %q", parsed.Node, parsed.Setting, parsed.Value, parsed.Item) + } + if parsed.Viewport == nil || *parsed.Viewport != (Viewport{0, 10.5, 1200, 640}) { + t.Errorf("viewport = %+v", parsed.Viewport) + } + if parsed.Width == nil || *parsed.Width != 612 { + t.Errorf("width = %v", parsed.Width) + } + + // An optional field sent as null counts as absent. + absent, err := ParseViewEvent(viewEvent(t, `{"node": null, "value": null, "viewport": null, "width": null}`)) + if err != nil { + t.Fatal(err) + } + if absent.Node != "" || absent.Value != nil || absent.Viewport != nil || absent.Width != nil { + t.Errorf("absent = %+v", absent) + } + + resize, err := ParseViewEvent(viewEvent(t, `{"event": "resize", "width": 340}`)) + if err != nil { + t.Fatal(err) + } + if resize.Kind != ViewResize || resize.Width == nil || *resize.Width != 340 { + t.Errorf("resize = %s, %v", resize.Kind, resize.Width) + } + + toggle, err := ParseViewEvent(viewEvent(t, `{"surface": {"toolWindowID": "deps"}, "value": true}`)) + if err != nil { + t.Fatal(err) + } + if toggle.Surface != (ViewSurface{SurfaceToolWindow, "deps"}) || toggle.Value != true { + t.Errorf("toggle = %+v, %v", toggle.Surface, toggle.Value) + } +} + +func TestParseViewEventRefusesEventsWithoutTheirRequiredShape(t *testing.T) { + invalid := []json.RawMessage{ + json.RawMessage(`null`), + json.RawMessage(`not json`), + viewEvent(t, `{"event": "hover"}`), + viewEvent(t, `{"surface": {"toolWindowID": "a", "settingRegionID": "b"}}`), + viewEvent(t, `{"surface": {"toolWindowID": "a", "settingRegionID": 3}}`), + viewEvent(t, `{"surface": {}}`), + viewEvent(t, `{"settings": {"effective": {}}}`), + viewEvent(t, `{"node": 3}`), + viewEvent(t, `{"value": ["a"]}`), + viewEvent(t, `{"viewport": {"x": 0}}`), + viewEvent(t, `{"width": "wide"}`), + } + for _, params := range invalid { + _, err := ParseViewEvent(params) + var sdk *SdkError + if !errors.As(err, &sdk) || sdk.Code() != codeInvalidViewEvent { + t.Errorf("%s: %v", params, err) + } + } +} + +func TestViewResultsAndPatchesSerializeAsTheSchemaNamesThem(t *testing.T) { + assertJSON(t, Unchanged(), `{}`) + assertJSON(t, ViewResult{}, `{}`) + assertJSON(t, View(map[string]any{"type": "label", "text": "a"}), `{"view": [{"type": "label", "text": "a"}]}`) + assertJSON(t, View(), `{"view": []}`) + assertJSON(t, Patches(), `{"patches": []}`) + patches := Patches( + PatchSet("filter", map[string]any{"enabled": false}), + PatchRemove("guava").InCanvas("graph"), + PatchInsert(map[string]any{"id": "web", "label": "web"}).InTree("modules").Under("app").At(0), + PatchReplace("refresh", map[string]any{"type": "button", "id": "refresh", "text": "Stop"}), + ) + assertJSON(t, patches, `{"patches": [ + {"op": "set", "id": "filter", "fields": {"enabled": false}}, + {"op": "remove", "id": "guava", "canvas": "graph"}, + {"op": "insert", "node": {"id": "web", "label": "web"}, "tree": "modules", "parent": "app", "index": 0}, + {"op": "replace", "id": "refresh", "node": {"type": "button", "id": "refresh", "text": "Stop"}} + ]}`) + // Each method returns a new patch. + base := PatchRemove("a") + _ = base.InCanvas("graph") + assertJSON(t, base, `{"op": "remove", "id": "a"}`) +} diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 1efa0dc7..b84250d4 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -461,7 +461,7 @@ Run these from the root of this repository: ```bash mvn -B -ntp -f shared/plugins/sdk/java/pom.xml verify -# End to end: the sample backends of all three SDKs against this checkout's Core. +# End to end: the sample backends of all four SDKs against this checkout's Core. node shared/plugins/scripts/sdk-e2e.mjs ``` @@ -469,7 +469,7 @@ This builds the SDK and the sample for Java 8 with any newer JDK, then runs the JUnit tests. Add `-Djvm=/path/to/java8/bin/java` to run the tests on a Java 8 runtime, as CI does. -The end-to-end script needs Rust, Node.js 20.3 or newer, Java +The end-to-end script needs Rust, Node.js 20.3 or newer, Go 1.22 or newer, Java (`LITHE_PLUGIN_SDK_JAVA_RUNTIME` or `java` on `PATH`) and Maven; `LITHE_PLUGIN_SDK_JAVA_SAMPLE` and `LITHE_PLUGIN_SDK_JAVA_NATIVE_SAMPLE` name already built sample JARs. diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 9a5d65aa..fa41829c 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -528,11 +528,11 @@ node --test shared/plugins/sdk/node/test/*.test.mjs npm ci --prefix shared/plugins/sdk/node --ignore-scripts npm run --prefix shared/plugins/sdk/node test:types -# End to end: the sample backends of all three SDKs against this checkout's Core. +# End to end: the sample backends of all four SDKs against this checkout's Core. node shared/plugins/scripts/sdk-e2e.mjs ``` The tests use a bounded in-memory host (`test/harness.mjs`), which plugin authors can copy to test their own backends without starting Lithe. The -end-to-end script needs Rust, Node.js 20.3 or newer, Java +end-to-end script needs Rust, Node.js 20.3 or newer, Go 1.22 or newer, Java (`LITHE_PLUGIN_SDK_JAVA_RUNTIME` or `java` on `PATH`) and Maven. diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 582f083e..8f5291e7 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -492,6 +492,6 @@ The unit tests drive a session through in-process pipes with a scripted host; `plugin-sdk/tests/host_services.rs` checks the host services against the contract's fixture. The end-to-end check builds the sample, installs it as a package, and runs it through a real Core session of this checkout. It needs -Rust, Node.js 20.3 or newer, Java (`LITHE_PLUGIN_SDK_JAVA_RUNTIME` or `java` on -`PATH`) and Maven; `LITHE_PLUGIN_SDK_RUST_SAMPLE` names an already built +Rust, Node.js 20.3 or newer, Go 1.22 or newer, Java +(`LITHE_PLUGIN_SDK_JAVA_RUNTIME` or `java` on `PATH`) and Maven; `LITHE_PLUGIN_SDK_RUST_SAMPLE` names an already built `sample-backend`.