diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7745ef1..4d951b5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -68,6 +68,8 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: "3.12"
+ - name: Install pytest for live test-discovery and execution checks
+ run: python -m pip install --disable-pip-version-check pytest
- uses: actions/download-artifact@v4
with:
name: python-support-archives
diff --git a/README.md b/README.md
index 4d67ab0..07deecd 100644
--- a/README.md
+++ b/README.md
@@ -1,79 +1,81 @@
# Python Support for Lithe (`io.github.lithe-idea.python-support`)
-Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: 0`), bundling [Pyrefly](https://github.com/facebook/pyrefly) `1.4.1` for fast static type checking and LSP navigation, and [debugpy](https://github.com/microsoft/debugpy) `1.8.22` for source-level debugging.
+Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginAPIVersion: 0`), bundling [Pyrefly](https://github.com/facebook/pyrefly) `1.4.1` for fast static type checking and LSP navigation, [debugpy](https://github.com/microsoft/debugpy) `1.8.22` for source-level debugging, and a zero-compilation pure-Python (`python -I -B`) plugin backend and build provider.
-遵循 Lithe 声明式插件契约 v0,为 Lithe 桌面端(macOS / Windows / Linux)提供开箱即用的 Python 语言支持、`.venv` 虚拟环境与多来源解释器发现、项目模型静态分析、`pytest` 测试集成、`uv` / `conda` / `Ruff` 构建任务、源码级断点调试及新建项目向导。跨平台实现与验证记录详见 [docs/feature-matrix.md](docs/feature-matrix.md)。
+遵循 Lithe 插件契约 v1(`schemaVersion: 0`),为 Lithe 桌面端(macOS / Windows / Linux)提供开箱即用的 Python 语言支持、宿主工具链驱动的 `Pyrefly` 解释器注入、`.venv` / `.conda` / `conda` / `uv` / `pyenv` 多来源环境发现、动态 `pytest` 测试树收集与执行、`uv` / `conda` / `Ruff` 构建任务、源码级断点调试及新建项目向导。跨平台实现与验证记录详见 [docs/feature-matrix.md](docs/feature-matrix.md)。
---
## 核心能力(Capabilities)
1. **语言与编辑器基础(`languages: python`)**
- - 识别 `.py`、`.pyi`、`.pyw`,配置 `#` 行注释与括号/引号自动配对,声明 `pyproject.toml` / `setup.py` / `setup.cfg` / `requirements.txt` / `Pipfile` / `pyrefly.toml` 项目标记及 `.venv` / `venv` 项目依赖目录。
-2. **语言服务器(`languageServers: python` / Pyrefly `1.4.1`)**
- - 构建期固定版本与 SHA-256 打包 `pyrefly 1.4.1`(Unix:`bin/pyrefly`,Windows:`bin/pyrefly.exe`),启动参数 `["lsp"]`,验证参数 `["--version"]`。
- - `workspaceConfiguration` 即时同步类型检查模式(`typeCheckingMode`)、诊断显示策略(`displayTypeErrors`)、诊断范围(`diagnosticMode`)、自动导入与括号补全,并通过 `indexingExclusions` 将工作区排除目录注入 `python.pyrefly.extraProjectExcludes`。
- - 不向 `pyrefly` 发送空字符串 `python.pythonPath: ""`,保留 `pyrefly` 对项目 `.venv`、`VIRTUAL_ENV`、`CONDA_PREFIX` 与 `pyproject.toml` 的原生环境自动解析。
-3. **工具链与虚拟环境解析(`toolDefinitions: python`)**
- - 严格按 Core 4 层优先级解析:项目级显式绑定 → 项目内虚拟环境(`.venv` / `venv`,`projectKind: "environment"`,要求 `pyvenv.cfg` 且受宿主工作区信任门控)→ 全局设置 → `VIRTUAL_ENV` 环境变量与 `PATH`(`python3` / `python`)→ 自动发现安装。
- - 自动发现覆盖 macOS(Homebrew `/opt/homebrew/opt/python@*/libexec`、`/usr/local/opt/python@*/libexec`、`Python.framework`)、Linux(`/usr`、`/usr/local`)、Windows(`%LOCALAPPDATA%\Programs\Python\*`)、`pyenv` / `pyenv-win`、`uv`(`~/.local/share/uv/python/*` 与 `%APPDATA%\uv\data\python\*`)、`conda` / `miniforge` / `miniconda` / `anaconda` base 与 `envs/*`。
-4. **4 个独立构建系统(`buildSystems`)**
- - `python`:`python -I -B ${pluginDir}/scripts/build_model.py ${root} ${outputFile}` 通过纯 `ast` + `tomllib`(Python 3.9–3.10 自动回退内置 `vendor/tomli`)静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 运行目标(绝不执行用户项目代码);内置 `pip install -r requirements.txt`、`mypy`(带诊断 `lineMatcher`)与 `pytest`(支持工作区/项目/目标及 `suite` / `case` 过滤,解析 `.pytest_cache/lithe-junit.xml` JUnit XML 报告)。
+ - 识别 `.py`、`.pyi`、`.pyw`,配置 `#` 行注释与括号/引号自动配对,声明 `pyproject.toml` / `setup.py` / `setup.cfg` / `requirements.txt` / `Pipfile` / `pyrefly.toml` 项目标记及 `.venv` / `venv` / `.conda` 项目依赖目录。
+2. **后端解析的语言服务器启动与解释器自动注入(`backend` + `languageServers: python` / Pyrefly `1.4.1`)**
+ - 启动语言服务器前,宿主需要能够发现 Python 3.9 或更高版本以执行启动解析后端。宿主会传入可用于自动启动的解释器路径,项目内环境交由 Pyrefly 按自身规则发现。
+ - 构建期按平台固定版本与 SHA-256 打包 `pyrefly 1.4.1`(Unix:`bin/pyrefly`,Windows:`bin/pyrefly.exe`),6 个平台发布包共享同一套纯 Python(`python -I -B`)插件后端 `scripts/backend.py`。
+ - `languageServers[0]` 采用 `"launch": {"kind": "backend", "function": "pyrefly.resolveLaunch", "timeoutMilliseconds": 30000}`:根据 `platform.os` 动态返回包内 `bin/pyrefly` 或 `bin/pyrefly.exe` 与 `arguments: ["lsp"]`,合并全部即时设置(`typeCheckingMode`、`displayTypeErrors`、`diagnosticMode`、`autoImportCompletions`、`completeFunctionParens`、`importFormat`)。
+ - 当宿主在调用参数中传入已选定的非项目内解释器 `tools.python.executable`(如外部 `conda`、`uv`、`pyenv` 或系统环境)时,自动注入 `workspaceConfiguration.python.pythonPath`;当 `tools.python` 缺失(未选定或项目内虚拟环境尚未获信任)时优雅省略 `pythonPath`,保留 `pyrefly` 原生 `.venv` / `pyproject.toml` 自动发现且不阻断启动。
+3. **工具链与多环境发现增强(`toolDefinitions: python` + `toolchain_provider.py`)**
+ - 严格按 Core 4 层优先级解析:项目级显式绑定 → 项目内环境(`.venv` / `venv` / `.conda`,`projectKind: "environment"`,受宿主工作区信任门控并保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` 与 `PATH`(`python3` / `python`)→ 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、macOS Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`)。
+ - `scripts/toolchain_provider.py` 完整实现 `litheToolchains`(`toolchains/query`)协议(支持 `~/.conda/environments.txt`、`CONDA_ENVS_PATH`、`UV_PYTHON_INSTALL_DIR`、`PYENV_ROOT`、Poetry 与 Pipenv 外部虚拟环境、`.python-version` 与 `pyproject.toml` `requires-python`)。当前桌面宿主通过清单中的 `toolDefinitions` 发现已安装解释器。提供者协议可独立验证,在桌面端启用还需要宿主支持 `toolchainProviders`、清单声明以及满足 Core 自举契约的打包运行时。
+4. **4 个独立构建系统与动态 `pytest` 测试树(`buildSystems` & `buildProviders`)**
+ - `python`:通过纯 Python 构建提供者 `scripts/build_provider.py --cache ${workspaceStateDir}`(`python -I -B`,`executesProjectCode: true`,`mayUseNetwork: false`)承载:
+ - `lithe/build/model`:复用 `scripts/build_model.py` 纯 `ast` + `tomllib`(Python 3.9–3.10 自动回退内置 `vendor/tomli`)静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 运行目标(绝不执行用户代码),派生 7 类声明式 `run` 配置;
+ - `lithe/build/discoverTests`:运行可随 `$/cancelRequest` 整组终止的 `pytest --collect-only`,收集函数、类方法与参数化用例,按 Core 的条数和 UTF-8 字节限制返回 `litheTestDiscovery` v0。缓存写入 `${workspaceStateDir}`。
+ - `lithe/build/test`:通过 pytest node ID 精确运行套件或单个用例,也接受 JUnit XML 类名。指定用例时须同时给出套件。运行时推送 `lithe/build/progress`,并产出 `.pytest_cache/lithe-junit.xml` 供 Core 解码。构建请求在排队时即可取消,执行进程的所有权随请求结束。macOS 和 Linux 使用 POSIX 进程组,Windows 使用 Job Object。
+ - `lithe/build/runEntrypoints`:协商 `litheBuild` 1 时按文件静态识别入口并抑制高频成功日志;
+ - 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。
- `uv`(`uv.lock`):`uv sync`、`uv lock`。
- `conda`(`environment.yml` / `environment.yaml`):`conda env update --file environment.yml --prune`。
- `ruff`(`ruff.toml` / `.ruff.toml` / `pyproject.toml`):`ruff check`(带诊断 `lineMatcher`)与 `ruff format`。
5. **调试器(`debugAdapters: debugpy`)**
- - 复用当前选定的 `python` 工具链(`>= 3.9`),以 `["-I", "-B"]` 隔离参数启动 `scripts/debugpy_adapter.py --log-dir ${logDir}`,在加载内置 `vendor/debugpy/adapter/__main__.py` 前显式设置 `PYTHONDONTWRITEBYTECODE=1` 并补齐 `sys.path[0]`(兼容 Python 3.9–3.14 的 `-I` 隔离模式,同时确保 `debugpy/adapter` 拉起的 `debugpy/launcher` 子进程在 Windows / macOS / Linux 可写插件目录下也不会生成任何 `__pycache__` 字节码)。
- - `launch` 默认开启 `"console": "internalConsole"`、`"justMyCode": true` 并注入 `"env": {"PYTHONDONTWRITEBYTECODE": "1"}`;同时支持远程 TCP `attach`(`host` / `port` / `pathMappings`)。
+ - 以 `["-I", "-B"]` 隔离参数启动 `scripts/debugpy_adapter.py --log-dir ${logDir}`,双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持已安装插件目录零字节码写入,支持本地 `launch` 与远程 TCP `attach`(`host` / `port` / `pathMappings`)。
6. **终端 Traceback 链接与新建项目向导(`outputLinkMatchers` & `projectGenerators`)**
- - 自动识别终端输出中的 `File "...", line N` 并支持一键跳转源码。
- - 新建项目向导支持选择并固定项目级 `python` 解释器(`pinAs: "project"`),可选 `None` / `venv (.venv)` / `uv (.venv)` 环境创建与示例代码生成。
+ - 自动识别终端输出中的 `File "...", line N` 并支持跳转源码;新建项目向导支持固定项目级 `python` 解释器(`pinAs: "project"`)及创建 `.venv`(`venv` / `uv`)。
---
## 日志接线说明(Structured Logging v2 Wiring)
-本插件 `0.1.0` 为**纯声明式插件**(不声明 `backend` 常驻进程),全部诊断均遵循 Lithe 结构化日志 v2 规范(Core `rust/logging/README.md` 与 `shared/plugins/contract/v1/README.md#structured-plugin-diagnostics`),已安装插件目录在运行期保持 **100% 只读**:
+本插件 `0.2.0` 包含纯 Python 插件后端(`scripts/backend.py`)、构建提供者(`scripts/build_provider.py`)与声明式贡献,全部诊断严格遵循 Lithe 结构化日志 v2 规范(Core `rust/logging/README.md`、`shared/plugins/contract/v1/README.md#structured-plugin-diagnostics` 与 `shared/plugins/guides/plugin-logging.md`),**零自建插件日志文件**,已安装插件目录在运行期保持 **100% 只读**。
-### 1. SDK 后端日志接线适用性说明
+### 1. 后端与构建 Provider 协议接线(统一通道:`plugins/io.github.lithe-idea.python-support/host`)
-- **`litheLogging` 0 / `lithe/log` 协议上报**:**不适用(N/A)**——本版本无插件后端进程,不引入 Node/Java/Rust 插件后端 SDK。
-- **降级与恢复事件(`plugins.operation.fallback_selected` / `plugins.operation.recovery_finished`,`WARN`)**:**不适用(N/A)**——仅带 SDK 后端的插件函数存在插件内缓存回退或连接恢复分支。
-- **高频成功诊断抑制(`suppressSuccessDiagnostics`)**:**不适用(N/A)**——本版本不导出高频查询或轮询插件函数。
+`scripts/lithe_rpc.py` 实现 stdio JSON-RPC 2.0 协议帧传输,与宿主代记的声明式贡献共用同一个结构化日志通道 `plugins/io.github.lithe-idea.python-support/host`(见 Core `rust/logging/events/plugins.json`):
+- **强制协商 `litheLogging` 0**:`initialize` 缺少 `experimental.litheLogging` `versions: [0]` 时立即以 `-32600` 拒绝握手;握手成功后将 Python 层 `sys.stdout` 重定向到 `sys.stderr`,确保 `stdout` 仅输出合法 `Content-Length` JSON-RPC 帧。
+- **请求级 `operationId` 关联与时序**:所有 `lithe/log` 通知严格在对应 JSON-RPC 响应帧发出**之前**写入 `stdout`,携带宿主请求传入的 `operationID`(回退为受控请求 ID),确保 Core 将诊断精确关联到活跃操作。
+- **取消不记失败**:收到 `$/cancelRequest` 时立即终止关联子进程组(POSIX `os.killpg` / Windows `taskkill /T /F`),返回 `-32800` 且**不发送** `operationFinished` 或 `operationFailed`。
+
+| `operation` | 所属进程 | 成功事件与级别 | 降级 / 恢复事件(`WARN`) | 失败事件与级别(`ERROR`) | 受控 `code` 类别标识 |
+| --- | --- | --- | --- | --- | --- |
+| `initialize` | `backend.py` / `build_provider.py` | 握手由 Core 记录 `plugins.host.protocol.initialized`(`INFO`) | `plugins.operation.fallback_selected`(`code: "functions_unavailable"`,当宿主未协商 `litheFunctions` 时) | 握手失败由 Core / 宿主记录 | `functions_unavailable` |
+| `pyrefly.resolveLaunch` | `backend.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "invalid_tool_hint"`,`count: 1`)
恢复:`plugins.operation.recovery_finished`(`code: "tool_hint_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `invalid_tool_hint`、`tool_hint_restored`、`python.unknownServer`、`internal_error` |
+| `python.inspectEnvironment` | `backend.py` | **已启用 `suppressSuccessDiagnostics`**(高频只读查询成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidExecutable`、`internal_error` |
+| `lithe/build/model` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "pyproject_parse_failed"`,`count: 1`)
恢复:`plugins.operation.recovery_finished`(`code: "pyproject_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `pyproject_parse_failed`、`pyproject_restored`、`python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
+| `lithe/build/discoverTests` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "test_discovery_truncated"`,`count` 为超出条数、大小或无法表示为有效选择器而省略的条目数) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `test_discovery_truncated`、`python.pytestUnavailable`、`python.pytestTimedOut`、`python.pytestCollectionFailed`、`python.interpreterUnavailable`、`python.cacheUnavailable` |
+| `lithe/build/test` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`;测试断言失败仍属正常协议返回 `exitCode != 0`,失效/越界选择器、进程级超时或解释器缺失才记 `ERROR`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidTestSelector`、`python.staleTestSelector`、`python.pytestTimedOut`、`python.interpreterUnavailable`、`python.projectUnavailable`、`internal_error` |
+| `lithe/build/runEntrypoints` | `build_provider.py` | **已启用 `suppressSuccessDiagnostics`**(打开文件高频静态入口探测成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
+| `notification` / `result-encoding` / `shutdown` | `lithe_rpc.py` | — | — | `plugins.operation.failed`(`ERROR`) | `framing_error`、`result_encoding_failed`、`internal_error` |
+
+> 注:`toolchains/query` 的错误码与超时由工具链契约(`plugin.toolchain.*`)结构化返回并由宿主工具链层统一观测;因 Core `plugin_logging` 操作白名单未纳入 `toolchains/query`,后端不为其额外发送 `lithe/log` 以避免产生 `plugins.diagnostics.rejected`。
### 2. 宿主代记的声明式插件操作(通道:`plugins/io.github.lithe-idea.python-support/host`)
-声明式贡献无插件后端进程,由实际执行该贡献的宿主或 Core 经 `diagnostics.recordPluginOperation` 将每次尝试的唯一终态代记到 v2 会话通道 `plugins/io.github.lithe-idea.python-support/host`(活动文件 `plugins/io.github.lithe-idea.python-support/host.log`,轮转文件 `~1.log`)。用户主动取消、停止或被新请求取代的尝试**不记录**:
+声明式启动的语言服务器子进程与调试适配器由宿主与 Core 经 `diagnostics.recordPluginOperation` 将唯一终态代记到 `plugins/io.github.lithe-idea.python-support/host`(用户主动取消或停止不记录):
| `operation` | 声明来源 | 记录方 | 成功事件与级别 | 失败事件与级别 | 可能的 `host.*` 失败类别标识(`code`) |
| --- | --- | --- | --- | --- | --- |
-| `languageServer/start` | `languageServers[]`(`python` / Pyrefly) | 启动前失败由桌面宿主记录;进入启动后经 `lsp.startServer.startupOperation` 交由 Core 记录唯一终态 | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.executableUnavailable`、`host.launchFailed`、`host.exitedEarly`、`host.initializeFailed`、`host.timedOut` |
+| `languageServer/start` | `languageServers[]`(`pyrefly.resolveLaunch` 解析后的 `pyrefly lsp` 进程) | 启动前失败由桌面宿主记录;进入启动后经 `lsp.startServer.startupOperation` 交由 Core 记录唯一终态 | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.planFailed`、`host.executableUnavailable`、`host.launchFailed`、`host.exitedEarly`、`host.initializeFailed`、`host.timedOut` |
| `debugAdapter/start` | `debugAdapters[]`(`debugpy`) | 桌面宿主(`op` 为调试会话 ID;用户停止与 Core 拒绝建会话不记录) | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.executableUnavailable`、`host.launchFailed`、`host.exitedEarly`、`host.initializeFailed`、`host.timedOut` |
-| `lithe/build/model` | `buildSystems[0].model`(`scripts/build_model.py` 命令式模型) | 桌面宿主(`op` 为加载构建模型的操作) | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.planFailed`、`host.executableUnavailable`、`host.launchFailed`、`host.timedOut`、`host.commandFailed`、`host.outputInvalid` |
-
-> 注:本插件未声明 `buildSystems[].dependencies` 与 `commandInstallers[]`,因此 `lithe/build/dependencies` 与 `commandInstaller/install` 在本版本不会触发。
-#### `host.*` 失败类别标识语义对照
-
-| `code` | 触发阶段与含义 |
-| --- | --- |
-| `host.planFailed` | 声明式命令无法完成启动或参数规划(如缺少必需目录或模板变量非法) |
-| `host.executableUnavailable` | 声明的包内可执行文件、入口脚本或 `python` 运行时工具链无法解析或版本不满足 `minimumVersion` |
-| `host.launchFailed` | 已解析的进程启动失败(操作系统 `exec` / 创建进程失败) |
-| `host.exitedEarly` | `pyrefly lsp` 或 `debugpy` 适配器在完成 `initialize` 握手前提前退出 |
-| `host.initializeFailed` | 已启动的语言服务器或调试适配器 `initialize` 握手返回错误 |
-| `host.timedOut` | 启动握手或 `build_model.py` 命令超出宿主设定的有界超时 |
-| `host.commandFailed` | `build_model.py` 非零退出(脚本保证真实失败必返回非零退出码) |
-| `host.outputInvalid` | `build_model.py` 正常退出但 `${outputFile}` 不是合法的 `litheBuildModel` v0 JSON 文档 |
-
-### 3. 上游子进程通道、隐私边界与原生日志文件
+### 3. 上游子进程通道、隐私红线与原生日志文件
| 组件 / 命令 | v2 结构化通道或原生文件位置 | 级别、限流、脱敏与清理策略 |
| --- | --- | --- |
-| `pyrefly lsp`(语言服务器) | 结构化通道:`lsp/python` | Core 记录 `lsp.process.started`、`lsp.protocol.initialized`、`lsp.session.updated`;上游 `window/logMessage` 与 `window/showMessage` 经 `lsp.message.logged` / `lsp.message.shown` 保留显式 `ERROR`/`WARN`/`INFO`/`DEBUG` 级别;未分类 `stderr` 经 `lsp.stderr.received` 固定记为 `DEBUG`(Core 限制每行 4 KiB、200 行/秒,再经 1 KiB 脱敏截断,仅在详细诊断开启时落盘);详细诊断开启(15 分钟单次到期)时仅接纳 `$/logTrace.message` 摘要(`lsp.trace.received`),拒绝可能含源码的 `verbose` 载荷。`pyrefly` 不写任何插件内文件。 |
-| `debugpy`(调试适配器与启动器) | 结构化通道:`debug/debugpy`
原生日志文件:`sessions//plugins/io.github.lithe-idea.python-support/files/debugpy.*.log` | 结构化会话事件(`debug.process.started`、`debug.session.initialized`、`debug.session.state_changed`、`debug.session.finished`、`debug.session.failed`、`debug.operation.failed`、`debug.operation.cancelled`)写入 `debug/debugpy`;上游 `debugpy` 原生日志通过 `--log-dir ${logDir}` 定向写入桌面宿主 `Store.PluginFilesDirectory` 创建的当前会话专属目录(权限 `0700`,逐段校验拒绝软链越界,绝不写插件安装目录或 app bundle)。上游 `debugpy` 默认输出适配器/pydevd 诊断日志,按 `` 独立建文件(`debugpy.adapter-.log`、`debugpy.launcher-.log`、`debugpy.pydevd..log`),无内置单文件轮转,随宿主日志会话生命周期统一保留与清理。 |
-| `scripts/build_model.py`(模型脚本) | 模型输出:宿主临时 `${outputFile}`
诊断输出:宿主构建命令 `stderr` 摘要 | 脚本以 `python -I -B` 与 `sys.dont_write_bytecode = True` 运行;`stdout` 不输出自由文本,`stderr` 严格只输出受控简短分类词(`invalid_arguments`、`project_root_unavailable`、`model_generation_failed ()`),**绝不拼接工作区路径、用户源码或原始异常消息**。 |
-| 工具链探针、构建任务、`pytest` 与项目生成 | 宿主 `app` / `app/core` 请求轨迹及构建/运行/向导面板 | `python --version` 探针受工作区信任门控保护(未信任工作区零探测项目内 `.venv`);`pip`、`mypy`、`pytest`、`uv`、`conda`、`ruff` 与 `projectgen` 子进程输出流向对应 UI 控制台与 JUnit XML(`.pytest_cache/lithe-junit.xml`),进程 `stdout`、源码与环境变量值绝不进入 v2 结构化日志。 |
+| `backend.py` / `build_provider.py`(纯 Python 后端与构建 Provider) | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`
未分类 `stderr`:`plugins.host.stderr.received`(`DEBUG`) | **零自建日志文件**;会话启动与握手由 Core 记录 `plugins.host.process.started` / `plugins.host.protocol.initialized` / `plugins.host.session.updated`;未预期异常在 `stderr` 仅输出 `: ()` 受控短词,**绝不拼接文件路径、命令参数、源码片段、输出内容或环境变量值**。Core 对 `stderr` 按每行 4 KiB 限流并脱敏截断,仅在详细诊断开启时落盘。 |
+| `pyrefly lsp`(语言服务器) | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`(或宿主内置 `lsp/python`) | Core 记录 `plugins.host.process.started`、`plugins.host.protocol.initialized`、`plugins.host.session.updated`;`window/logMessage` 与 `window/showMessage` 保留显式 `ERROR`/`WARN`/`INFO`/`DEBUG` 级别;未分类 `stderr` 经 `plugins.host.stderr.received` 记为 `DEBUG`(仅详细诊断开启时落盘);详细诊断开启(15 分钟单次到期)时仅接纳 `$/logTrace.message` 摘要,拒绝 `verbose` 载荷。`pyrefly` 不写任何插件内文件。 |
+| `debugpy`(调试适配器与启动器) | 结构化通道:`debug/debugpy`
原生日志文件:`sessions//plugins/io.github.lithe-idea.python-support/files/debugpy.*.log` | 结构化会话事件写入 `debug/debugpy`;上游 `debugpy` 原生日志通过 `--log-dir ${logDir}` 定向写入宿主 `Store.PluginFilesDirectory` 创建的当前会话专属目录(权限 `0700`,逐段校验拒绝软链越界,绝不写插件安装目录或 app bundle),按 `` 建文件并随宿主日志会话生命周期统一保留与清理。 |
+| `pytest`、构建任务与项目生成 | 构建/测试面板流式输出(`lithe/build/progress`)与 JUnit XML(`.pytest_cache/lithe-junit.xml`) | `lithe/build/discoverTests` 将 `pytest` 缓存重定向至 `${workspaceStateDir}`;进程 `stdout`、用户测试代码与环境变量值仅进入协议进度流或报告文件,绝不进入 v2 结构化诊断日志。 |
---
@@ -90,6 +92,8 @@ Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion:
### 常用命令
+插件测试使用真实 pytest。将 pytest 安装到 `PYTHON` 对应的环境,或通过 `PYTEST_PYTHON` 指定已安装 pytest 的解释器。
+
```bash
# 打包当前开发平台(例如 macOS Apple Silicon)
node scripts/package.mjs --platform darwin-arm64
@@ -100,7 +104,7 @@ node scripts/package.mjs
# 校验 dist/ 下构建产物的目录安全性、Windows 文件名/大小写兼容性与清单一致性
node --test --test-timeout=60000 scripts/package/*.test.mjs
-# 运行契约不变量检查、build_model.py 全量单测、pyrefly LSP 诊断、debugpy DAP 调试冒烟与只读包哈希不变断言
+# 运行契约不变量检查、backend/build_provider/toolchain_provider 协议单测、pyrefly LSP 解释器注入与回退、pytest 动态发现与执行、debugpy 调试及只读包哈希不变断言
node scripts/test.mjs
# 针对真实 Lithe 桌面宿主与 Rust Core 运行端到端集成测试
diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md
index c080192..4d0f8f7 100644
--- a/docs/feature-matrix.md
+++ b/docs/feature-matrix.md
@@ -1,25 +1,31 @@
# Python Support 功能矩阵(Feature Matrix)
-本文档维护 `io.github.lithe-idea.python-support` 插件在 6 个目标发布平台上的实现与真实执行验证状态(插件功能矩阵与测试证据仅在本插件仓库维护,不进入宿主仓库)。
+本文档维护 `io.github.lithe-idea.python-support`(`v0.2.0`)插件在 6 个目标发布平台上的实现与真实执行验证状态(插件功能矩阵与测试证据仅在本插件仓库维护,不进入宿主仓库)。
## 状态定义
- `✅ 已验证`:已在目标平台实机完成打包安装、真实上游二进制/运行时进程执行及宿主端到端测试验证。
-- `⏳ 待实机验证(pending)`:已在 `plugin.json`、脚本与对应平台归档(`dist/python-support-0.1.0-.zip`)中完成实现,并通过归档路径/大小写安全检查、Lithe Store 规则校验以及 Unix/Windows 双清单真实 Core `ValidatePluginManifest` 契约校验;但尚未在对应 OS/架构实机或 CI runner 上执行原生子进程工作流,严禁在未实跑前标为已验证。
-- `🚧 规划中(M3)`:归属后续 M3 插件后端进程版本。
+- `⏳ 待实机验证(pending)`:已在 `plugin.json`、脚本与对应平台归档(`dist/python-support-0.2.0-.zip`)中完成实现,并通过归档路径/大小写安全检查、Lithe Store 规则校验以及 Unix/Windows 双清单真实 Core `ValidatePluginManifest` 契约校验;但尚未在对应 OS/架构实机或 CI runner 上执行原生子进程工作流,严禁在未实跑前标为已验证。
+- `🚧 待宿主开放(blocked on host capability)`:插件端协议与代码已完整实现并通过真实 Core 解码验证,待桌面宿主开放对应能力版本后启用清单声明。
## 跨平台能力与验证矩阵
| 能力域 | 功能项 | `darwin-arm64` | `darwin-x64` | `windows-x64` / `windows-arm64` | `linux-x64` / `linux-arm64` | 最近实机验证 | 实现与测试证据路径(本仓库) |
| --- | --- | --- | --- | --- | --- | --- | --- |
-| 语言基础 (`languages`) | `.py` / `.pyi` / `.pyw` 识别、`#` 行注释、括号/引号配对、项目标记与 `.venv` / `venv` 依赖目录 | ✅ 已验证 | ⏳ pending(归档与清单已校验) | ⏳ pending(归档与 Windows 清单已校验) | ⏳ pending(归档与清单已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
-| 语言服务器 (`languageServers`) | 内置打包 `pyrefly` `1.4.1`(`bin/pyrefly` / `bin/pyrefly.exe`、`lsp`、`--version`、`workspaceConfiguration`、`indexingExclusions`,保留 `.venv` 原生自动发现) | ✅ 已验证 | ⏳ pending(`macos-x86_64` 二进制已打包校验) | ⏳ pending(`bin/pyrefly.exe` 已打包与契约校验) | ⏳ pending(`musl` 二进制已打包校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`vendor-lock.json`
`scripts/package.mjs`
`scripts/package/archives.test.mjs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
-| 工具链与虚拟环境 (`toolDefinitions`) | `python` 4 层解析:项目绑定 → `.venv` / `venv`(受工作区信任门控,保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` + `PATH` → 16 条跨平台自动发现规则 | ✅ 已验证 | ⏳ pending(清单与 Core 规则已校验) | ⏳ pending(`Scripts/python.exe` / `python.exe` 布局与发现规则已通过 Core 校验) | ⏳ pending(清单与 Core 规则已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
-| 构建模型与运行 (`buildSystems: python`) | `scripts/build_model.py`(`-I -B`,纯 AST + `tomllib` / `vendor/tomli` 零代码执行)静态发现 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 并派生 `run` 配置 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_model.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
-| 任务与测试 (`buildSystems: python`) | `pip install -r requirements.txt`、`mypy`(含诊断 `lineMatcher`)、`pytest`(支持工作区/项目/目标及 `suite` / `case` 过滤,解析 `.pytest_cache/lithe-junit.xml`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
+| 语言基础 (`languages`) | `.py` / `.pyi` / `.pyw` 识别、`#` 行注释、括号/引号配对、项目标记与 `.venv` / `venv` / `.conda` 依赖目录 | ✅ 已验证 | ⏳ pending(归档与清单已校验) | ⏳ pending(归档与 Windows 清单已校验) | ⏳ pending(归档与清单已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
+| 插件后端与语言服务器启动解析 (`backend` + `languageServers`) | 纯 Python(`python -I -B`)stdio JSON-RPC 后端 `scripts/backend.py`(协商 `litheLogging` 0 与 `litheFunctions` 0);`pyrefly.resolveLaunch` 按 `platform.os` 返回包内 `bin/pyrefly`(Unix)或 `bin/pyrefly.exe`(Windows)与 `["lsp"]`,在宿主传入 `tools.python.executable` 时自动注入 `workspaceConfiguration.python.pythonPath`(支持项目外 conda / uv / pyenv 解释器),缺失或未信任项目环境时优雅省略 `pythonPath` 回退 `pyrefly 1.4.1` 原生 `.venv` 发现 | ✅ 已验证 | ⏳ pending(`macos-x86_64` 二进制与纯 Python 后端已打包校验) | ⏳ pending(`bin/pyrefly.exe` 平台分支已通过 Core `DecodePluginLanguageServerLaunch` 校验) | ⏳ pending(`musl` 二进制与纯 Python 后端已打包校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/lithe_rpc.py`
`io.github.lithe-idea.python-support/scripts/backend.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
+| 工具链与环境自动发现 (`toolDefinitions`) | `python` 4 层解析:项目绑定 → `.venv` / `venv` / `.conda`(受工作区信任门控,保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` + `PATH` → 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`) | ✅ 已验证 | ⏳ pending(清单与 Core 规则已校验) | ⏳ pending(`Scripts/python.exe` / `python.exe` 布局与环境变量发现规则已通过 Core 校验) | ⏳ pending(清单与 Core 规则已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
+| 构建模型与运行 (`buildSystems: python` + `provider`) | `scripts/build_provider.py`(`python -I -B`,`lithe/build/model`)复用 `scripts/build_model.py` 纯 AST + `tomllib` / `vendor/tomli` 静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 并派生 7 类声明式 `run` 配置;支持损坏 `pyproject.toml` 降级与修复后恢复诊断,并在协商 `litheBuild` 1 时支持 `lithe/build/runEntrypoints` | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_model.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
+| 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `lithe/build/discoverTests` 通过有界可取消 `pytest --collect-only` 收集函数、测试类方法与 `@pytest.mark.parametrize` 参数化用例(缓存写入 `${workspaceStateDir}`,按条数和 UTF-8 字节限制返回 `litheTestDiscovery` v0);`lithe/build/test` 支持精确 node ID 与 JUnit 类名重跑,单个用例须带套件、`lithe/build/progress` 流式输出及 `.pytest_cache/lithe-junit.xml` 解码;保留 `pip install -r requirements.txt` 与 `mypy` 任务 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
| 独立工具构建系统 (`uv` / `conda` / `ruff`) | `uv`(`sync` / `lock`)、`conda`(`env update --file environment.yml --prune`)、`ruff`(`check` 含 `lineMatcher` / `format`)按各自标记文件独立检测与规划 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
| 调试器 (`debugAdapters: debugpy`) | 内置打包 `debugpy` `1.8.22`(`stdio` DAP,`["-I", "-B"]` + `scripts/debugpy_adapter.py`、`--log-dir ${logDir}`、适配器与 `launch` 双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持插件目录零写入、支持远程 `attach` + `pathMappings`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/scripts/debugpy_adapter.py`
`vendor-lock.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
| 终端输出跳转 (`outputLinkMatchers`) | Python Traceback `File "...", line N` 点击定位源码与行号 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
| 新建项目向导 (`projectGenerators`) | `python-project`:选择并固定项目级 `python` 工具链(`pinAs: "project"`),可选 `none` / `venv (.venv)` / `uv (.venv)` 与示例代码生成(Windows 自动将 `python3` 命令切换为 `python`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(Windows 清单 `python` 命令切换已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/templates/python/`
`scripts/package/archives.test.mjs`
`e2e/host/desktop/internal/projectgen/python_integration_test.go` |
| 国际化 (`l10n`) | 英文默认文案 + `l10n/zh-Hans.json` 简体中文完整设置与分组翻译 | ✅ 已验证 | ⏳ pending(归档与 Core `settingsState` 已校验) | ⏳ pending(归档与 Core `settingsState` 已校验) | ⏳ pending(归档与 Core `settingsState` 已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/l10n/zh-Hans.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
-| 插件后端高级能力(M3) | `pytest --collect-only` 原生测试树发现、依赖树视图、`pyproject.toml` 原生配置页编辑器、工具链后端深度枚举 | 🚧 规划中(M3) | 🚧 规划中(M3) | 🚧 规划中(M3) | 🚧 规划中(M3) | — | — |
+| 工具链 Provider 协议 (`litheToolchains` / `toolchains/query`) | `scripts/toolchain_provider.py` 与 `backend.py` 已完整实现 `toolchains/query`(解析 `~/.conda/environments.txt`、`CONDA_ENVS_PATH`、`UV_PYTHON_INSTALL_DIR`、`PYENV_ROOT`、Poetry/Pipenv 外部虚拟环境、`.python-version` 与 `pyproject.toml` `requires-python`,严格排除工作区内目录并通过真实 Core `toolchains.decodeReply` 校验);清单层待桌面宿主开放 `toolchainProviders` 后启用(见下方前置说明) | 🚧 待宿主开放 `toolchainProviders`(后端协议与 Core 解码已在 `darwin-arm64` 实测通过) | 🚧 待宿主开放 `toolchainProviders` | 🚧 待宿主开放 `toolchainProviders` | 🚧 待宿主开放 `toolchainProviders` | `2026-11-18`(协议与 Core 解码验证) | `io.github.lithe-idea.python-support/scripts/toolchain_provider.py`
`io.github.lithe-idea.python-support/scripts/backend.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
+
+## `toolchainProviders` 宿主前置条件说明
+
+1. **桌面宿主能力门禁**:`Lithe-core-rust` 已支持 `toolchainProviders: 0`(`litheToolchains` 的 `toolchains/query` 与 `toolchains.decodeReply`),但当前桌面宿主 `desktop/internal/pluginhost/pluginhost.go` 的 `Declared()` 尚未声明 `toolchainProviders`。若在 `plugin.json` 中直接写入 `"requires": {"toolchainProviders": 0}`,当前桌面宿主安装校验会拒绝安装整个插件。
+2. **自举约束**:Core 清单校验(`validate_packaged_provider_backend`)要求声明 `toolchainProviders` 的插件后端必须使用包内可执行文件(`packaged`)或包内自带运行时(`packagedRuntime`)自举,不能依赖所要发现的外部 `tool: "python"` 启动。
+3. **当前落地方案**:桌面宿主通过 `toolDefinitions` 中的 16 条声明式规则和新增的 `.conda` 项目环境候选发现解释器。独立协议测试协商 `experimental.litheToolchains` 并验证 `toolchains/query` 响应。正式接线仍需桌面宿主开放能力、清单声明及打包后端自举,当前安装包通过固定宿主校验。
diff --git a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go
index 099d16e..2a10afb 100644
--- a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go
+++ b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go
@@ -5,19 +5,24 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
+ "fmt"
"io"
"io/fs"
"maps"
+ "net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
+ "sync"
"testing"
"time"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/buildprovider"
"github.com/1lck/Lithe-IDEA/desktop/internal/core"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend"
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost"
"github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall"
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice"
@@ -71,15 +76,6 @@ func toWindowsVariantManifest(t *testing.T, unixManifest []byte) []byte {
if err := json.Unmarshal(unixManifest, &doc); err != nil {
t.Fatal(err)
}
- servers, _ := doc["languageServers"].([]any)
- for _, rawServer := range servers {
- srv, _ := rawServer.(map[string]any)
- if srv["languageID"] == "python" {
- if launch, ok := srv["launch"].(map[string]any); ok {
- launch["path"] = "bin/pyrefly.exe"
- }
- }
- }
generators, _ := doc["projectGenerators"].([]any)
for _, rawGen := range generators {
gen, _ := rawGen.(map[string]any)
@@ -98,6 +94,27 @@ func toWindowsVariantManifest(t *testing.T, unixManifest []byte) []byte {
return encoded
}
+func pythonFileURI(path string) string {
+ slashed := filepath.ToSlash(path)
+ if !strings.HasPrefix(slashed, "/") {
+ slashed = "/" + slashed
+ }
+ return (&url.URL{Scheme: "file", Path: slashed}).String()
+}
+
+func resolvePytestToolForE2E(t *testing.T, ctx context.Context, systemPython string) core.BuildTool {
+ t.Helper()
+ executable := os.Getenv("PYTEST_PYTHON")
+ if executable == "" {
+ executable = systemPython
+ }
+ cmd := exec.CommandContext(ctx, executable, "-B", "-c", "import pytest")
+ if err := cmd.Run(); err != nil {
+ t.Fatalf("pytest is required for the host test; set PYTEST_PYTHON to an interpreter with pytest: %v", err)
+ }
+ return core.BuildTool{Executable: executable}
+}
+
func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
archive := os.Getenv("LITHE_TEST_PYTHON_PLUGIN_ARCHIVE")
if archive == "" {
@@ -112,6 +129,9 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
if err != nil {
t.Fatalf("%s not on PATH: %v", pythonCmd, err)
}
+ if resolvedSysPy, evalErr := filepath.EvalSymlinks(systemPython); evalErr == nil {
+ systemPython = resolvedSysPy
+ }
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
@@ -122,6 +142,9 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ t.Cleanup(func() {
+ service.Host.Stop(pythonSupportPluginID)
+ })
// 1. Real installer Prepare + Commit + Enable.
plan, err := service.Installer.Prepare(ctx, plugininstall.Request{
@@ -162,6 +185,37 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
t.Fatalf("Windows manifest rejected by pluginhost.Validate: %v", err)
}
+ // Wire runtime tool launch resolution and structured log capture on service.Backend.
+ registryInput, err := toolchain.RegistryInput([]json.RawMessage{normalizedManifest})
+ if err != nil {
+ t.Fatalf("toolchain.RegistryInput: %v", err)
+ }
+ var logMu sync.Mutex
+ var recordedEvents []string
+ service.Backend.SetLogFacts(func(_ core.LogLevel, event string, fields map[string]any) {
+ logMu.Lock()
+ op, _ := fields["operation"].(string)
+ recordedEvents = append(recordedEvents, fmt.Sprintf("%s:%s", event, op))
+ logMu.Unlock()
+ })
+ service.Backend.SetToolResolver(func(_ context.Context, _, _, tool string) (pluginbackend.ToolExecutable, error) {
+ if tool != "python" {
+ return pluginbackend.ToolExecutable{}, fmt.Errorf("unexpected tool %s", tool)
+ }
+ return pluginbackend.ToolExecutable{Path: systemPython}, nil
+ })
+ service.Backend.SetToolEntryResolver(func(callCtx context.Context, _, _ string, input pluginbackend.ToolEntryLaunch) (pluginbackend.ToolExecutable, error) {
+ launch, launchErr := kernel.InstantiateToolchainLaunch(callCtx, registryInput, input.Tool, systemPython, "", input.Entry, input.RuntimeArguments, input.Arguments)
+ if launchErr != nil {
+ return pluginbackend.ToolExecutable{}, launchErr
+ }
+ return pluginbackend.ToolExecutable{Path: launch.Executable, Arguments: launch.Arguments}, nil
+ })
+ sessionLogDir := t.TempDir()
+ service.LogDirectory = func(_ context.Context, _ string) string {
+ return sessionLogDir
+ }
+
// 3. Verify zh-Hans localization is accepted by Core settingsState without rejections.
zhBytes, err := os.ReadFile(filepath.Join(installedDir, "l10n", "zh-Hans.json"))
if err != nil {
@@ -181,38 +235,113 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
t.Fatalf("unexpected l10n rejections: %+v", settingsState.Localization.Rejected)
}
- // 4. Plan language server (Pyrefly) and run --version against installed binary.
+ // 4. Plan backend-resolved language server (Pyrefly), call real backend.py pyrefly.resolveLaunch
+ // with and without tools.python.executable, decode via Core, and run pyrefly --version.
stateDir := t.TempDir()
- logDir := t.TempDir()
- lspPlan, err := kernel.PlanPluginLanguageServer(ctx, normalizedManifest, "python", core.PluginBackendDirectories{
- PluginDirectory: installedDir,
- StateDirectory: stateDir,
- LogDirectory: logDir,
- Architecture: core.PluginArchitecture(),
- })
+ wsStateDir := t.TempDir()
+ tempDir := t.TempDir()
+ lspDirs := core.PluginBackendDirectories{
+ PluginDirectory: installedDir,
+ StateDirectory: stateDir,
+ WorkspaceStateDirectory: wsStateDir,
+ LogDirectory: sessionLogDir,
+ TemporaryDirectory: tempDir,
+ Architecture: core.PluginArchitecture(),
+ }
+ lspPlan, err := kernel.PlanPluginLanguageServer(ctx, normalizedManifest, "python", lspDirs)
if err != nil {
t.Fatalf("PlanPluginLanguageServer: %v", err)
}
- pyreflyExec, err := pluginhost.ResolveExecutable(installedDir, lspPlan.Launch.Path)
+ if lspPlan.Launch.Kind != "backend" || lspPlan.Launch.Function != "pyrefly.resolveLaunch" {
+ t.Fatalf("expected backend-resolved pyrefly launch, got %+v", lspPlan.Launch)
+ }
+
+ // 4a. Call pyrefly.resolveLaunch WITH tools.python.executable injected.
+ var resolveParamsWithTool map[string]any
+ if err := json.Unmarshal(lspPlan.ResolveParams, &resolveParamsWithTool); err != nil {
+ t.Fatal(err)
+ }
+ resolveParamsWithTool["tools"] = map[string]any{
+ "python": map[string]any{
+ "executable": systemPython,
+ "version": "3.12.0",
+ },
+ }
+ encodedWithTool, err := json.Marshal(resolveParamsWithTool)
if err != nil {
- t.Fatalf("ResolveExecutable(%s): %v", lspPlan.Launch.Path, err)
+ t.Fatal(err)
}
- verOut, err := exec.CommandContext(ctx, pyreflyExec, lspPlan.ValidationArguments...).CombinedOutput()
+ ctxRef := json.RawMessage(`{"contextID":"ctx-e2e-1","generation":1}`)
+ answerWithTool, err := service.Host.Call(ctx, pythonSupportPluginID, lspPlan.Launch.Function, encodedWithTool, ctxRef, 30*time.Second)
+ if err != nil {
+ t.Fatalf("Host.Call(pyrefly.resolveLaunch with tool): %v", err)
+ }
+ decodedWithTool, err := kernel.DecodePluginLanguageServerLaunch(ctx, normalizedManifest, "python", lspDirs, answerWithTool)
+ if err != nil {
+ t.Fatalf("DecodePluginLanguageServerLaunch(with tool): %v", err)
+ }
+ expectedPyreflyRel := "bin/pyrefly"
+ if runtime.GOOS == "windows" {
+ expectedPyreflyRel = "bin/pyrefly.exe"
+ }
+ if decodedWithTool.Launch.Kind != "packaged" || decodedWithTool.Launch.Path != expectedPyreflyRel {
+ t.Fatalf("decoded launch = %+v, want packaged %s", decodedWithTool.Launch, expectedPyreflyRel)
+ }
+ if !slices.Equal(decodedWithTool.Arguments, []string{"lsp"}) {
+ t.Fatalf("decoded arguments = %v, want [lsp]", decodedWithTool.Arguments)
+ }
+ if !strings.Contains(string(decodedWithTool.WorkspaceConfiguration), `"pythonPath"`) {
+ t.Fatalf("expected pythonPath injected when tools.python is present, got %s", decodedWithTool.WorkspaceConfiguration)
+ }
+
+ pyreflyExec, err := pluginhost.ResolveExecutable(installedDir, decodedWithTool.Launch.Path)
+ if err != nil {
+ t.Fatalf("ResolveExecutable(%s): %v", decodedWithTool.Launch.Path, err)
+ }
+ verOut, err := exec.CommandContext(ctx, pyreflyExec, "--version").CombinedOutput()
if err != nil {
t.Fatalf("pyrefly --version failed: %v\n%s", err, verOut)
}
if !strings.Contains(strings.ToLower(string(verOut)), "pyrefly 1.4.1") {
t.Fatalf("unexpected pyrefly version output: %q", string(verOut))
}
- if strings.Contains(string(lspPlan.WorkspaceConfiguration), `"pythonPath"`) {
- t.Fatalf("workspaceConfiguration must not emit empty pythonPath: %s", lspPlan.WorkspaceConfiguration)
+
+ // 4b. Call pyrefly.resolveLaunch WITHOUT tools.python (graceful fallback, no pythonPath) and with Windows platform.
+ answerFallback, err := service.Host.Call(ctx, pythonSupportPluginID, lspPlan.Launch.Function, lspPlan.ResolveParams, ctxRef, 30*time.Second)
+ if err != nil {
+ t.Fatalf("Host.Call(pyrefly.resolveLaunch fallback): %v", err)
+ }
+ decodedFallback, err := kernel.DecodePluginLanguageServerLaunch(ctx, normalizedManifest, "python", lspDirs, answerFallback)
+ if err != nil {
+ t.Fatalf("DecodePluginLanguageServerLaunch(fallback): %v", err)
+ }
+ if strings.Contains(string(decodedFallback.WorkspaceConfiguration), `"pythonPath"`) {
+ t.Fatalf("workspaceConfiguration must omit pythonPath when tools.python is absent: %s", decodedFallback.WorkspaceConfiguration)
+ }
+
+ var resolveParamsWin map[string]any
+ if err := json.Unmarshal(lspPlan.ResolveParams, &resolveParamsWin); err != nil {
+ t.Fatal(err)
+ }
+ resolveParamsWin["platform"] = map[string]any{"os": "windows", "arch": "x86_64"}
+ encodedWin, _ := json.Marshal(resolveParamsWin)
+ answerWin, err := service.Host.Call(ctx, pythonSupportPluginID, lspPlan.Launch.Function, encodedWin, ctxRef, 30*time.Second)
+ if err != nil {
+ t.Fatalf("Host.Call(pyrefly.resolveLaunch windows): %v", err)
+ }
+ decodedWin, err := kernel.DecodePluginLanguageServerLaunch(ctx, normalizedManifest, "python", lspDirs, answerWin)
+ if err != nil {
+ t.Fatalf("DecodePluginLanguageServerLaunch(windows): %v", err)
+ }
+ if decodedWin.Launch.Path != "bin/pyrefly.exe" {
+ t.Fatalf("windows launch path = %q, want bin/pyrefly.exe", decodedWin.Launch.Path)
}
// 5. Plan debug adapter (debugpy), verify launch/attach startArguments, and run DAP initialize smoke.
dapPlan, err := kernel.PlanPluginDebugAdapter(ctx, normalizedManifest, "debugpy", core.PluginBackendDirectories{
PluginDirectory: installedDir,
StateDirectory: stateDir,
- LogDirectory: logDir,
+ LogDirectory: sessionLogDir,
Architecture: core.PluginArchitecture(),
})
if err != nil {
@@ -240,7 +369,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
if err := os.WriteFile(mainPy, []byte("if __name__ == '__main__':\n print('ok')\n"), 0o644); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(filepath.Join(workspace, "pyproject.toml"), []byte("[project]\nname = \"ws-app\"\nversion = \"0.1.0\"\n[project.scripts]\nws-cli = \"ws_pkg.cli:main\"\n"), 0o644); err != nil {
+ if err := os.WriteFile(filepath.Join(workspace, "pyproject.toml"), []byte("[project]\nname = \"ws-app\"\nversion = \"0.1.0\"\nrequires-python = \">=3.10\"\n[project.scripts]\nws-cli = \"ws_pkg.cli:main\"\n"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(workspace, "uv.lock"), []byte("version = 1\n"), 0o644); err != nil {
@@ -252,6 +381,14 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
if err := os.WriteFile(filepath.Join(workspace, "ruff.toml"), []byte("line-length = 100\n"), 0o644); err != nil {
t.Fatal(err)
}
+ testsDir := filepath.Join(workspace, "tests")
+ if err := os.MkdirAll(testsDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ sampleTestPy := "import pytest\n\ndef test_alpha():\n assert 1 + 1 == 2\n\n@pytest.mark.parametrize('n,want', [(2, 6), (4, 12)])\ndef test_scale(n, want):\n assert n * 3 == want\n"
+ if err := os.WriteFile(filepath.Join(testsDir, "test_sample.py"), []byte(sampleTestPy), 0o644); err != nil {
+ t.Fatal(err)
+ }
launchStart, err := kernel.PlanDebugStart(ctx, normalizedManifest, "debugpy", "launch", core.DebugStartFacts{
Registration: core.DebugGeneration{Generation: 1, CurrentGeneration: 1},
@@ -292,7 +429,6 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
t.Fatalf("unexpected attach connection: %+v", attachStart.Connection)
}
- // Smoke-run debugpy adapter over stdio with real systemPython and --log-dir.
dapArgs := append([]string{}, dapPlan.Launch.RuntimeArguments...)
dapArgs = append(dapArgs, entryScript)
dapArgs = append(dapArgs, dapPlan.Arguments...)
@@ -321,7 +457,8 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
_ = dapCmd.Process.Kill()
_ = dapCmd.Wait()
- // 6. Detect all 4 build systems (python, uv, conda, ruff), run build_model.py, and decode litheBuildModel.
+ // 6. Detect all 4 build systems (conda, python, ruff, uv), start real build_provider.py,
+ // and verify lithe/build/model, lithe/build/discoverTests, and lithe/build/test + junitXml!
detection, err := kernel.DetectBuildSystems(ctx, workspace, []json.RawMessage{normalizedManifest})
if err != nil {
t.Fatalf("DetectBuildSystems: %v", err)
@@ -335,26 +472,58 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
t.Fatalf("detected build systems = %v, want [conda python ruff uv]", detectedIDs)
}
- outFile := filepath.Join(t.TempDir(), "model.json")
+ buildWsState := t.TempDir()
+ providerClient, err := buildprovider.Start(ctx, service.Backend, pluginbackend.StartRequest{
+ Manifest: normalizedManifest,
+ PackageDirectory: installedDir,
+ PluginID: pythonSupportPluginID,
+ ProviderID: pythonSupportPluginID + "/build/python",
+ BuildSystemID: "python",
+ Role: "build",
+ StateDirectory: stateDir,
+ WorkspaceStateDirectory: buildWsState,
+ LogDirectory: sessionLogDir,
+ Architecture: core.PluginArchitecture(),
+ RootURI: pythonFileURI(workspace),
+ WorkingDirectory: workspace,
+ })
+ if err != nil {
+ t.Fatalf("buildprovider.Start(python): %v", err)
+ }
+ defer func() {
+ stopCtx, stopCancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer stopCancel()
+ _ = providerClient.Close(stopCtx)
+ }()
+
+ pytestTool := resolvePytestToolForE2E(t, ctx, systemPython)
+
+ // 6a. Provider lithe/build/model -> DecodeBuildModel.
modelPlan, err := kernel.PlanBuildModel(ctx, normalizedManifest, "python", core.BuildPlanRequest{
Root: ".",
PluginDirectory: installedDir,
- WorkspaceStateDirectory: stateDir,
- OutputFile: outFile,
+ WorkspaceStateDirectory: buildWsState,
WorkspaceRoot: workspace,
+ Tool: &pytestTool,
})
if err != nil {
t.Fatalf("PlanBuildModel: %v", err)
}
- modelCmd := exec.CommandContext(ctx, systemPython, modelPlan.Arguments...)
- modelCmd.Dir = workspace
- if modelOut, runErr := modelCmd.CombinedOutput(); runErr != nil {
- t.Fatalf("build_model.py failed: %v\n%s", runErr, modelOut)
+ if modelPlan.Provider == nil || modelPlan.Provider.Method != "lithe/build/model" {
+ t.Fatalf("expected provider modelPlan, got %+v", modelPlan)
+ }
+ modelOp, err := providerClient.Execute(ctx, modelPlan.Provider.Method, modelPlan.Provider.Params, 30_000)
+ if err != nil {
+ t.Fatalf("providerClient.Execute(lithe/build/model): %v", err)
+ }
+ modelRawResult, err := modelOp.Wait(ctx)
+ if err != nil {
+ t.Fatalf("modelOp.Wait: %v", err)
}
decodedModel, err := kernel.DecodeBuildModel(ctx, normalizedManifest, "python", core.BuildDecodeModelRequest{
WorkspaceRoot: workspace,
Root: ".",
- OutputFile: outFile,
+ Result: modelRawResult,
})
if err != nil {
t.Fatalf("DecodeBuildModel: %v", err)
@@ -366,6 +535,133 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
t.Fatalf("expected derived Run entries for ws-cli and main.py, got %+v", decodedModel.Run)
}
+ // 6b. Provider lithe/build/discoverTests -> DecodeBuildTestDiscovery.
+ discPlan, err := kernel.PlanBuildTestDiscovery(ctx, normalizedManifest, "python", core.BuildPlanRequest{
+ Root: ".",
+ WorkspaceRoot: workspace,
+ Tool: &pytestTool,
+ })
+ if err != nil {
+ t.Fatalf("PlanBuildTestDiscovery: %v", err)
+ }
+ if discPlan.Provider == nil || discPlan.Provider.Method != "lithe/build/discoverTests" {
+ t.Fatalf("expected provider testDiscoveryPlan, got %+v", discPlan)
+ }
+ discOp, err := providerClient.Execute(ctx, discPlan.Provider.Method, discPlan.Provider.Params, 45_000)
+ if err != nil {
+ t.Fatalf("providerClient.Execute(lithe/build/discoverTests): %v", err)
+ }
+ discRawResult, err := discOp.Wait(ctx)
+ if err != nil {
+ t.Fatalf("discOp.Wait: %v", err)
+ }
+ decodedDiscovery, err := kernel.DecodeBuildTestDiscovery(ctx, normalizedManifest, "python", core.BuildDecodeTestDiscoveryRequest{
+ Root: ".",
+ Result: discRawResult,
+ })
+ if err != nil {
+ t.Fatalf("DecodeBuildTestDiscovery: %v", err)
+ }
+ if len(decodedDiscovery.Tests) != 3 {
+ t.Fatalf("discovered tests = %+v, want 3 items (test_alpha, test_scale[2-6], test_scale[4-12])", decodedDiscovery.Tests)
+ }
+ var chosenTest *core.BuildDiscoveredTest
+ for i := range decodedDiscovery.Tests {
+ if decodedDiscovery.Tests[i].Suite == "tests/test_sample.py" && decodedDiscovery.Tests[i].Case == "test_scale[2-6]" {
+ chosenTest = &decodedDiscovery.Tests[i]
+ break
+ }
+ }
+ if chosenTest == nil {
+ t.Fatalf("expected discovered parameterized selector tests/test_sample.py :: test_scale[2-6], got %+v", decodedDiscovery.Tests)
+ }
+
+ // 6c. Run that exact single discovered test via PlanBuildTest -> lithe/build/test -> DecodeBuildTestResults!
+ testPlan, err := kernel.PlanBuildTest(ctx, normalizedManifest, "python", core.BuildTestRequest{
+ Root: ".",
+ WorkspaceRoot: workspace,
+ Project: chosenTest.Project,
+ Target: chosenTest.Target,
+ Suite: chosenTest.Suite,
+ Case: chosenTest.Case,
+ Projects: []string{"."},
+ })
+ if err != nil {
+ t.Fatalf("PlanBuildTest: %v", err)
+ }
+ if testPlan.Provider == nil || testPlan.Provider.Method != "lithe/build/test" {
+ t.Fatalf("expected provider testPlan, got %+v", testPlan)
+ }
+ // Attach resolved pytestTool hints to the provider params just as workbench tests.go does.
+ var testProviderParams map[string]any
+ if err := json.Unmarshal(testPlan.Provider.Params, &testProviderParams); err != nil {
+ t.Fatal(err)
+ }
+ testProviderParams["tool"] = map[string]any{"executable": pytestTool.Executable}
+ enrichedTestParams, err := json.Marshal(testProviderParams)
+ if err != nil {
+ t.Fatal(err)
+ }
+ testOp, err := providerClient.Execute(ctx, testPlan.Provider.Method, enrichedTestParams, 60_000)
+ if err != nil {
+ t.Fatalf("providerClient.Execute(lithe/build/test): %v", err)
+ }
+ testRawResult, err := testOp.Wait(ctx)
+ if err != nil {
+ t.Fatalf("testOp.Wait: %v", err)
+ }
+ var execReply struct {
+ ExitCode int `json:"exitCode"`
+ Output string `json:"output"`
+ }
+ if err := json.Unmarshal(testRawResult, &execReply); err != nil {
+ t.Fatal(err)
+ }
+ if execReply.ExitCode != 0 {
+ t.Fatalf("pytest single-case exitCode = %d, output:\n%s", execReply.ExitCode, execReply.Output)
+ }
+ decodedResults, err := kernel.DecodeBuildTestResults(ctx, normalizedManifest, "python", core.BuildTestResultsRequest{
+ WorkspaceRoot: workspace,
+ Root: ".",
+ Project: ".",
+ Projects: []string{"."},
+ Output: execReply.Output,
+ })
+ if err != nil {
+ t.Fatalf("DecodeBuildTestResults: %v", err)
+ }
+ if !decodedResults.Success || decodedResults.Summary.Total != 1 || decodedResults.Summary.Passed != 1 {
+ t.Fatalf("unexpected decoded JUnit XML results: %+v", decodedResults)
+ }
+
+ // Verify Core validated and forwarded structured lithe/log events for both backend and build provider
+ // with zero plugins.diagnostics.rejected events!
+ drained, err := kernel.DrainCoreEvents(ctx)
+ if err != nil {
+ t.Fatalf("DrainCoreEvents: %v", err)
+ }
+ logMu.Lock()
+ captured := slices.Clone(recordedEvents)
+ logMu.Unlock()
+ for _, ev := range drained.Events {
+ op, _ := ev.Fields["operation"].(string)
+ captured = append(captured, fmt.Sprintf("%s:%s", ev.Event, op))
+ if ev.Event == "plugins.diagnostics.rejected" {
+ t.Fatalf("unexpected rejected plugin diagnostic from Core: %+v", ev)
+ }
+ }
+ for _, entry := range captured {
+ if strings.HasPrefix(entry, "plugins.diagnostics.rejected:") {
+ t.Fatalf("unexpected rejected plugin diagnostic in log facts: %v", captured)
+ }
+ }
+ if !slices.Contains(captured, "plugins.operation.finished:pyrefly.resolveLaunch") {
+ t.Fatalf("expected plugins.operation.finished:pyrefly.resolveLaunch in Core log facts, got %v", captured)
+ }
+ if !slices.Contains(captured, "plugins.operation.finished:lithe/build/discoverTests") {
+ t.Fatalf("expected plugins.operation.finished:lithe/build/discoverTests in Core log facts, got %v", captured)
+ }
+
// 7. Verify Python Traceback outputLinkMatchers.
var normalizedDoc struct {
OutputLinkMatchers []core.OutputLinkMatcher `json:"outputLinkMatchers"`
@@ -389,7 +685,8 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
t.Fatalf("unexpected output links: %+v", links)
}
- // 8. Verify .venv toolchain resolution (including workspace trust gating when supported by host).
+ // 8. Verify .venv toolchain resolution (including workspace trust gating) AND Core toolchains.decodeReply
+ // validation of scripts/toolchain_provider.py output!
venvCmd := exec.CommandContext(ctx, systemPython, "-m", "venv", ".venv")
venvCmd.Dir = workspace
if out, err := venvCmd.CombinedOutput(); err != nil {
@@ -436,6 +733,126 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
}
}
+ // Verify real Core toolchains.decodeReply accepts scripts/toolchain_provider.py query_python_toolchains output.
+ extUvRoot := t.TempDir()
+ if resolvedExt, evalErr := filepath.EvalSymlinks(extUvRoot); evalErr == nil {
+ extUvRoot = resolvedExt
+ }
+ extPyHome := filepath.Join(extUvRoot, "cpython-3.12.6")
+ extPyBinDir := filepath.Join(extPyHome, "bin")
+ extPyExe := filepath.Join(extPyBinDir, "python3")
+ if runtime.GOOS == "windows" {
+ extPyBinDir = filepath.Join(extPyHome, "Scripts")
+ extPyExe = filepath.Join(extPyBinDir, "python.exe")
+ }
+ if err := os.MkdirAll(extPyBinDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(extPyExe, []byte("#!/bin/sh\necho Python 3.12.6\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(extPyHome, "pyvenv.cfg"), []byte("version_info = 3.12.6\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ tcReqParams := map[string]any{
+ "operationID": "tc-core-e2e-1",
+ "generation": 1,
+ "providerID": "python",
+ "authority": map[string]any{"kind": "local"},
+ "tools": []string{"python"},
+ "workspace": map[string]any{"rootID": "ws-1", "root": workspace, "directory": "."},
+ "context": map[string]any{"contextID": "ctx-e2e-1", "generation": 1},
+ }
+ tcReqParamsJSON, _ := json.Marshal(tcReqParams)
+ pySnippet := fmt.Sprintf(
+ "import json, sys; sys.path.insert(0, %q); from pathlib import Path; from lithe_rpc import CallContext, CancelToken, DiagnosticsReporter; from toolchain_provider import query_python_toolchains, TOOLCHAIN_PROVIDER_DECLARATION; params = json.loads(sys.argv[1]); ctx = CallContext(cancel_token=CancelToken(), diagnostics=DiagnosticsReporter(lambda _: None, lambda _: True), suppress_cb=lambda: None); out = query_python_toolchains(params, ctx, home_dir=Path(%q), environ={'UV_PYTHON_INSTALL_DIR': %q}); print(json.dumps({'decl': TOOLCHAIN_PROVIDER_DECLARATION, 'reply': out}))",
+ filepath.Join(installedDir, "scripts"),
+ extUvRoot,
+ extUvRoot,
+ )
+ tcOutBytes, err := exec.CommandContext(ctx, systemPython, "-I", "-B", "-c", pySnippet, string(tcReqParamsJSON)).CombinedOutput()
+ if err != nil {
+ t.Fatalf("running toolchain_provider.py failed: %v\n%s", err, tcOutBytes)
+ }
+ var tcBundle struct {
+ Decl json.RawMessage `json:"decl"`
+ Reply json.RawMessage `json:"reply"`
+ }
+ if err := json.Unmarshal(tcOutBytes, &tcBundle); err != nil {
+ t.Fatalf("unmarshaling toolchain_provider output: %v\n%s", err, tcOutBytes)
+ }
+
+ // Build an in-memory manifest variant declaring toolchainProviders + packaged backend so Core toolchains.decodeReply
+ // checks every field, path, installation, and statement emitted by toolchain_provider.py!
+ var tcManifestMap map[string]any
+ if err := json.Unmarshal(normalizedManifest, &tcManifestMap); err != nil {
+ t.Fatal(err)
+ }
+ reqMap, _ := tcManifestMap["requires"].(map[string]any)
+ reqMap["toolchainProviders"] = 0
+ perms, _ := tcManifestMap["permissions"].([]any)
+ tcManifestMap["permissions"] = append(perms, "toolchains.provide")
+ tcManifestMap["backend"] = map[string]any{
+ "launch": map[string]any{"kind": "packaged", "path": expectedPyreflyRel},
+ }
+ tcManifestMap["toolchainProviders"] = []any{tcBundle.Decl}
+ tcManifestBytes, _ := json.Marshal(tcManifestMap)
+ tcRegistryInput, err := toolchain.RegistryInput([]json.RawMessage{tcManifestBytes})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ pyprojectPath := filepath.Join(workspace, "pyproject.toml")
+ pyVerPath := filepath.Join(workspace, ".python-version")
+ condaTxtPath := filepath.Join(extUvRoot, ".conda", "environments.txt")
+ fsFacts := []core.ToolchainFileFact{
+ {Path: workspace, CanonicalPath: workspace, Kind: "directory"},
+ {Path: extUvRoot, CanonicalPath: extUvRoot, Kind: "directory"},
+ {Path: extPyHome, CanonicalPath: extPyHome, Kind: "directory"},
+ {Path: extPyExe, CanonicalPath: extPyExe, Kind: "file", Executable: true},
+ {Path: pyprojectPath, CanonicalPath: pyprojectPath, Kind: "file"},
+ {Path: pyVerPath, CanonicalPath: pyVerPath, Kind: "missing"},
+ {Path: condaTxtPath, CanonicalPath: condaTxtPath, Kind: "missing"},
+ }
+ wireReq, _ := json.Marshal(map[string]any{
+ "jsonrpc": "2.0",
+ "id": "req-1",
+ "method": "toolchains/query",
+ "params": tcReqParams,
+ })
+ wireResp, _ := json.Marshal(map[string]any{
+ "jsonrpc": "2.0",
+ "id": "req-1",
+ "result": tcBundle.Reply,
+ })
+ var decodeReplyOutcome struct {
+ Status string `json:"status"`
+ Error *core.MarketplaceRejection `json:"error"`
+ Snapshot json.RawMessage `json:"snapshot"`
+ }
+ if err := kernel.Execute(ctx, "toolchains.decodeReply", core.ToolchainQuery{
+ Registry: tcRegistryInput,
+ PluginID: pythonSupportPluginID,
+ Request: wireReq,
+ Response: wireResp,
+ CurrentGeneration: 1,
+ Filesystem: fsFacts,
+ Platform: toolchain.PlatformName(runtime.GOOS),
+ WorkspaceRoots: []string{workspace},
+ }, &decodeReplyOutcome); err != nil {
+ t.Fatalf("toolchains.decodeReply failed: %v", err)
+ }
+ if decodeReplyOutcome.Status != "ok" {
+ t.Fatalf("toolchains.decodeReply rejected reply: status=%s err=%+v", decodeReplyOutcome.Status, decodeReplyOutcome.Error)
+ }
+ if !strings.Contains(string(decodeReplyOutcome.Snapshot), "3.12.6") {
+ t.Fatalf("expected decoded toolchain snapshot to include installation 3.12.6, got %s", decodeReplyOutcome.Snapshot)
+ }
+
+ // Shut down backend cleanly BEFORE checking package immutability so any shutdown write would be caught too!
+ service.Host.Stop(pythonSupportPluginID)
+
// 9. Assert installed plugin package file list and SHA-256 hashes are 100% unchanged!
afterDigest := pythonPackageDigest(t, installedDir)
if !maps.Equal(beforeDigest, afterDigest) {
diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json
index 74096ba..ca0926a 100644
--- a/e2e/host/lithe-host.json
+++ b/e2e/host/lithe-host.json
@@ -1,12 +1,12 @@
{
"repository": "https://github.com/1lck/Lithe-IDEA.git",
- "revision": "7c8d0b88d5f622ea6ec425c22f723a6189cb2b04",
+ "revision": "9f4d5fb0597fc54223d85b8f06c9a1032a161bf8",
"packages": {
"./internal/projectgen": "^TestPythonPlugin",
"./internal/workbench": "^TestPythonSupportPlugin"
},
"requiredEnvironment": {
- "LITHE_TEST_PYTHON_PLUGIN_ARCHIVE": "python-support--.zip to install, for example dist/python-support-0.1.1-darwin-arm64.zip"
+ "LITHE_TEST_PYTHON_PLUGIN_ARCHIVE": "python-support--.zip to install, for example dist/python-support-0.2.0-darwin-arm64.zip"
},
"repositoryEnvironment": {
"LITHE_PLUGIN_PYTHON_DIR": "io.github.lithe-idea.python-support"
diff --git a/io.github.lithe-idea.python-support/l10n/zh-Hans.json b/io.github.lithe-idea.python-support/l10n/zh-Hans.json
index 2735c75..61d838f 100644
--- a/io.github.lithe-idea.python-support/l10n/zh-Hans.json
+++ b/io.github.lithe-idea.python-support/l10n/zh-Hans.json
@@ -3,7 +3,7 @@
"settings": {
"pythonExecutable": {
"title": "Python 解释器覆盖路径",
- "description": "显式指定用于构建、运行和 pytest 测试的 Python 解释器路径。留空时自动使用 Python 工具链解析结果(依次查找 .venv、venv、VIRTUAL_ENV、PATH 与已发现安装)。"
+ "description": "显式指定用于构建、运行和 pytest 测试的 Python 解释器路径。留空时自动使用 Python 工具链解析结果(依次查找 .venv、venv、.conda、VIRTUAL_ENV、PATH 与已发现的 conda / uv / pyenv 安装)。"
},
"typeCheckingMode": {
"title": "类型检查模式",
diff --git a/io.github.lithe-idea.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json
index 8065b55..7f1f4e3 100644
--- a/io.github.lithe-idea.python-support/plugin.json
+++ b/io.github.lithe-idea.python-support/plugin.json
@@ -2,7 +2,7 @@
"schemaVersion": 0,
"id": "io.github.lithe-idea.python-support",
"displayName": "Python Support",
- "version": "0.1.1",
+ "version": "0.2.0",
"vendor": {
"id": "io.github.lithe-idea",
"displayName": "Lithe Community",
@@ -11,6 +11,8 @@
"repository": "https://github.com/Lithe-IDEA/lithe-plugin-python",
"pluginAPIVersion": 0,
"requires": {
+ "backend": 0,
+ "buildProviders": 0,
"buildSystems": 0,
"debugAdapters": 0,
"languageServers": 0,
@@ -22,6 +24,7 @@
},
"requiresTools": ["python"],
"permissions": [
+ "backend.launch",
"debug.attach",
"debug.launch",
"languageServer.launch",
@@ -36,6 +39,16 @@
"onDebug:debugpy",
"onLanguage:python"
],
+ "backend": {
+ "launch": {
+ "kind": "runtime",
+ "tool": "python",
+ "minimumVersion": "3.9",
+ "runtimeArguments": ["-I", "-B"],
+ "entry": "scripts/backend.py"
+ },
+ "arguments": ["--state", "${stateDir}"]
+ },
"languages": [
{
"id": "python",
@@ -61,7 +74,7 @@
"environment.yml",
"environment.yaml"
],
- "projectDependencyPaths": [".venv", "venv"]
+ "projectDependencyPaths": [".venv", "venv", ".conda"]
},
"configuration": {
"lineComment": "#",
@@ -85,7 +98,7 @@
"id": "pythonExecutable",
"type": "file",
"title": "Python executable override",
- "description": "Explicit path to the Python interpreter for build, run, and pytest commands. Leave empty to resolve automatically from the Python toolchain (.venv, venv, VIRTUAL_ENV, PATH, or discovered installations).",
+ "description": "Explicit path to the Python interpreter for build, run, and pytest commands. Leave empty to resolve automatically from the Python toolchain (.venv, venv, .conda, VIRTUAL_ENV, PATH, or discovered conda / uv / pyenv installations).",
"default": "",
"effect": "reload",
"page": { "buildSystemID": "python" },
@@ -179,11 +192,10 @@
"languageID": "python",
"languageIdentifier": "python",
"launch": {
- "kind": "packaged",
- "path": "bin/pyrefly"
+ "kind": "backend",
+ "function": "pyrefly.resolveLaunch",
+ "timeoutMilliseconds": 30000
},
- "arguments": ["lsp"],
- "validationArguments": ["--version"],
"workspaceConfiguration": {
"python": {
"pyrefly": {
@@ -221,34 +233,27 @@
],
"discovery": [
{
- "root": { "kind": "absolute", "path": "/opt/homebrew/opt" },
- "pattern": "python@*/libexec",
- "platforms": ["macos"]
+ "root": { "kind": "environment", "variable": "UV_PYTHON_INSTALL_DIR" },
+ "pattern": "*"
},
{
- "root": { "kind": "absolute", "path": "/usr/local/opt" },
- "pattern": "python@*/libexec",
- "platforms": ["macos"]
+ "root": { "kind": "environment", "variable": "XDG_DATA_HOME" },
+ "pattern": "uv/python/*",
+ "platforms": ["macos", "linux"]
},
{
- "root": { "kind": "absolute", "path": "/Library/Frameworks/Python.framework/Versions" },
- "pattern": "*",
- "platforms": ["macos"]
+ "root": { "kind": "home" },
+ "pattern": ".local/share/uv/python/*",
+ "platforms": ["macos", "linux"]
},
{
- "root": { "kind": "absolute", "path": "/" },
- "pattern": "usr",
- "platforms": ["linux"]
+ "root": { "kind": "environment", "variable": "APPDATA" },
+ "pattern": "uv/data/python/*",
+ "platforms": ["windows"]
},
{
- "root": { "kind": "absolute", "path": "/usr" },
- "pattern": "local",
- "platforms": ["linux"]
- },
- {
- "root": { "kind": "environment", "variable": "LOCALAPPDATA" },
- "pattern": "Programs/Python/*",
- "platforms": ["windows"]
+ "root": { "kind": "environment", "variable": "PYENV_ROOT" },
+ "pattern": "versions/*"
},
{
"root": { "kind": "home" },
@@ -261,18 +266,16 @@
"platforms": ["windows"]
},
{
- "root": { "kind": "home" },
- "pattern": ".local/share/uv/python/*",
- "platforms": ["macos", "linux"]
+ "root": { "kind": "environment", "variable": "CONDA_ENVS_PATH" },
+ "pattern": "*"
},
{
- "root": { "kind": "environment", "variable": "APPDATA" },
- "pattern": "uv/data/python/*",
- "platforms": ["windows"]
+ "root": { "kind": "environment", "variable": "CONDA_PREFIX" },
+ "pattern": "envs/*"
},
{
- "root": { "kind": "home" },
- "pattern": "*conda*"
+ "root": { "kind": "environment", "variable": "WORKON_HOME" },
+ "pattern": "*"
},
{
"root": { "kind": "home" },
@@ -280,21 +283,27 @@
},
{
"root": { "kind": "home" },
- "pattern": "miniforge*"
+ "pattern": "miniforge*/envs/*"
},
{
- "root": { "kind": "home" },
- "pattern": "miniforge*/envs/*"
+ "root": { "kind": "absolute", "path": "/opt/homebrew/opt" },
+ "pattern": "python@*/libexec",
+ "platforms": ["macos"]
},
{
- "root": { "kind": "absolute", "path": "/opt" },
- "pattern": "*conda*",
- "platforms": ["macos", "linux"]
+ "root": { "kind": "absolute", "path": "/usr/local/opt" },
+ "pattern": "python@*/libexec",
+ "platforms": ["macos"]
},
{
- "root": { "kind": "absolute", "path": "/opt" },
- "pattern": "*conda*/envs/*",
- "platforms": ["macos", "linux"]
+ "root": { "kind": "absolute", "path": "/Library/Frameworks/Python.framework/Versions" },
+ "pattern": "*",
+ "platforms": ["macos"]
+ },
+ {
+ "root": { "kind": "environment", "variable": "LOCALAPPDATA" },
+ "pattern": "Programs/Python/*",
+ "platforms": ["windows"]
}
],
"commands": ["python3", "python"],
@@ -373,6 +382,33 @@
"requires": ["venv/pyvenv.cfg"],
"platforms": ["windows"]
},
+ {
+ "id": "dot-conda-python3",
+ "kind": "projectFile",
+ "path": ".conda/bin/python3",
+ "home": ".conda",
+ "projectKind": "environment",
+ "requires": [".conda/conda-meta/history"],
+ "platforms": ["macos", "linux"]
+ },
+ {
+ "id": "dot-conda-python",
+ "kind": "projectFile",
+ "path": ".conda/bin/python",
+ "home": ".conda",
+ "projectKind": "environment",
+ "requires": [".conda/conda-meta/history"],
+ "platforms": ["macos", "linux"]
+ },
+ {
+ "id": "dot-conda-windows",
+ "kind": "projectFile",
+ "path": ".conda/python.exe",
+ "home": ".conda",
+ "projectKind": "environment",
+ "requires": [".conda/conda-meta/history"],
+ "platforms": ["windows"]
+ },
{
"id": "project-request",
"kind": "toolchain",
@@ -448,20 +484,21 @@
},
"minimumVersion": "3.9"
},
- "model": {
- "source": "command",
- "arguments": [
- "-I",
- "-B",
- "${pluginDir}/scripts/build_model.py",
- "${root}",
- "${outputFile}"
- ],
- "output": "outputFile",
- "decoder": "litheBuildModel",
- "executesProjectCode": false,
+ "provider": {
+ "launch": {
+ "kind": "runtime",
+ "tool": "python",
+ "minimumVersion": "3.9",
+ "runtimeArguments": ["-I", "-B"],
+ "entry": "scripts/build_provider.py"
+ },
+ "arguments": ["--cache", "${workspaceStateDir}"],
+ "executesProjectCode": true,
"mayUseNetwork": false
},
+ "model": {
+ "source": "provider"
+ },
"tasks": [
{
"id": "pip-install-requirements",
@@ -587,32 +624,12 @@
}
],
"test": {
+ "source": "provider",
"scopes": ["workspace", "project", "target"],
"targetTags": ["test"],
"filters": ["suite", "case"],
- "arguments": [
- "-m",
- "pytest",
- "--junitxml=.pytest_cache/lithe-junit.xml",
- {
- "value": "${target.property:directory}",
- "when": ["targetSelected", "noSuiteSelected"]
- },
- {
- "value": "${test.suite}",
- "when": "suiteSelected"
- },
- {
- "value": "-k",
- "when": "caseSelected"
- },
- {
- "value": "${test.case}",
- "when": "caseSelected"
- },
- "${optionArguments}",
- "${userArguments}"
- ],
+ "discovery": true,
+ "arguments": [],
"results": {
"decoder": "junitXml",
"reports": [".pytest_cache/lithe-junit.xml"]
@@ -641,7 +658,7 @@
"watch": ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt"]
},
"layout": {
- "excluded": [".venv", "venv"],
+ "excluded": [".venv", "venv", ".conda"],
"hiddenDirectoryNames": [
"__pycache__",
".mypy_cache",
diff --git a/io.github.lithe-idea.python-support/scripts/backend.py b/io.github.lithe-idea.python-support/scripts/backend.py
new file mode 100644
index 0000000..bf5d9cd
--- /dev/null
+++ b/io.github.lithe-idea.python-support/scripts/backend.py
@@ -0,0 +1,177 @@
+import os
+import sys
+
+# Never write bytecode into the installed read-only plugin package or user workspace.
+sys.dont_write_bytecode = True
+os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
+
+import argparse
+from pathlib import Path
+import threading
+from typing import Any, Optional
+
+# Ensure sibling scripts are importable under Python 3.11+ `-I` safe_path mode.
+_SCRIPTS_DIR = str(Path(__file__).resolve().parent)
+if _SCRIPTS_DIR not in sys.path:
+ sys.path.insert(0, _SCRIPTS_DIR)
+
+from lithe_rpc import CallContext, JsonRpcServer, PluginError # noqa: E402
+from toolchain_provider import query_python_toolchains # noqa: E402
+
+_VALID_TYPE_CHECKING_MODES = frozenset({"default", "auto", "basic", "strict", "all", "off"})
+_VALID_DISPLAY_TYPE_ERRORS = frozenset({"force-on", "default", "error-missing-imports", "force-off"})
+_VALID_DIAGNOSTIC_MODES = frozenset({"openFilesOnly", "workspace"})
+_VALID_IMPORT_FORMATS = frozenset({"absolute", "relative"})
+
+
+def _enum_setting(settings: dict[str, Any], key: str, allowed: frozenset[str], default: str) -> str:
+ val = settings.get(key)
+ return val if isinstance(val, str) and val in allowed else default
+
+
+def _bool_setting(settings: dict[str, Any], key: str, default: bool) -> bool:
+ val = settings.get(key)
+ return val if isinstance(val, bool) else default
+
+
+def create_backend_server(*, state_dir: Optional[str] = None) -> JsonRpcServer:
+ server = JsonRpcServer(name="python-support-backend", version="0.2.0")
+ degraded_workspaces: set[str] = set()
+ degraded_lock = threading.Lock()
+
+ def _workspace_key(params: dict[str, Any], ctx: CallContext) -> str:
+ if isinstance(ctx.workspace_context, dict) and isinstance(ctx.workspace_context.get("contextID"), str):
+ return ctx.workspace_context["contextID"]
+ ws_state = params.get("workspaceStateDirectory")
+ if isinstance(ws_state, str) and ws_state:
+ return ws_state
+ return state_dir or "default"
+
+ def resolve_pyrefly_launch(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]:
+ server_id = params.get("serverID")
+ if server_id != "python":
+ raise PluginError("python.unknownServer", "Unsupported language server identifier.")
+
+ platform_info = params.get("platform")
+ if isinstance(platform_info, dict) and isinstance(platform_info.get("os"), str):
+ os_name = platform_info["os"].strip().lower()
+ else:
+ os_name = "windows" if sys.platform == "win32" else ("macos" if sys.platform == "darwin" else "linux")
+
+ packaged_path = "bin/pyrefly.exe" if os_name in ("windows", "win32") else "bin/pyrefly"
+
+ raw_settings = params.get("settings")
+ settings = raw_settings if isinstance(raw_settings, dict) else {}
+
+ diagnostic_mode = _enum_setting(settings, "diagnosticMode", _VALID_DIAGNOSTIC_MODES, "openFilesOnly")
+ python_cfg: dict[str, Any] = {
+ "pyrefly": {
+ "typeCheckingMode": _enum_setting(
+ settings,
+ "typeCheckingMode",
+ _VALID_TYPE_CHECKING_MODES,
+ "default",
+ ),
+ "displayTypeErrors": _enum_setting(
+ settings,
+ "displayTypeErrors",
+ _VALID_DISPLAY_TYPE_ERRORS,
+ "force-on",
+ ),
+ "diagnosticMode": diagnostic_mode,
+ },
+ "analysis": {
+ "diagnosticMode": diagnostic_mode,
+ "autoImportCompletions": _bool_setting(settings, "autoImportCompletions", True),
+ "completeFunctionParens": _bool_setting(settings, "completeFunctionParens", False),
+ "importFormat": _enum_setting(settings, "importFormat", _VALID_IMPORT_FORMATS, "absolute"),
+ },
+ }
+
+ ws_key = _workspace_key(params, ctx)
+ hint_degraded = False
+ tools = params.get("tools")
+ if tools is not None:
+ if not isinstance(tools, dict):
+ hint_degraded = True
+ elif "python" in tools and tools["python"] is not None:
+ py_tool = tools["python"]
+ if not isinstance(py_tool, dict):
+ hint_degraded = True
+ else:
+ raw_exec = py_tool.get("executable")
+ if raw_exec is None or raw_exec == "":
+ pass
+ elif (
+ isinstance(raw_exec, str)
+ and raw_exec.strip() == raw_exec
+ and not any(ord(ch) < 32 or ord(ch) == 127 for ch in raw_exec)
+ and len(raw_exec.encode("utf-8")) <= 4096
+ ):
+ python_cfg["pythonPath"] = raw_exec
+ else:
+ hint_degraded = True
+
+ if hint_degraded:
+ with degraded_lock:
+ degraded_workspaces.add(ws_key)
+ ctx.diagnostics.degraded("pyrefly.resolveLaunch", "invalid_tool_hint", 1)
+ else:
+ was_degraded = False
+ with degraded_lock:
+ if ws_key in degraded_workspaces:
+ degraded_workspaces.remove(ws_key)
+ was_degraded = True
+ if was_degraded:
+ ctx.diagnostics.recovered("pyrefly.resolveLaunch", "tool_hint_restored", 1)
+
+ return {
+ "executable": {
+ "kind": "packaged",
+ "path": packaged_path,
+ },
+ "arguments": ["lsp"],
+ "workspaceConfiguration": {
+ "python": python_cfg,
+ },
+ }
+
+ def inspect_environment(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]:
+ ctx.raise_if_cancelled()
+ raw_exec = params.get("executable")
+ if raw_exec is not None:
+ if (
+ not isinstance(raw_exec, str)
+ or not raw_exec.strip()
+ or any(ord(ch) < 32 or ord(ch) == 127 for ch in raw_exec)
+ or not Path(raw_exec).is_absolute()
+ ):
+ raise PluginError("python.invalidExecutable", "Executable must be an absolute path.")
+ target = Path(raw_exec)
+ home = target.parent.parent if target.parent.name.lower() in ("bin", "scripts") else target.parent
+ return {
+ "executable": str(target),
+ "isVirtualEnv": (home / "pyvenv.cfg").is_file() or (home / "conda-meta").is_dir(),
+ }
+ return {
+ "version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
+ "isVirtualEnv": sys.prefix != getattr(sys, "base_prefix", sys.prefix),
+ }
+
+ server.function("pyrefly.resolveLaunch", resolve_pyrefly_launch)
+ server.function("python.inspectEnvironment", inspect_environment)
+ server.suppress_success_diagnostics("python.inspectEnvironment")
+ server.toolchain_provider("python", query_python_toolchains)
+ return server
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(add_help=False)
+ parser.add_argument("--state", dest="state_dir", default=None)
+ known, _ = parser.parse_known_args(argv[1:])
+ server = create_backend_server(state_dir=known.state_dir)
+ return server.listen()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv))
diff --git a/io.github.lithe-idea.python-support/scripts/build_model.py b/io.github.lithe-idea.python-support/scripts/build_model.py
index c445624..418fa9e 100644
--- a/io.github.lithe-idea.python-support/scripts/build_model.py
+++ b/io.github.lithe-idea.python-support/scripts/build_model.py
@@ -8,6 +8,7 @@
# Never write bytecode into the installed read-only plugin directory or the user workspace.
sys.dont_write_bytecode = True
+os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
def _load_tomllib():
@@ -34,6 +35,7 @@ def _load_tomllib():
".svn",
".venv",
"venv",
+ ".conda",
"env",
".env",
"__pycache__",
@@ -144,6 +146,7 @@ def _parse_pyproject(pyproject_path: Path):
"version": None,
"requires_python": None,
"scripts": {},
+ "parse_failed": False,
}
if not pyproject_path.is_file():
return meta
@@ -151,8 +154,10 @@ def _parse_pyproject(pyproject_path: Path):
try:
data = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))
except Exception:
+ meta["parse_failed"] = True
return meta
if not isinstance(data, dict):
+ meta["parse_failed"] = True
return meta
project = data.get("project")
@@ -401,11 +406,14 @@ def _module_name_for_file(rel_posix: str, has_src_dir: bool):
return ".".join(parts), app_dir
-def build_model(root_dir: Path) -> dict:
+def build_model_with_diagnostics(root_dir: Path) -> tuple[dict, list[str]]:
root_real = root_dir.resolve()
py_meta = _parse_pyproject(root_dir / "pyproject.toml")
cfg_meta = _parse_setup_cfg(root_dir / "setup.cfg")
setup_meta = _parse_setup_py(root_dir / "setup.py")
+ degraded_codes: list[str] = []
+ if py_meta.get("parse_failed"):
+ degraded_codes.append("pyproject_parse_failed")
project_name = py_meta["name"] or cfg_meta["name"] or setup_meta["name"] or root_real.name or "python-project"
project_version = py_meta["version"] or cfg_meta["version"] or setup_meta["version"]
@@ -474,7 +482,7 @@ def add_target(name: str, path: str, tags: list[str], properties: dict[str, str]
kept_dirs = []
for d in sorted(dirnames):
child = current_path / d
- if d in (".venv", "venv") and depth == 0:
+ if d in (".venv", "venv", ".conda") and depth == 0:
content_roots.append({"path": d, "kind": "excluded"})
continue
if _should_skip_dir(d):
@@ -605,7 +613,7 @@ def add_target(name: str, path: str, tags: list[str], properties: dict[str, str]
seen_roots.add(key)
deduped_roots.append(root_entry)
- return {
+ model = {
"format": "litheBuildModel",
"version": 0,
"projects": [
@@ -619,6 +627,53 @@ def add_target(name: str, path: str, tags: list[str], properties: dict[str, str]
"tasks": [],
"contentRoots": deduped_roots,
}
+ return model, degraded_codes
+
+
+def build_model(root_dir: Path) -> dict:
+ model, _ = build_model_with_diagnostics(root_dir)
+ return model
+
+
+def inspect_file_entrypoints(root_dir: Path, rel_file_posix: str, project_selection: dict) -> list[dict]:
+ """Static AST inspection of a single Python file for lithe/build/runEntrypoints."""
+ root_real = root_dir.resolve()
+ clean_rel = rel_file_posix.replace("\\", "/").lstrip("/")
+ if not clean_rel or any(part in ("", ".", "..") for part in clean_rel.split("/")):
+ return []
+ fpath = root_dir / Path(*clean_rel.split("/"))
+ if not fpath.is_file() or not _safe_within(root_real, fpath):
+ return []
+ if _is_test_file(clean_rel, fpath.name) or fpath.name == "setup.py":
+ return []
+ tree = _read_ast(fpath)
+ if tree is None:
+ return []
+ facts = _analyze_python_file(tree)
+ has_src_dir = (root_dir / "src").is_dir() and _safe_within(root_real, root_dir / "src")
+ results: list[dict] = []
+
+ if fpath.name == "__main__.py":
+ parent_rel = "/".join(clean_rel.split("/")[:-1])
+ if parent_rel:
+ mod_name, _ = _module_name_for_file(f"{parent_rel}/__init__.py", has_src_dir)
+ if mod_name:
+ results.append({
+ "run": "main",
+ "name": mod_name,
+ "entrypoint": f"module:{mod_name}",
+ "project": project_selection,
+ })
+ return results
+
+ if facts["has_main_guard"]:
+ results.append({
+ "run": "main",
+ "name": clean_rel,
+ "entrypoint": f"script:{clean_rel}",
+ "project": project_selection,
+ })
+ return results
def main(argv: list[str]) -> int:
diff --git a/io.github.lithe-idea.python-support/scripts/build_provider.py b/io.github.lithe-idea.python-support/scripts/build_provider.py
new file mode 100644
index 0000000..8c78d4c
--- /dev/null
+++ b/io.github.lithe-idea.python-support/scripts/build_provider.py
@@ -0,0 +1,619 @@
+import os
+import sys
+
+# Never write bytecode into the installed read-only plugin package or user workspace.
+sys.dont_write_bytecode = True
+os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
+
+import argparse
+import json
+from pathlib import Path
+import shutil
+import tempfile
+import threading
+from typing import Any, Optional
+from urllib.parse import unquote, urlparse
+
+# Ensure sibling scripts are importable under Python 3.11+ `-I` safe_path mode.
+_SCRIPTS_DIR = str(Path(__file__).resolve().parent)
+if _SCRIPTS_DIR not in sys.path:
+ sys.path.insert(0, _SCRIPTS_DIR)
+
+from build_model import ( # noqa: E402
+ _parse_pyproject,
+ _parse_setup_cfg,
+ _parse_setup_py,
+ _safe_within,
+ build_model_with_diagnostics,
+ inspect_file_entrypoints,
+)
+from lithe_rpc import ( # noqa: E402
+ CallContext,
+ JsonRpcServer,
+ MAX_BUILD_RESULT_BYTES,
+ PluginError,
+ run_bounded_process,
+)
+
+_MAX_DISCOVERED_TESTS = 10_000
+_MAX_TEST_SELECTOR_BYTES = 1024
+_JUNIT_REPORT_REL = ".pytest_cache/lithe-junit.xml"
+
+_PYTEST_COLLECTOR_SNIPPET = """
+import json, os, pathlib, sys
+sys.dont_write_bytecode = True
+os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
+
+out_path = pathlib.Path(sys.argv[1])
+cache_dir = sys.argv[2]
+project = json.loads(sys.argv[3])
+max_items, max_bytes, max_selector_bytes = map(int, sys.argv[4:7])
+extra_args = sys.argv[7:]
+
+try:
+ import pytest
+except ModuleNotFoundError:
+ sys.exit(197)
+
+cwd_real = pathlib.Path.cwd().resolve()
+
+def valid_selector(text):
+ try:
+ return (text.strip() and not text.lstrip().startswith("-")
+ and len(text.encode("utf-8")) <= max_selector_bytes
+ and not any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in text))
+ except UnicodeEncodeError:
+ return False
+
+class _LitheTestCollector:
+ def __init__(self):
+ self.items = []
+ self.omitted = 0
+
+ def pytest_collection_finish(self, session):
+ root_real = pathlib.Path(str(session.config.rootpath)).resolve()
+ # Reserve room for JSON keys, counters and the provider response envelope.
+ remaining_bytes = max_bytes - 128
+ for item in session.items:
+ nodeid = getattr(item, "nodeid", "")
+ if not isinstance(nodeid, str) or not nodeid:
+ continue
+ if "::" in nodeid:
+ fpart, cpart = nodeid.split("::", 1)
+ else:
+ fpart, cpart = nodeid, getattr(item, "name", "") or nodeid
+ item_path = getattr(item, "path", None)
+ resolved_suite = None
+ if item_path is not None:
+ try:
+ resolved_suite = pathlib.Path(item_path).resolve().relative_to(cwd_real).as_posix()
+ except Exception:
+ resolved_suite = None
+ if resolved_suite is None:
+ try:
+ resolved_suite = (root_real / fpart).resolve().relative_to(cwd_real).as_posix()
+ except Exception:
+ resolved_suite = None
+ if (
+ resolved_suite
+ and valid_selector(resolved_suite)
+ and valid_selector(cpart)
+ and ":" not in resolved_suite and "\\\\" not in resolved_suite
+ and all(seg not in ("", ".", "..") and not seg.startswith("-") for seg in resolved_suite.split("/"))
+ ):
+ if len(self.items) < max_items:
+ selector = {"suite": resolved_suite, "case": cpart, "project": project}
+ size = len(json.dumps(selector, ensure_ascii=False).encode("utf-8")) + 2
+ if size <= remaining_bytes:
+ self.items.append(selector)
+ remaining_bytes -= size
+ continue
+ self.omitted += 1
+
+args = [
+ "--collect-only",
+ "-q",
+ "--color=no",
+ "-o",
+ "addopts=",
+ "-o",
+ f"cache_dir={cache_dir}",
+ *extra_args,
+]
+collector = _LitheTestCollector()
+raw_code = pytest.main(args, plugins=[collector])
+try:
+ exit_code = int(raw_code)
+except Exception:
+ exit_code = 1
+out_path.write_text(
+ json.dumps({"items": collector.items, "omitted": collector.omitted}, ensure_ascii=False),
+ encoding="utf-8",
+)
+sys.exit(exit_code)
+""".strip()
+
+
+def file_uri_to_path(uri: str) -> Optional[Path]:
+ parsed = urlparse(uri)
+ if parsed.scheme != "file":
+ return None
+ raw_path = unquote(parsed.path or "")
+ if parsed.netloc and parsed.netloc.lower() != "localhost":
+ if os.name == "nt":
+ return Path(f"//{parsed.netloc}{raw_path}")
+ return Path(f"/{parsed.netloc}{raw_path}")
+ # Windows file:///C:/path -> /C:/path -> C:/path
+ if len(raw_path) >= 3 and raw_path[0] == "/" and raw_path[1].isalpha() and raw_path[2] == ":":
+ raw_path = raw_path[1:]
+ return Path(raw_path) if raw_path else None
+
+
+def _strip_dot_slash_prefix(text: str) -> str:
+ while text.startswith("./"):
+ text = text[2:]
+ return text
+
+
+def _normalize_rel_root(raw_root: Any) -> str:
+ if raw_root is None or raw_root in ("", "."):
+ return "."
+ if not isinstance(raw_root, str) or any(ord(c) < 32 or ord(c) == 127 for c in raw_root):
+ raise PluginError("python.invalidRoot", "Invalid build instance root.")
+ cleaned = _strip_dot_slash_prefix(raw_root.replace("\\", "/"))
+ cleaned = cleaned.strip("/")
+ if not cleaned:
+ return "."
+ parts = cleaned.split("/")
+ if any(p in ("", ".", "..") for p in parts):
+ raise PluginError("python.invalidRoot", "Build instance root escapes workspace.")
+ return "/".join(parts)
+
+
+def _validate_safe_rel_selector_path(raw: Any, *, allow_dot: bool = False) -> str:
+ if not isinstance(raw, str) or any(ord(c) < 32 or ord(c) == 127 for c in raw):
+ raise PluginError("python.invalidTestSelector", "The requested test selector path is invalid.")
+ slashed = raw.replace("\\", "/")
+ if slashed.startswith("/") or ":" in slashed:
+ raise PluginError("python.invalidTestSelector", "The requested test selector must be a relative path.")
+ cleaned = _strip_dot_slash_prefix(slashed).rstrip("/")
+ if allow_dot and cleaned in ("", "."):
+ return "."
+ if not cleaned or cleaned.startswith("-"):
+ raise PluginError("python.invalidTestSelector", "The requested test selector path is invalid.")
+ parts = cleaned.split("/")
+ if any(p in ("", ".", "..") or p.startswith("-") for p in parts):
+ raise PluginError("python.invalidTestSelector", "The requested test selector path is invalid.")
+ return "/".join(parts)
+
+
+def _verify_contained_path(instance_dir: Path, instance_real: Path, rel_posix: str, *, expect_dir: bool) -> Path:
+ """
+ Verifies every segment from `instance_dir` to `rel_posix` stays strictly within `instance_real`
+ (rejecting symlinks that escape the instance) and distinguishes boundary violations from missing/stale files.
+ """
+ cur = instance_dir
+ for part in rel_posix.split("/"):
+ cur = cur / part
+ if cur.is_symlink() and not _safe_within(instance_real, cur):
+ raise PluginError("python.invalidTestSelector", "The requested test selector escapes the project root.")
+ if cur.exists() and not _safe_within(instance_real, cur):
+ raise PluginError("python.invalidTestSelector", "The requested test selector escapes the project root.")
+ if expect_dir:
+ if not cur.is_dir():
+ raise PluginError("python.staleTestSelector", "The requested test target directory no longer exists.")
+ else:
+ if not cur.is_file():
+ raise PluginError("python.staleTestSelector", "The requested test suite file no longer exists.")
+ return cur
+
+
+def _project_name_for_dir(instance_dir: Path) -> str:
+ py_meta = _parse_pyproject(instance_dir / "pyproject.toml")
+ if py_meta.get("name"):
+ return py_meta["name"]
+ cfg_meta = _parse_setup_cfg(instance_dir / "setup.cfg")
+ if cfg_meta.get("name"):
+ return cfg_meta["name"]
+ setup_meta = _parse_setup_py(instance_dir / "setup.py")
+ if setup_meta.get("name"):
+ return setup_meta["name"]
+ return instance_dir.name or "python-project"
+
+
+def _resolve_pytest_selector_args(
+ instance_dir: Path,
+ suite: Any,
+ case: Any,
+ target: Optional[dict[str, Any]],
+) -> list[str]:
+ """
+ Validates and maps (suite, case, target) into pytest positional selectors.
+ - A case requires a suite for an exact node ID.
+ - Enforces strict workspace containment (`_safe_within`) on every resolved file/directory.
+ """
+ instance_real = instance_dir.resolve()
+
+ clean_case: Optional[str] = None
+ if case is not None:
+ if suite is None:
+ raise PluginError("python.invalidTestSelector", "A pytest case requires its test suite.")
+ if (
+ not isinstance(case, str)
+ or not case.strip()
+ or len(case) > 1024
+ or any(ord(c) < 32 or ord(c) == 127 for c in case)
+ or case.lstrip().startswith("-")
+ ):
+ raise PluginError("python.invalidTestSelector", "The requested test case selector is invalid.")
+ clean_case = case
+
+ if suite is not None:
+ if (
+ not isinstance(suite, str)
+ or not suite.strip()
+ or len(suite) > 1024
+ or any(ord(c) < 32 or ord(c) == 127 for c in suite)
+ or suite.lstrip().startswith("-")
+ ):
+ raise PluginError("python.invalidTestSelector", "The requested test suite selector is invalid.")
+
+ if ("/" in suite or "\\" in suite or suite.endswith((".py", ".pyi", ".pyw"))
+ or (instance_dir / suite).is_file()):
+ norm_suite = _validate_safe_rel_selector_path(suite, allow_dot=False)
+ _verify_contained_path(instance_dir, instance_real, norm_suite, expect_dir=False)
+ nodeid = f"{norm_suite}::{clean_case}" if clean_case else norm_suite
+ return [nodeid]
+
+ # Dotted JUnit XML classname suite (e.g. "tests.test_calc.TestCalc" or "tests.test_calc").
+ parts = suite.split(".")
+ if not parts or any(not p or p in (".", "..") or p.startswith("-") or "/" in p or "\\" in p for p in parts):
+ raise PluginError("python.invalidTestSelector", "The requested test suite selector is invalid.")
+
+ for idx in range(len(parts), 0, -1):
+ mod_rel = "/".join(parts[:idx]) + ".py"
+ cand = instance_dir / Path(*parts[:idx]).with_suffix(".py")
+ if cand.exists() or cand.is_symlink():
+ _verify_contained_path(instance_dir, instance_real, mod_rel, expect_dir=False)
+ rem = parts[idx:]
+ resolved_base = f"{mod_rel}::{'::'.join(rem)}" if rem else mod_rel
+ nodeid = f"{resolved_base}::{clean_case}" if clean_case else resolved_base
+ return [nodeid]
+
+ raise PluginError("python.staleTestSelector", "The requested test suite could not be resolved in the project.")
+
+ target_dir: Optional[str] = None
+ if isinstance(target, dict):
+ props = target.get("properties")
+ if isinstance(props, dict) and "directory" in props and props["directory"] is not None:
+ norm_target = _validate_safe_rel_selector_path(props["directory"], allow_dot=True)
+ if norm_target != ".":
+ _verify_contained_path(instance_dir, instance_real, norm_target, expect_dir=True)
+ target_dir = norm_target
+
+ return [target_dir] if target_dir else []
+
+
+def create_build_provider_server(*, cache_dir: Optional[str] = None) -> JsonRpcServer:
+ server = JsonRpcServer(name="python-build-provider", version="0.2.0")
+ workspace_root_holder: dict[str, Path] = {"root": Path.cwd().resolve()}
+ owned_temp_dir: Optional[str] = None
+ if cache_dir:
+ cache_root = Path(cache_dir)
+ else:
+ owned_temp_dir = tempfile.mkdtemp(prefix="lithe-python-build-")
+ cache_root = Path(owned_temp_dir)
+
+ degraded_model_roots: set[str] = set()
+ state_lock = threading.Lock()
+
+ def _on_init(params: dict[str, Any]) -> None:
+ folders = params.get("workspaceFolders")
+ if isinstance(folders, list) and folders:
+ first = folders[0]
+ if isinstance(first, dict) and isinstance(first.get("uri"), str):
+ parsed = file_uri_to_path(first["uri"])
+ if parsed is not None and parsed.is_dir():
+ workspace_root_holder["root"] = parsed.resolve()
+ return
+ root_uri = params.get("rootUri")
+ if isinstance(root_uri, str) and root_uri:
+ parsed = file_uri_to_path(root_uri)
+ if parsed is not None and parsed.is_dir():
+ workspace_root_holder["root"] = parsed.resolve()
+ return
+ root_path = params.get("rootPath")
+ if isinstance(root_path, str) and root_path:
+ cand = Path(root_path)
+ if cand.is_dir():
+ workspace_root_holder["root"] = cand.resolve()
+
+ def _on_shutdown() -> None:
+ if owned_temp_dir and os.path.isdir(owned_temp_dir):
+ shutil.rmtree(owned_temp_dir, ignore_errors=True)
+
+ def _resolve_instance(params: dict[str, Any]) -> tuple[str, Path]:
+ ws_root = workspace_root_holder["root"]
+ norm_root = _normalize_rel_root(params.get("root"))
+ inst = ws_root if norm_root == "." else (ws_root / Path(*norm_root.split("/")))
+ if not inst.is_dir() or not _safe_within(ws_root, inst):
+ raise PluginError("python.projectUnavailable", "The Python project directory is unavailable.")
+ return norm_root, inst.resolve()
+
+ def _resolve_runtime_and_env(params: dict[str, Any]) -> tuple[str, dict[str, str]]:
+ python_exec = sys.executable
+ tool = params.get("tool")
+ if isinstance(tool, dict):
+ raw_exec = tool.get("executable")
+ if isinstance(raw_exec, str) and raw_exec.strip():
+ python_exec = raw_exec.strip()
+ options = params.get("options")
+ if isinstance(options, dict):
+ opt_exec = options.get("pythonExecutable")
+ if isinstance(opt_exec, str) and opt_exec.strip():
+ python_exec = opt_exec.strip()
+
+ env = dict(os.environ)
+ raw_env = params.get("environment")
+ if isinstance(raw_env, dict):
+ for k, v in raw_env.items():
+ if isinstance(k, str) and isinstance(v, str) and "\x00" not in k and "\x00" not in v:
+ env[k] = v
+ # Ensure child processes never write bytecode and emit UTF-8 output cleanly.
+ env["PYTHONDONTWRITEBYTECODE"] = "1"
+ env["PYTHONIOENCODING"] = "utf-8"
+ return python_exec, env
+
+ def _string_args(value: Any) -> list[str]:
+ if not isinstance(value, list):
+ return []
+ return [item for item in value if isinstance(item, str) and "\x00" not in item]
+
+ def handle_model(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]:
+ ctx.raise_if_cancelled()
+ norm_root, instance_dir = _resolve_instance(params)
+ model, degraded_codes = build_model_with_diagnostics(instance_dir)
+ if "pyproject_parse_failed" in degraded_codes:
+ with state_lock:
+ degraded_model_roots.add(norm_root)
+ ctx.diagnostics.degraded("lithe/build/model", "pyproject_parse_failed", 1)
+ else:
+ restored = False
+ with state_lock:
+ if norm_root in degraded_model_roots:
+ degraded_model_roots.remove(norm_root)
+ restored = True
+ if restored:
+ ctx.diagnostics.recovered("lithe/build/model", "pyproject_restored", 1)
+ return model
+
+ def handle_discover_tests(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]:
+ ctx.raise_if_cancelled()
+ norm_root, instance_dir = _resolve_instance(params)
+ python_exec, child_env = _resolve_runtime_and_env(params)
+ project_selection = {
+ "name": _project_name_for_dir(instance_dir),
+ "path": norm_root,
+ }
+
+ try:
+ cache_root.mkdir(parents=True, exist_ok=True)
+ pytest_cache_dir = cache_root / "pytest-collect-cache"
+ pytest_cache_dir.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ raise PluginError("python.cacheUnavailable", "Workspace state directory is not writable.") from exc
+
+ timeout_ms = 45_000.0
+ raw_env_timeout = os.environ.get("LITHE_PYTHON_DISCOVER_TIMEOUT_MS")
+ if raw_env_timeout:
+ try:
+ timeout_ms = max(200.0, float(raw_env_timeout))
+ except ValueError:
+ pass
+
+ option_args = _string_args(params.get("optionArguments"))
+ with tempfile.TemporaryDirectory(dir=str(cache_root), prefix="discover-") as run_tmp:
+ out_json_path = Path(run_tmp) / "collected.json"
+ argv = [
+ python_exec,
+ "-B",
+ "-c",
+ _PYTEST_COLLECTOR_SNIPPET,
+ str(out_json_path),
+ str(pytest_cache_dir),
+ json.dumps(project_selection),
+ str(_MAX_DISCOVERED_TESTS),
+ str(MAX_BUILD_RESULT_BYTES),
+ str(_MAX_TEST_SELECTOR_BYTES),
+ *option_args,
+ ]
+ try:
+ exit_code, _output, timed_out = run_bounded_process(
+ argv,
+ cwd=str(instance_dir),
+ env=child_env,
+ cancel_token=ctx.cancel_token,
+ timeout_seconds=timeout_ms / 1000.0,
+ )
+ except FileNotFoundError as exc:
+ raise PluginError(
+ "python.interpreterUnavailable",
+ "The selected Python interpreter could not be started.",
+ ) from exc
+
+ if timed_out:
+ raise PluginError("python.pytestTimedOut", "pytest test discovery timed out.")
+ if exit_code == 197:
+ raise PluginError(
+ "python.pytestUnavailable",
+ "pytest is not installed in the selected Python environment.",
+ )
+ if exit_code == 5:
+ return {
+ "format": "litheTestDiscovery",
+ "version": 0,
+ "tests": [],
+ }
+ if exit_code != 0 or not out_json_path.is_file():
+ raise PluginError(
+ "python.pytestCollectionFailed",
+ "pytest failed to collect tests. Fix syntax or import errors and retry.",
+ )
+
+ try:
+ with out_json_path.open("rb") as collection:
+ data = collection.read(MAX_BUILD_RESULT_BYTES + 1)
+ if len(data) > MAX_BUILD_RESULT_BYTES:
+ raise ValueError("pytest collection report exceeds its byte budget")
+ payload = json.loads(data)
+ items = payload["items"]
+ omitted = payload["omitted"]
+ if (not isinstance(items, list) or len(items) > _MAX_DISCOVERED_TESTS
+ or type(omitted) is not int or omitted < 0):
+ raise ValueError("invalid pytest collection report")
+ except (OSError, ValueError, TypeError, KeyError) as exc:
+ raise PluginError(
+ "python.pytestCollectionFailed",
+ "pytest returned an unreadable test collection payload.",
+ ) from exc
+
+ if omitted:
+ ctx.diagnostics.degraded("lithe/build/discoverTests", "test_discovery_truncated", omitted)
+
+ return {
+ "format": "litheTestDiscovery",
+ "version": 0,
+ "tests": items,
+ }
+
+ def handle_test(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]:
+ ctx.raise_if_cancelled()
+ _norm_root, instance_dir = _resolve_instance(params)
+ python_exec, child_env = _resolve_runtime_and_env(params)
+
+ project_param = params.get("project")
+ run_cwd = instance_dir
+ if isinstance(project_param, dict) and isinstance(project_param.get("path"), str):
+ proj_rel = _normalize_rel_root(project_param["path"])
+ ws_root = workspace_root_holder["root"]
+ cand_dir = ws_root if proj_rel == "." else (ws_root / Path(*proj_rel.split("/")))
+ if not _safe_within(instance_dir, cand_dir):
+ raise PluginError("python.invalidTestSelector", "The requested test project escapes the build instance.")
+ if not cand_dir.is_dir():
+ raise PluginError("python.staleTestSelector", "The requested test project no longer exists.")
+ run_cwd = cand_dir.resolve()
+
+ raw_suite = params["suite"] if "suite" in params else None
+ raw_case = params["case"] if "case" in params else None
+ target = params.get("target") if isinstance(params.get("target"), dict) else None
+ option_args = _string_args(params.get("optionArguments"))
+ user_args = _string_args(params.get("userArguments"))
+
+ # Validate selectors BEFORE touching disk or spawning pytest so stale/invalid selectors reject cleanly.
+ positional_targets = _resolve_pytest_selector_args(run_cwd, raw_suite, raw_case, target)
+
+ junit_file = run_cwd / Path(*_JUNIT_REPORT_REL.split("/"))
+ try:
+ if junit_file.exists():
+ junit_file.unlink()
+ junit_file.parent.mkdir(parents=True, exist_ok=True)
+ except OSError:
+ pass
+
+ argv = [
+ python_exec,
+ "-B",
+ "-m",
+ "pytest",
+ f"--junitxml={_JUNIT_REPORT_REL}",
+ *option_args,
+ *user_args,
+ *(["--", *positional_targets] if positional_targets else []),
+ ]
+
+ timeout_ms = 600_000.0
+ raw_env_timeout = os.environ.get("LITHE_PYTHON_TEST_TIMEOUT_MS")
+ if raw_env_timeout:
+ try:
+ timeout_ms = max(200.0, float(raw_env_timeout))
+ except ValueError:
+ pass
+
+ ctx.progress(message="Running pytest")
+ try:
+ exit_code, output, timed_out = run_bounded_process(
+ argv,
+ cwd=str(run_cwd),
+ env=child_env,
+ cancel_token=ctx.cancel_token,
+ timeout_seconds=timeout_ms / 1000.0,
+ on_output=lambda chunk: ctx.progress(output=chunk),
+ )
+ except FileNotFoundError as exc:
+ raise PluginError(
+ "python.interpreterUnavailable",
+ "The selected Python interpreter could not be started.",
+ ) from exc
+
+ if timed_out:
+ raise PluginError("python.pytestTimedOut", "pytest execution timed out.")
+ # pytest returns usage error (4) for missing node IDs and no tests (5) for
+ # unmatched filters. With a selection, neither fulfills the requested run.
+ if (raw_suite is not None or raw_case is not None) and exit_code in (4, 5):
+ raise PluginError("python.staleTestSelector", "pytest could not run the requested test selection.")
+
+ return {
+ "exitCode": exit_code,
+ "output": output,
+ }
+
+ def handle_run_entrypoints(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]:
+ ctx.raise_if_cancelled()
+ norm_root, instance_dir = _resolve_instance(params)
+ raw_file = params.get("file")
+ if not isinstance(raw_file, str) or not raw_file.strip():
+ return {"format": "litheRunEntrypoints", "version": 0, "entrypoints": []}
+ slashed = raw_file.replace("\\", "/")
+ if slashed.startswith("/") or ":" in slashed:
+ return {"format": "litheRunEntrypoints", "version": 0, "entrypoints": []}
+ clean_file = _strip_dot_slash_prefix(slashed).rstrip("/")
+ if norm_root != ".":
+ prefix = norm_root + "/"
+ if not clean_file.startswith(prefix):
+ return {"format": "litheRunEntrypoints", "version": 0, "entrypoints": []}
+ rel_file = clean_file[len(prefix) :]
+ else:
+ rel_file = clean_file
+ if not rel_file or any(p in ("", ".", "..") for p in rel_file.split("/")):
+ return {"format": "litheRunEntrypoints", "version": 0, "entrypoints": []}
+ project_selection = {
+ "name": _project_name_for_dir(instance_dir),
+ "path": norm_root,
+ }
+ entrypoints = inspect_file_entrypoints(instance_dir, rel_file, project_selection)
+ return {
+ "format": "litheRunEntrypoints",
+ "version": 0,
+ "entrypoints": entrypoints,
+ }
+
+ server.on_initialize(_on_init)
+ server.on_shutdown(_on_shutdown)
+ server.build_handler("lithe/build/model", handle_model)
+ server.build_handler("lithe/build/discoverTests", handle_discover_tests)
+ server.build_handler("lithe/build/test", handle_test)
+ server.build_handler("lithe/build/runEntrypoints", handle_run_entrypoints)
+ server.suppress_success_diagnostics("lithe/build/runEntrypoints")
+ return server
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(add_help=False)
+ parser.add_argument("--cache", dest="cache_dir", default=None)
+ known, _ = parser.parse_known_args(argv[1:])
+ server = create_build_provider_server(cache_dir=known.cache_dir)
+ return server.listen()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv))
diff --git a/io.github.lithe-idea.python-support/scripts/lithe_rpc.py b/io.github.lithe-idea.python-support/scripts/lithe_rpc.py
new file mode 100644
index 0000000..86448fa
--- /dev/null
+++ b/io.github.lithe-idea.python-support/scripts/lithe_rpc.py
@@ -0,0 +1,1184 @@
+import os
+import sys
+
+# Never write bytecode into the installed read-only plugin package or user workspace.
+sys.dont_write_bytecode = True
+os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
+
+from concurrent.futures import ThreadPoolExecutor
+import json
+import re
+import signal
+import subprocess
+import threading
+import time
+from typing import Any, Callable, Optional
+
+FUNCTIONS_VERSION = 0
+BUILD_VERSIONS = (1, 0)
+LOGGING_VERSION = 0
+TOOLCHAINS_VERSION = 0
+
+MAX_SAFE_INTEGER = 9_007_199_254_740_991
+MAX_INCOMING_FRAME_BYTES = 16 * 1024 * 1024
+MAX_IN_FLIGHT_REQUESTS = 32
+MAX_FUNCTION_RESULT_BYTES = 1024 * 1024
+MAX_BUILD_RESULT_BYTES = 32 * 1024 * 1024
+MAX_BUILD_MESSAGE_BYTES = 4096
+MAX_BUILD_OUTPUT_BYTES = 65536
+MAX_ERROR_MESSAGE_BYTES = 1024
+
+ERROR_PARSE = -32700
+ERROR_INVALID_REQUEST = -32600
+ERROR_METHOD_NOT_FOUND = -32601
+ERROR_INVALID_PARAMS = -32602
+ERROR_INTERNAL = -32603
+ERROR_SERVER_NOT_INITIALIZED = -32002
+ERROR_REQUEST_FAILED = -32000
+ERROR_REQUEST_CANCELLED = -32800
+
+TOOLCHAIN_ERROR_CODES = {
+ "plugin.toolchain.methodUnavailable": -32601,
+ "plugin.toolchain.invalidParams": -32602,
+ "plugin.toolchain.cancelled": -32800,
+ "plugin.toolchain.permissionDenied": -32070,
+ "plugin.toolchain.authorityUnsupported": -32071,
+ "plugin.toolchain.timeout": -32072,
+ "plugin.toolchain.providerUnavailable": -32073,
+ "plugin.toolchain.invalidReply": -32074,
+ "plugin.toolchain.limitExceeded": -32075,
+ "plugin.toolchain.unsafePath": -32076,
+ "plugin.toolchain.operationExpired": -32077,
+}
+
+KNOWN_LOGGING_OPERATIONS = frozenset({
+ "initialize",
+ "shutdown",
+ "notification",
+ "function-call",
+ "result-encoding",
+ "lithe/keymap/import",
+ "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",
+})
+
+BUILD_FORMATS = {
+ "lithe/build/model": "litheBuildModel",
+ "lithe/build/dependencies": "litheDependencies",
+ "lithe/build/discoverTests": "litheTestDiscovery",
+ "lithe/build/runEntrypoints": "litheRunEntrypoints",
+}
+
+_LOG_TOKEN_RE = re.compile(r"^[A-Za-z0-9._:/\-$]+$")
+_PLUGIN_ERROR_CODE_RE = re.compile(r"^[A-Za-z][A-Za-z0-9._-]*$")
+_FUNCTION_SEGMENT_RE = re.compile(r"^[a-z][A-Za-z0-9]*$")
+_PROVIDER_ID_RE = re.compile(r"^[a-z][a-z0-9-]{0,63}$")
+
+
+def is_log_token(value: Any, limit: int) -> bool:
+ return (
+ isinstance(value, str)
+ and 0 < len(value.encode("utf-8")) <= limit
+ and _LOG_TOKEN_RE.match(value) is not None
+ )
+
+
+def is_plugin_error_code(value: Any) -> bool:
+ return (
+ isinstance(value, str)
+ and 0 < len(value.encode("utf-8")) <= 64
+ and _PLUGIN_ERROR_CODE_RE.match(value) is not None
+ )
+
+
+def is_function_id(value: Any) -> bool:
+ if not isinstance(value, str) or not value or len(value.encode("utf-8")) > 128:
+ return False
+ return all(_FUNCTION_SEGMENT_RE.match(part) is not None for part in value.split("."))
+
+
+def bounded_utf8(text: Any, limit: int = MAX_ERROR_MESSAGE_BYTES) -> str:
+ value = str(text or "")
+ encoded = value.encode("utf-8")
+ if len(encoded) <= limit:
+ return value
+ return encoded[:limit].decode("utf-8", errors="ignore")
+
+
+def request_key(req_id: Any) -> str:
+ if isinstance(req_id, bool):
+ return f"bool:{req_id}"
+ if isinstance(req_id, int):
+ return f"int:{req_id}"
+ return f"{type(req_id).__name__}:{req_id}"
+
+
+def request_operation_id(operation_id: Any, req_id: Any) -> Optional[str]:
+ if is_log_token(operation_id, 128):
+ return operation_id
+ fallback: Optional[str] = None
+ if isinstance(req_id, str):
+ fallback = req_id
+ elif isinstance(req_id, int) and not isinstance(req_id, bool):
+ fallback = str(req_id)
+ return fallback if is_log_token(fallback, 128) else None
+
+
+class CancelledError(Exception):
+ """Raised when the host cancels an active request or shuts down the session."""
+
+
+class PluginError(Exception):
+ """Controlled user-facing error with a stable pluginErrorCode and zero private paths."""
+
+ def __init__(self, code: str, message: str) -> None:
+ if not is_plugin_error_code(code):
+ raise ValueError(f"Invalid plugin error code: {code!r}")
+ super().__init__(message)
+ self.code = code
+ self.user_message = bounded_utf8(message, MAX_ERROR_MESSAGE_BYTES)
+
+
+class ToolchainQueryError(Exception):
+ """Typed JSON-RPC error matching shared/plugins/contract/v1/toolchains/README.md."""
+
+ def __init__(
+ self,
+ stable_code: str,
+ message: str,
+ operation_id: str,
+ provider_id: str,
+ details: Optional[dict[str, Any]] = None,
+ ) -> None:
+ if stable_code not in TOOLCHAIN_ERROR_CODES:
+ raise ValueError(f"Unknown toolchain error code: {stable_code!r}")
+ super().__init__(message)
+ self.stable_code = stable_code
+ self.rpc_code = TOOLCHAIN_ERROR_CODES[stable_code]
+ self.user_message = bounded_utf8(message, MAX_ERROR_MESSAGE_BYTES) or "Toolchain query failed."
+ self.operation_id = operation_id
+ self.provider_id = provider_id
+ self.details = details
+
+
+class FramingError(Exception):
+ """Raised when the incoming stdio stream violates Content-Length framing."""
+
+
+class CancelToken:
+ """Shares cancellation with a queued or running request."""
+
+ def __init__(self) -> None:
+ self._event = threading.Event()
+
+ @property
+ def cancelled(self) -> bool:
+ return self._event.is_set()
+
+ def raise_if_cancelled(self) -> None:
+ if self._event.is_set():
+ raise CancelledError("Request cancelled")
+
+ def wait(self, timeout: float) -> bool:
+ return self._event.wait(timeout)
+
+ def cancel(self) -> None:
+ self._event.set()
+
+
+def run_bounded_process(
+ argv: list[str],
+ *,
+ cwd: str,
+ env: dict[str, str],
+ cancel_token: CancelToken,
+ timeout_seconds: float,
+ max_output_bytes: int = 8 * 1024 * 1024,
+ on_output: Optional[Callable[[str], None]] = None,
+) -> tuple[int, str, bool]:
+ """
+ Runs a child process in its own process group with bounded timeout, bounded output,
+ and immediate termination on request cancellation.
+ Returns (exit_code, combined_output, timed_out).
+ """
+ cancel_token.raise_if_cancelled()
+ job = None
+ if os.name == "nt":
+ from windows_job import WindowsJob
+
+ job = WindowsJob()
+ try:
+ # A Windows virtualenv redirector can create a child before its
+ # interpreter starts. The base executable keeps bootstrap atomic.
+ proc = job.start(sys._base_executable, argv, cwd=cwd, env=env)
+ except Exception:
+ job.close()
+ raise
+ else:
+ proc = subprocess.Popen(
+ argv, cwd=cwd, env=env, stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ chunks: list[bytes] = []
+ captured_bytes = 0
+ lock = threading.Lock()
+
+ def _reader() -> None:
+ nonlocal captured_bytes
+ stream = proc.stdout
+ if stream is None:
+ return
+ try:
+ while True:
+ data = stream.read1(4096)
+ if not data:
+ break
+ text_chunk: Optional[str] = None
+ with lock:
+ if captured_bytes < max_output_bytes:
+ remaining = max_output_bytes - captured_bytes
+ kept = data[:remaining]
+ chunks.append(kept)
+ captured_bytes += len(kept)
+ text_chunk = kept.decode("utf-8", errors="replace")
+ if text_chunk and on_output is not None:
+ on_output(text_chunk)
+ except Exception:
+ pass
+ finally:
+ try:
+ stream.close()
+ except Exception:
+ pass
+
+ reader_thread = threading.Thread(target=_reader, daemon=True)
+ deadline = time.monotonic() + max(0.1, timeout_seconds)
+ timed_out = False
+ try:
+ reader_thread.start()
+ while proc.poll() is None:
+ cancel_token.raise_if_cancelled()
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ timed_out = True
+ break
+ try:
+ proc.wait(timeout=min(0.05, remaining))
+ except subprocess.TimeoutExpired:
+ continue
+ finally:
+ # The request owns the whole group, even after its direct child exits.
+ # Closing the Windows job or killing the POSIX group releases inherited
+ # output handles left open by surviving descendants before draining.
+ if job is not None:
+ job.close()
+ else:
+ try:
+ os.killpg(proc.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ proc.wait(timeout=2.0)
+ if reader_thread.ident is None:
+ proc.stdout.close()
+ else:
+ reader_thread.join(timeout=2.0)
+
+ cancel_token.raise_if_cancelled()
+ exit_code = proc.returncode
+ with lock:
+ output = b"".join(chunks).decode("utf-8", errors="replace")
+ return exit_code, output, timed_out
+
+
+class DiagnosticsReporter:
+ """Emits validated lithe/log notifications with controlled category codes only."""
+
+ def __init__(
+ self,
+ send_fn: Callable[[dict[str, Any]], None],
+ is_registered_fn: Callable[[str], bool],
+ operation_id: Optional[str] = None,
+ ) -> None:
+ self._send = send_fn
+ self._is_registered = is_registered_fn
+ self._operation_id = operation_id
+
+ def _record(
+ self,
+ kind: str,
+ operation: str,
+ code: Optional[str] = None,
+ count: Optional[int] = None,
+ duration_ms: Optional[int] = None,
+ ) -> None:
+ if operation not in KNOWN_LOGGING_OPERATIONS and not self._is_registered(operation):
+ raise ValueError(f"Unregistered diagnostic operation: {operation!r}")
+ if code is not None and not is_log_token(code, 64):
+ raise ValueError(f"Invalid controlled diagnostic code: {code!r}")
+ if count is not None and (isinstance(count, bool) or not isinstance(count, int) or count < 0 or count > MAX_SAFE_INTEGER):
+ raise ValueError(f"Invalid diagnostic count: {count!r}")
+ wire_op = operation if len(operation.encode("utf-8")) <= 64 else "function-call"
+ params: dict[str, Any] = {
+ "kind": kind,
+ "operation": wire_op,
+ }
+ if code is not None:
+ params["code"] = code
+ if count is not None:
+ params["count"] = count
+ if duration_ms is not None:
+ clamped = min(MAX_SAFE_INTEGER, max(0, int(duration_ms)))
+ params["durationMs"] = clamped
+ if self._operation_id is not None and is_log_token(self._operation_id, 128):
+ params["operationId"] = self._operation_id
+ self._send(params)
+
+ def degraded(self, operation: str, code: str, count: Optional[int] = None) -> None:
+ self._record("degraded", operation, code=code, count=count)
+
+ def recovered(self, operation: str, code: str, count: Optional[int] = None) -> None:
+ self._record("recovered", operation, code=code, count=count)
+
+ def terminal(self, operation: str, error_code: Optional[str], duration_ms: float) -> None:
+ if error_code is not None:
+ safe_code = error_code if is_log_token(error_code, 64) else "internal_error"
+ self._record("operationFailed", operation, code=safe_code, duration_ms=int(duration_ms))
+ else:
+ self._record("operationFinished", operation, duration_ms=int(duration_ms))
+
+
+class CallContext:
+ """Per-request execution context passed to function, build, and toolchain handlers."""
+
+ def __init__(
+ self,
+ *,
+ cancel_token: CancelToken,
+ diagnostics: DiagnosticsReporter,
+ suppress_cb: Callable[[], None],
+ operation_id: Optional[str] = None,
+ progress_cb: Optional[Callable[[dict[str, Any]], None]] = None,
+ workspace_context: Optional[dict[str, Any]] = None,
+ ) -> None:
+ self.cancel_token = cancel_token
+ self.diagnostics = diagnostics
+ self._suppress_cb = suppress_cb
+ self.operation_id = operation_id
+ self._progress_cb = progress_cb
+ self.workspace_context = workspace_context
+
+ def suppress_success_diagnostics(self) -> None:
+ self._suppress_cb()
+
+ def raise_if_cancelled(self) -> None:
+ self.cancel_token.raise_if_cancelled()
+
+ def progress(
+ self,
+ *,
+ message: Optional[str] = None,
+ percentage: Optional[int] = None,
+ output: Optional[str] = None,
+ ) -> None:
+ if self._progress_cb is not None and not self.cancel_token.cancelled:
+ payload: dict[str, Any] = {}
+ if message is not None:
+ payload["message"] = message
+ if percentage is not None:
+ payload["percentage"] = percentage
+ if output is not None:
+ payload["output"] = output
+ self._progress_cb(payload)
+
+
+class _MalformedJsonSentinel:
+ pass
+
+
+_MALFORMED_JSON = _MalformedJsonSentinel()
+
+
+class FrameDecoder:
+ """Incremental Content-Length JSON-RPC frame parser."""
+
+ def __init__(self) -> None:
+ self._buf = bytearray()
+
+ def push(self, chunk: bytes) -> list[Any]:
+ self._buf.extend(chunk)
+ messages: list[Any] = []
+ while True:
+ sep = self._buf.find(b"\r\n\r\n")
+ if sep < 0:
+ if len(self._buf) > 65536:
+ raise FramingError("Header exceeds 64 KiB without CRLFCRLF terminator")
+ break
+ header_bytes = bytes(self._buf[:sep])
+ content_length: Optional[int] = None
+ for raw_line in header_bytes.split(b"\r\n"):
+ if not raw_line:
+ continue
+ colon = raw_line.find(b":")
+ if colon <= 0:
+ raise FramingError("Malformed header line")
+ name = raw_line[:colon].strip().lower()
+ val = raw_line[colon + 1 :].strip()
+ if name == b"content-length":
+ if not val.isdigit():
+ raise FramingError("Invalid Content-Length")
+ content_length = int(val)
+ if content_length is None or content_length > MAX_INCOMING_FRAME_BYTES:
+ raise FramingError("Missing or oversized Content-Length")
+ total = sep + 4 + content_length
+ if len(self._buf) < total:
+ break
+ body = bytes(self._buf[sep + 4 : total])
+ del self._buf[:total]
+ try:
+ messages.append(json.loads(body.decode("utf-8")))
+ except Exception:
+ messages.append(_MALFORMED_JSON)
+ return messages
+
+
+def encode_frame(payload: dict[str, Any]) -> bytes:
+ raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
+ header = f"Content-Length: {len(raw)}\r\n\r\n".encode("ascii")
+ return header + raw
+
+
+class JsonRpcServer:
+ """
+ Pure-Python Lithe plugin backend / build provider stdio JSON-RPC server.
+ Implements litheLogging 0, litheFunctions 0, litheBuild 0/1, and litheToolchains 0.
+ """
+
+ def __init__(self, *, name: str, version: str = "0.2.0") -> None:
+ self.name = name
+ self.version = version
+ self._functions: dict[str, Callable[[dict[str, Any], CallContext], Any]] = {}
+ self._build_handlers: dict[str, Callable[[dict[str, Any], CallContext], Any]] = {}
+ self._toolchain_providers: dict[str, Callable[[dict[str, Any], CallContext], Any]] = {}
+ self._quiet_success: set[str] = set()
+ self._initialize_hooks: list[Callable[[dict[str, Any]], None]] = []
+ self._shutdown_hooks: list[Callable[[], None]] = []
+
+ self._phase = "idle"
+ self._logging_negotiated = False
+ self._logging_ready = False
+ self._early_diagnostics: list[dict[str, Any]] = []
+ self._functions_version: Optional[int] = None
+ self._build_version: Optional[int] = None
+ self._selected_toolchain_providers: set[str] = set()
+ self.initialize_params: Optional[dict[str, Any]] = None
+
+ self._write_lock = threading.Lock()
+ self._state_lock = threading.Lock()
+ self._incoming: dict[str, CancelToken] = {}
+ self._output_stream: Any = None
+ self._error_stream: Any = sys.stderr
+ self._exit_code: Optional[int] = None
+ self._done_event = threading.Event()
+ self._executor = ThreadPoolExecutor(max_workers=8, thread_name_prefix=f"{name}-worker")
+
+ def function(self, fn_id: str, handler: Callable[[dict[str, Any], CallContext], Any]) -> "JsonRpcServer":
+ if not is_function_id(fn_id):
+ raise ValueError(f"Invalid function ID: {fn_id!r}")
+ if fn_id in self._functions:
+ raise ValueError(f"Duplicate function ID: {fn_id!r}")
+ self._functions[fn_id] = handler
+ return self
+
+ def build_handler(self, method: str, handler: Callable[[dict[str, Any], CallContext], Any]) -> "JsonRpcServer":
+ if not method.startswith("lithe/build/"):
+ raise ValueError(f"Invalid build method: {method!r}")
+ self._build_handlers[method] = handler
+ return self
+
+ def toolchain_provider(
+ self,
+ provider_id: str,
+ handler: Callable[[dict[str, Any], CallContext], Any],
+ ) -> "JsonRpcServer":
+ if not _PROVIDER_ID_RE.match(provider_id):
+ raise ValueError(f"Invalid toolchain provider ID: {provider_id!r}")
+ self._toolchain_providers[provider_id] = handler
+ return self
+
+ def suppress_success_diagnostics(self, operation: str) -> "JsonRpcServer":
+ if operation not in KNOWN_LOGGING_OPERATIONS and operation not in self._functions:
+ raise ValueError(f"Cannot suppress unknown operation: {operation!r}")
+ self._quiet_success.add(operation)
+ return self
+
+ def on_initialize(self, hook: Callable[[dict[str, Any]], None]) -> "JsonRpcServer":
+ self._initialize_hooks.append(hook)
+ return self
+
+ def on_shutdown(self, hook: Callable[[], None]) -> "JsonRpcServer":
+ self._shutdown_hooks.append(hook)
+ return self
+
+ @property
+ def diagnostics(self) -> DiagnosticsReporter:
+ return self._make_diagnostics(None)
+
+ def _make_diagnostics(self, operation_id: Optional[str]) -> DiagnosticsReporter:
+ def _send(params: dict[str, Any]) -> None:
+ with self._state_lock:
+ if not self._logging_negotiated or self._phase == "exited":
+ return
+ if not self._logging_ready:
+ if len(self._early_diagnostics) < 8:
+ self._early_diagnostics.append(params)
+ return
+ self._write_frame({"jsonrpc": "2.0", "method": "lithe/log", "params": params})
+
+ return DiagnosticsReporter(_send, lambda op: op in self._functions, operation_id)
+
+ def _write_frame(self, message: dict[str, Any]) -> None:
+ with self._write_lock:
+ if self._output_stream is None or self._phase == "exited":
+ return
+ data = encode_frame(message)
+ self._output_stream.write(data)
+ self._output_stream.flush()
+
+ def _write_stderr_category(self, category: str, detail: Optional[str] = None) -> None:
+ try:
+ suffix = f" ({detail})" if detail else ""
+ self._error_stream.write(f"{self.name}: {category}{suffix}\n")
+ self._error_stream.flush()
+ except Exception:
+ pass
+
+ def _respond(self, req_id: Any, result: Any = None, error: Optional[dict[str, Any]] = None) -> None:
+ if self._phase == "exited":
+ return
+ try:
+ if error is not None:
+ self._write_frame({"jsonrpc": "2.0", "id": req_id, "error": error})
+ else:
+ self._write_frame({"jsonrpc": "2.0", "id": req_id, "result": result})
+ except Exception:
+ self.diagnostics.terminal("result-encoding", "result_encoding_failed", 0)
+ self._write_frame({
+ "jsonrpc": "2.0",
+ "id": req_id,
+ "error": {
+ "code": ERROR_INTERNAL,
+ "message": "The plugin backend failed unexpectedly.",
+ },
+ })
+
+ def _abort_all(self) -> None:
+ with self._state_lock:
+ tokens = list(self._incoming.values())
+ self._incoming.clear()
+ for token in tokens:
+ token.cancel()
+
+ def _finish(self, code: int) -> None:
+ with self._state_lock:
+ if self._phase == "exited":
+ return
+ self._phase = "exited"
+ self._exit_code = code
+ self._abort_all()
+ self._done_event.set()
+
+ def listen(
+ self,
+ *,
+ input_stream: Any = None,
+ output_stream: Any = None,
+ error_stream: Any = None,
+ ) -> int:
+ if self._phase != "idle":
+ raise RuntimeError("Server can listen only once")
+ in_raw = input_stream if input_stream is not None else sys.stdin.buffer
+ out_raw = output_stream if output_stream is not None else sys.stdout.buffer
+ err_out = error_stream if error_stream is not None else sys.stderr
+
+ # Redirect Python-level sys.stdout to stderr so accidental print() calls never corrupt frames.
+ if output_stream is None:
+ sys.stdout = err_out # type: ignore[assignment]
+
+ self._output_stream = out_raw
+ self._error_stream = err_out
+ self._phase = "listening"
+
+ decoder = FrameDecoder()
+ try:
+ while not self._done_event.is_set():
+ chunk = in_raw.read1(8192) if hasattr(in_raw, "read1") else in_raw.read(8192)
+ if not chunk:
+ self._finish(0 if self._phase == "shuttingDown" else 1)
+ break
+ try:
+ messages = decoder.push(chunk)
+ except FramingError:
+ self.diagnostics.terminal("notification", "framing_error", 0)
+ self._finish(1)
+ break
+ for msg in messages:
+ if self._done_event.is_set():
+ break
+ self._dispatch(msg)
+ finally:
+ if self._phase != "exited":
+ self._finish(1)
+ self._executor.shutdown(wait=False, cancel_futures=True)
+ return self._exit_code if self._exit_code is not None else 0
+
+ def _dispatch(self, message: Any) -> None:
+ if message is _MALFORMED_JSON:
+ self._respond(None, error={"code": ERROR_PARSE, "message": "The message is not valid JSON."})
+ return
+ if not isinstance(message, dict):
+ self._respond(None, error={"code": ERROR_INVALID_REQUEST, "message": "The message is not a JSON-RPC object."})
+ return
+
+ has_id = "id" in message and message["id"] is not None
+ method = message.get("method")
+ if not isinstance(method, str):
+ return
+ if has_id:
+ self._handle_request(message["id"], method, message.get("params"))
+ else:
+ self._handle_notification(method, message.get("params"))
+
+ def _handle_notification(self, method: str, params: Any) -> None:
+ if method == "exit":
+ self._finish(0 if self._phase == "shuttingDown" else 1)
+ return
+ if method == "$/cancelRequest":
+ if isinstance(params, dict) and "id" in params:
+ key = request_key(params["id"])
+ with self._state_lock:
+ token = self._incoming.get(key)
+ if token is not None:
+ token.cancel()
+ return
+
+ def _handle_request(self, req_id: Any, method: str, params: Any) -> None:
+ if method == "initialize":
+ self._handle_initialize(req_id, params if isinstance(params, dict) else {})
+ return
+ if method == "shutdown":
+ self._handle_shutdown(req_id)
+ return
+ if self._phase in ("listening", "initializing"):
+ self._respond(
+ req_id,
+ error={"code": ERROR_SERVER_NOT_INITIALIZED, "message": "The backend is not initialized."},
+ )
+ return
+ if self._phase != "ready":
+ self._respond(
+ req_id,
+ error={"code": ERROR_INVALID_REQUEST, "message": "The backend is shutting down."},
+ )
+ return
+
+ if method == "lithe/function/invoke":
+ self._submit(req_id, self._invoke_function, params)
+ return
+ if method in self._build_handlers and self._build_version is not None:
+ if method == "lithe/build/runEntrypoints" and self._build_version < 1:
+ self._respond(
+ req_id,
+ error={"code": ERROR_METHOD_NOT_FOUND, "message": "The requested method is not supported."},
+ )
+ return
+ self._submit(req_id, self._invoke_build, method, params)
+ return
+ if method == "toolchains/query" and self._selected_toolchain_providers:
+ self._submit(req_id, self._invoke_toolchain_query, params)
+ return
+
+ self._respond(
+ req_id,
+ error={"code": ERROR_METHOD_NOT_FOUND, "message": "The requested method is not supported."},
+ )
+
+ def _submit(self, req_id: Any, invoke: Callable[..., None], *args: Any) -> None:
+ key = request_key(req_id)
+ token = CancelToken()
+ with self._state_lock:
+ admitted = key not in self._incoming and len(self._incoming) < MAX_IN_FLIGHT_REQUESTS
+ if admitted:
+ self._incoming[key] = token
+ if not admitted:
+ self._respond(
+ req_id,
+ error={"code": ERROR_INVALID_REQUEST, "message": "The backend cannot accept this request."},
+ )
+ return
+
+ def run() -> None:
+ try:
+ invoke(req_id, token, *args)
+ finally:
+ with self._state_lock:
+ self._incoming.pop(key, None)
+
+ self._executor.submit(run)
+
+ def _handle_initialize(self, req_id: Any, params: dict[str, Any]) -> None:
+ if self._phase != "listening":
+ self._respond(
+ req_id,
+ error={"code": ERROR_INVALID_REQUEST, "message": "initialize was already received."},
+ )
+ return
+ self._phase = "initializing"
+ self.initialize_params = params
+ capabilities = params.get("capabilities")
+ offered = capabilities.get("experimental") if isinstance(capabilities, dict) else None
+ if not isinstance(offered, dict):
+ offered = {}
+
+ def _offers(entry: Any, version: int) -> bool:
+ return (
+ isinstance(entry, dict)
+ and isinstance(entry.get("versions"), list)
+ and any(not isinstance(v, bool) and v == version for v in entry["versions"])
+ )
+
+ if not _offers(offered.get("litheLogging"), LOGGING_VERSION):
+ self._phase = "listening"
+ self._respond(
+ req_id,
+ error={
+ "code": ERROR_INVALID_REQUEST,
+ "message": f"The backend requires litheLogging version {LOGGING_VERSION}.",
+ },
+ )
+ return
+
+ self._logging_negotiated = True
+ self._logging_ready = False
+ self._early_diagnostics = []
+
+ build_ver: Optional[int] = None
+ if self._build_handlers:
+ for candidate_ver in BUILD_VERSIONS:
+ if _offers(offered.get("litheBuild"), candidate_ver):
+ build_ver = candidate_ver
+ break
+ self._build_version = build_ver
+
+ self._functions_version = FUNCTIONS_VERSION if _offers(offered.get("litheFunctions"), FUNCTIONS_VERSION) else None
+
+ self._selected_toolchain_providers = set()
+ tc_offer = offered.get("litheToolchains")
+ if _offers(tc_offer, TOOLCHAINS_VERSION) and isinstance(tc_offer, dict):
+ raw_providers = tc_offer.get("providers")
+ if isinstance(raw_providers, list) and len(raw_providers) <= 8:
+ for p_id in raw_providers:
+ if isinstance(p_id, str) and p_id in self._toolchain_providers:
+ self._selected_toolchain_providers.add(p_id)
+
+ try:
+ for hook in self._initialize_hooks:
+ hook(params)
+ except PluginError as err:
+ self._phase = "listening"
+ self._respond(
+ req_id,
+ error={"code": ERROR_REQUEST_FAILED, "message": err.user_message, "data": {"code": err.code}},
+ )
+ return
+ except Exception as exc:
+ self._phase = "listening"
+ self._write_stderr_category("initialize_failed", type(exc).__name__)
+ self._respond(
+ req_id,
+ error={"code": ERROR_INTERNAL, "message": "The plugin backend failed unexpectedly."},
+ )
+ return
+
+ if self._functions and self._functions_version is None:
+ self.diagnostics.degraded("initialize", "functions_unavailable")
+
+ experimental: dict[str, Any] = {
+ "litheLogging": {"version": LOGGING_VERSION},
+ }
+ if self._build_version is not None:
+ experimental["litheBuild"] = {"version": self._build_version}
+ if self._functions_version is not None:
+ experimental["litheFunctions"] = {
+ "version": self._functions_version,
+ "functions": [{"id": fn_id} for fn_id in sorted(self._functions)],
+ }
+ if self._selected_toolchain_providers:
+ experimental["litheToolchains"] = {
+ "version": TOOLCHAINS_VERSION,
+ "providers": sorted(self._selected_toolchain_providers),
+ }
+
+ with self._state_lock:
+ self._phase = "ready"
+ self._respond(
+ req_id,
+ result={
+ "capabilities": {"experimental": experimental},
+ "serverInfo": {"name": self.name, "version": self.version},
+ },
+ )
+ with self._state_lock:
+ self._logging_ready = True
+ early = list(self._early_diagnostics)
+ self._early_diagnostics.clear()
+ for diag_params in early:
+ self._write_frame({"jsonrpc": "2.0", "method": "lithe/log", "params": diag_params})
+
+ def _handle_shutdown(self, req_id: Any) -> None:
+ if self._phase not in ("ready", "listening", "initializing"):
+ self._respond(
+ req_id,
+ error={"code": ERROR_INVALID_REQUEST, "message": "shutdown was already received."},
+ )
+ return
+ self._phase = "shuttingDown"
+ self._abort_all()
+ for hook in self._shutdown_hooks:
+ try:
+ hook()
+ except Exception as exc:
+ self._write_stderr_category("shutdown_hook_failed", type(exc).__name__)
+ self.diagnostics.terminal("shutdown", "internal_error", 0)
+ self._respond(req_id, result=None)
+
+ def _invoke_function(self, req_id: Any, token: CancelToken, raw_params: Any) -> None:
+ if not isinstance(raw_params, dict):
+ self._respond(req_id, error={"code": ERROR_INVALID_PARAMS, "message": "Function invoke requires object params."})
+ return
+ fn_id = raw_params.get("functionID")
+ handler = self._functions.get(fn_id) if self._functions_version is not None and isinstance(fn_id, str) else None
+ if handler is None:
+ self._respond(
+ req_id,
+ error={"code": ERROR_INVALID_PARAMS, "message": "The requested plugin function is not registered."},
+ )
+ return
+
+ op_id = raw_params.get("operationID")
+ call_params = raw_params.get("params")
+ if call_params is None:
+ call_params = {}
+ if not isinstance(call_params, dict):
+ self._respond(req_id, error={"code": ERROR_INVALID_PARAMS, "message": "Function params must be an object."})
+ return
+ ws_ctx = raw_params.get("context") if isinstance(raw_params.get("context"), dict) else None
+
+ reporting = True
+
+ def _progress(payload: dict[str, Any]) -> None:
+ if not reporting or not isinstance(op_id, str) or not op_id:
+ return
+ report: dict[str, Any] = {"operationID": op_id}
+ if "message" in payload:
+ report["message"] = bounded_utf8(payload["message"], MAX_ERROR_MESSAGE_BYTES)
+ if "percentage" in payload and isinstance(payload["percentage"], (int, float)):
+ report["percentage"] = min(100, max(0, int(round(payload["percentage"]))))
+ self._write_frame({"jsonrpc": "2.0", "method": "lithe/function/progress", "params": report})
+
+ def _shape_function(value: Any) -> Any:
+ encoded = json.dumps(value, ensure_ascii=False).encode("utf-8")
+ if len(encoded) > MAX_FUNCTION_RESULT_BYTES:
+ raise ValueError("Function result exceeds 1 MiB limit")
+ return value
+
+ def _stop_reporting() -> None:
+ nonlocal reporting
+ reporting = False
+
+ self._execute_tracked(
+ req_id=req_id,
+ token=token,
+ operation=fn_id,
+ wire_op_id=op_id,
+ invoke=lambda ctx: handler(call_params, ctx),
+ shape=_shape_function,
+ on_settled=_stop_reporting,
+ progress_cb=_progress,
+ workspace_context=ws_ctx,
+ emit_logging=True,
+ )
+
+ def _invoke_build(self, req_id: Any, token: CancelToken, method: str, raw_params: Any) -> None:
+ progressing = method in (
+ "lithe/build/execute",
+ "lithe/build/test",
+ "lithe/build/prepareRun",
+ "lithe/build/prepareDebug",
+ )
+ if not isinstance(raw_params, dict) or (progressing and not isinstance(raw_params.get("operationID"), str)):
+ self._respond(
+ req_id,
+ error={"code": ERROR_INVALID_PARAMS, "message": "A build request needs object params and its wire operationID."},
+ )
+ return
+
+ handler = self._build_handlers[method]
+ op_id = raw_params.get("operationID")
+ reporting = True
+
+ def _progress(payload: dict[str, Any]) -> None:
+ if not reporting or not progressing or not isinstance(op_id, str):
+ return
+ report: dict[str, Any] = {"operationID": op_id}
+ if "message" in payload:
+ report["message"] = bounded_utf8(payload["message"], MAX_BUILD_MESSAGE_BYTES)
+ if "output" in payload:
+ report["output"] = bounded_utf8(payload["output"], MAX_BUILD_OUTPUT_BYTES)
+ if "percentage" in payload and isinstance(payload["percentage"], (int, float)):
+ report["percentage"] = min(100, max(0, int(round(payload["percentage"]))))
+ self._write_frame({"jsonrpc": "2.0", "method": "lithe/build/progress", "params": report})
+
+ def _shape_build(result: Any) -> dict[str, Any]:
+ if not isinstance(result, dict):
+ raise ValueError(f"{method} must return a dict")
+ expected_fmt = BUILD_FORMATS.get(method)
+ doc = dict(result)
+ if expected_fmt is not None:
+ if doc.get("format") not in (None, expected_fmt):
+ raise ValueError(f"Unexpected format for {method}")
+ if doc.get("version") not in (None, 0):
+ raise ValueError(f"Unexpected version for {method}")
+ doc["format"] = expected_fmt
+ doc["version"] = 0
+ if method in ("lithe/build/execute", "lithe/build/test"):
+ exit_code = doc.get("exitCode")
+ output = doc.get("output")
+ if (
+ isinstance(exit_code, bool)
+ or not isinstance(exit_code, int)
+ or exit_code < -2147483648
+ or exit_code > 2147483647
+ or not isinstance(output, str)
+ ):
+ raise ValueError(f"{method} requires int32 exitCode and string output")
+ encoded = json.dumps(doc, ensure_ascii=False).encode("utf-8")
+ if len(encoded) > MAX_BUILD_RESULT_BYTES:
+ raise ValueError(f"{method} exceeds 32 MiB build result limit")
+ return doc
+
+ def _stop_reporting() -> None:
+ nonlocal reporting
+ reporting = False
+
+ self._execute_tracked(
+ req_id=req_id,
+ token=token,
+ operation=method,
+ wire_op_id=op_id,
+ invoke=lambda ctx: handler(raw_params, ctx),
+ shape=_shape_build,
+ on_settled=_stop_reporting,
+ progress_cb=_progress if progressing else None,
+ workspace_context=None,
+ emit_logging=True,
+ )
+
+ def _invoke_toolchain_query(self, req_id: Any, token: CancelToken, raw_params: Any) -> None:
+ if not isinstance(raw_params, dict):
+ self._respond(
+ req_id,
+ error={
+ "code": ERROR_INVALID_PARAMS,
+ "message": "Malformed toolchain query params.",
+ "data": {
+ "code": "plugin.toolchain.invalidParams",
+ "operationID": "",
+ "providerID": "",
+ },
+ },
+ )
+ return
+
+ provider_id = raw_params.get("providerID") if isinstance(raw_params.get("providerID"), str) else ""
+ op_id = raw_params.get("operationID") if isinstance(raw_params.get("operationID"), str) else ""
+ if provider_id not in self._selected_toolchain_providers:
+ self._respond(
+ req_id,
+ error={
+ "code": ERROR_METHOD_NOT_FOUND,
+ "message": "The requested toolchain provider is not active on this session.",
+ "data": {
+ "code": "plugin.toolchain.methodUnavailable",
+ "operationID": op_id,
+ "providerID": provider_id,
+ },
+ },
+ )
+ return
+
+ handler = self._toolchain_providers[provider_id]
+ ctx = CallContext(
+ cancel_token=token,
+ diagnostics=self._make_diagnostics(request_operation_id(op_id, req_id)),
+ suppress_cb=lambda: None,
+ operation_id=op_id,
+ )
+ try:
+ token.raise_if_cancelled()
+ result = handler(raw_params, ctx)
+ token.raise_if_cancelled()
+ self._respond(req_id, result=result)
+ except CancelledError:
+ self._respond(
+ req_id,
+ error={
+ "code": ERROR_REQUEST_CANCELLED,
+ "message": "The toolchain query was cancelled.",
+ "data": {
+ "code": "plugin.toolchain.cancelled",
+ "operationID": op_id,
+ "providerID": provider_id,
+ },
+ },
+ )
+ except ToolchainQueryError as tc_err:
+ data_obj: dict[str, Any] = {
+ "code": tc_err.stable_code,
+ "operationID": tc_err.operation_id,
+ "providerID": tc_err.provider_id,
+ }
+ if tc_err.details is not None:
+ data_obj["details"] = tc_err.details
+ self._respond(
+ req_id,
+ error={
+ "code": tc_err.rpc_code,
+ "message": tc_err.user_message,
+ "data": data_obj,
+ },
+ )
+ except Exception as exc:
+ if token.cancelled:
+ self._respond(
+ req_id,
+ error={
+ "code": ERROR_REQUEST_CANCELLED,
+ "message": "The toolchain query was cancelled.",
+ "data": {
+ "code": "plugin.toolchain.cancelled",
+ "operationID": op_id,
+ "providerID": provider_id,
+ },
+ },
+ )
+ else:
+ self._write_stderr_category("toolchain_query_failed", type(exc).__name__)
+ self._respond(
+ req_id,
+ error={
+ "code": -32073,
+ "message": "The toolchain provider failed unexpectedly.",
+ "data": {
+ "code": "plugin.toolchain.providerUnavailable",
+ "operationID": op_id,
+ "providerID": provider_id,
+ },
+ },
+ )
+ def _execute_tracked(
+ self,
+ *,
+ req_id: Any,
+ token: CancelToken,
+ operation: str,
+ wire_op_id: Any,
+ invoke: Callable[[CallContext], Any],
+ shape: Callable[[Any], Any],
+ on_settled: Callable[[], None],
+ progress_cb: Optional[Callable[[dict[str, Any]], None]],
+ workspace_context: Optional[dict[str, Any]],
+ emit_logging: bool,
+ ) -> None:
+ started = time.monotonic()
+ diag = self._make_diagnostics(request_operation_id(wire_op_id, req_id))
+ quiet_call = False
+
+ def _suppress() -> None:
+ nonlocal quiet_call
+ quiet_call = True
+
+ ctx = CallContext(
+ cancel_token=token,
+ diagnostics=diag,
+ suppress_cb=_suppress,
+ operation_id=wire_op_id if isinstance(wire_op_id, str) else None,
+ progress_cb=progress_cb,
+ workspace_context=workspace_context,
+ )
+
+ result_val: Any = None
+ error_obj: Optional[dict[str, Any]] = None
+ diag_error_code: Optional[str] = None
+ was_cancelled = False
+
+ try:
+ token.raise_if_cancelled()
+ raw_value = invoke(ctx)
+ result_val = shape(raw_value)
+ token.raise_if_cancelled()
+ except CancelledError:
+ was_cancelled = True
+ error_obj = {"code": ERROR_REQUEST_CANCELLED, "message": "The request was cancelled."}
+ except PluginError as p_err:
+ if token.cancelled:
+ was_cancelled = True
+ error_obj = {"code": ERROR_REQUEST_CANCELLED, "message": "The request was cancelled."}
+ else:
+ diag_error_code = p_err.code
+ error_obj = {
+ "code": ERROR_REQUEST_FAILED,
+ "message": p_err.user_message,
+ "data": {"code": p_err.code},
+ }
+ except Exception as exc:
+ if token.cancelled:
+ was_cancelled = True
+ error_obj = {"code": ERROR_REQUEST_CANCELLED, "message": "The request was cancelled."}
+ else:
+ self._write_stderr_category("request_failed", type(exc).__name__)
+ diag_error_code = "internal_error"
+ error_obj = {
+ "code": ERROR_INTERNAL,
+ "message": "The plugin backend failed unexpectedly.",
+ }
+ finally:
+ elapsed_ms = (time.monotonic() - started) * 1000.0
+ on_settled()
+
+ # Emit terminal lithe/log notification strictly BEFORE the RPC response frame
+ # so Core correlates wire operationId with the still-active host operation.
+ if emit_logging and not was_cancelled:
+ if error_obj is not None:
+ diag.terminal(operation, diag_error_code or "internal_error", elapsed_ms)
+ elif not quiet_call and operation not in self._quiet_success:
+ diag.terminal(operation, None, elapsed_ms)
+
+ self._respond(req_id, result=result_val, error=error_obj)
diff --git a/io.github.lithe-idea.python-support/scripts/toolchain_provider.py b/io.github.lithe-idea.python-support/scripts/toolchain_provider.py
new file mode 100644
index 0000000..c5381d3
--- /dev/null
+++ b/io.github.lithe-idea.python-support/scripts/toolchain_provider.py
@@ -0,0 +1,727 @@
+import os
+import sys
+
+# Never write bytecode into the installed read-only plugin package or user workspace.
+sys.dont_write_bytecode = True
+os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
+
+import base64
+import glob
+import hashlib
+import json
+from pathlib import Path
+import re
+from typing import Any, Optional
+
+# Ensure sibling scripts are importable under Python 3.11+ `-I` safe_path mode.
+_SCRIPTS_DIR = str(Path(__file__).resolve().parent)
+if _SCRIPTS_DIR not in sys.path:
+ sys.path.insert(0, _SCRIPTS_DIR)
+
+from build_model import _load_tomllib # noqa: E402
+from lithe_rpc import CallContext, ToolchainQueryError, run_bounded_process # noqa: E402
+
+PROVIDER_ID = "python"
+SUPPORTED_TOOLS = frozenset({"python", "io.github.lithe-idea.python-support:python"})
+
+TOOLCHAIN_PROVIDER_DECLARATION = {
+ "id": PROVIDER_ID,
+ "displayName": "Python Environments (conda / uv / pyenv / Poetry / Pipenv)",
+ "tools": ["python"],
+ "watchFiles": [
+ {"pattern": ".python-version", "reader": "compatible"},
+ {"pattern": "pyproject.toml", "reader": "native"},
+ {"pattern": "Pipfile", "reader": "native"},
+ {"pattern": "poetry.lock", "reader": "native"},
+ ],
+}
+
+_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
+_VERSION_EXTRACT_RE = re.compile(r"(\d+(?:\.\d+)+)")
+_SPEC_CLAUSE_RE = re.compile(r"^(~=|==|!=|<=|>=|<|>|\^)\s*v?(\d+(?:\.\d+)*(?:\.\*)?)$")
+
+_MAX_INSTALLATIONS = 512
+_MAX_STATEMENTS = 256
+_MAX_WATCH_PATHS = 256
+_MAX_PROBES = 24
+_MAX_DIR_ENTRIES = 1024
+
+
+def _is_valid_id(value: Any) -> bool:
+ return isinstance(value, str) and _IDENTIFIER_RE.match(value) is not None and not any(ord(c) < 32 or ord(c) == 127 for c in value)
+
+
+def _is_valid_rel_dir(value: Any) -> bool:
+ if not isinstance(value, str) or not value or len(value.encode("utf-8")) > 2048:
+ return False
+ if any(ord(c) < 32 or ord(c) == 127 for c in value):
+ return False
+ if value == ".":
+ return True
+ if "\\" in value or ":" in value:
+ return False
+ return all(part not in ("", ".", "..") for part in value.split("/"))
+
+
+def _parse_version_tuple(ver: str) -> Optional[tuple[int, ...]]:
+ m = re.match(r"^(\d+(?:\.\d+)*)", ver.strip())
+ if not m:
+ return None
+ parts = [int(p) for p in m.group(1).split(".")]
+ if len(parts) > 8:
+ return None
+ return tuple(parts)
+
+
+def _normalize_version_tuple(parts: tuple[int, ...]) -> tuple[int, ...]:
+ trimmed = list(parts)
+ while len(trimmed) > 1 and trimmed[-1] == 0:
+ trimmed.pop()
+ return tuple(trimmed)
+
+
+def _compare_versions(left: tuple[int, ...], right: tuple[int, ...]) -> int:
+ nl = _normalize_version_tuple(left)
+ nr = _normalize_version_tuple(right)
+ if nl < nr:
+ return -1
+ if nl > nr:
+ return 1
+ return 0
+
+
+def _matches_clause(candidate: tuple[int, ...], op: str, raw_target: str) -> bool:
+ wildcard = raw_target.endswith(".*")
+ base_str = raw_target[:-2] if wildcard else raw_target
+ if not re.match(r"^\d+(?:\.\d+)*$", base_str):
+ return False
+ target = tuple(int(x) for x in base_str.split("."))
+
+ if wildcard:
+ prefix = candidate[: len(target)]
+ padded = prefix + (0,) * max(0, len(target) - len(prefix))
+ if op == "==":
+ return padded == target
+ if op == "!=":
+ return padded != target
+ return False
+
+ cmp_val = _compare_versions(candidate, target)
+ if op == "==":
+ return cmp_val == 0
+ if op == "!=":
+ return cmp_val != 0
+ if op == ">=":
+ return cmp_val >= 0
+ if op == "<=":
+ return cmp_val <= 0
+ if op == ">":
+ return cmp_val > 0
+ if op == "<":
+ return cmp_val < 0
+ if op == "~=":
+ if cmp_val < 0:
+ return False
+ upper = list(target[:-1]) if len(target) > 1 else [target[0]]
+ upper[-1] += 1
+ return _compare_versions(candidate, tuple(upper)) < 0
+ if op == "^":
+ if cmp_val < 0:
+ return False
+ upper_list = list(target)
+ bumped = False
+ for idx, val in enumerate(upper_list):
+ if val != 0:
+ upper_list = upper_list[: idx + 1]
+ upper_list[idx] = val + 1
+ bumped = True
+ break
+ if not bumped:
+ upper_list[-1] += 1
+ return _compare_versions(candidate, tuple(upper_list)) < 0
+ return False
+
+
+def matches_python_requirement(version_str: str, requirement: str) -> bool:
+ """Evaluates PEP 440 / Poetry / .python-version requirement expressions."""
+ ver_tuple = _parse_version_tuple(version_str)
+ if ver_tuple is None:
+ return False
+ req = requirement.strip()
+ if not req or req == "*":
+ return True
+
+ # Plain dotted version or prefix from .python-version (e.g. "3.12", "3.12.4", "cpython-3.12.4-macos").
+ cleaned = req
+ if cleaned.startswith("cpython-"):
+ cleaned = cleaned[len("cpython-") :]
+ cleaned = cleaned.split("-", 1)[0]
+ if re.match(r"^\d+(?:\.\d+)*$", cleaned):
+ target = tuple(int(x) for x in cleaned.split("."))
+ if len(target) <= 2:
+ padded = ver_tuple[: len(target)] + (0,) * max(0, len(target) - len(ver_tuple))
+ return padded == target
+ return _compare_versions(ver_tuple, target) == 0
+
+ clauses = [c.strip() for c in req.split(",") if c.strip()]
+ if not clauses:
+ return False
+ for clause in clauses:
+ m = _SPEC_CLAUSE_RE.match(clause)
+ if not m:
+ return False
+ if not _matches_clause(ver_tuple, m.group(1), m.group(2)):
+ return False
+ return True
+
+
+def _within_dir(path: Path, root: Path, case_sensitive: bool) -> bool:
+ p_str = str(path)
+ r_str = str(root)
+ if not case_sensitive:
+ p_str = p_str.lower()
+ r_str = r_str.lower()
+ r_norm = r_str.rstrip("/\\")
+ p_norm = p_str.rstrip("/\\")
+ if p_norm == r_norm:
+ return True
+ sep = "\\" if "\\" in r_norm else "/"
+ return p_norm.startswith(r_norm + sep)
+
+
+def _executable_layouts_for_platform(platform_name: str) -> list[str]:
+ if platform_name == "windows":
+ return ["Scripts/python.exe", "python.exe"]
+ return ["bin/python3", "bin/python"]
+
+
+def _read_metadata_version(home_dir: Path) -> Optional[str]:
+ """Reads Python version from pyvenv.cfg or conda-meta/python-*.json without spawning a process."""
+ pyvenv_cfg = home_dir / "pyvenv.cfg"
+ if pyvenv_cfg.is_file():
+ try:
+ for raw_line in pyvenv_cfg.read_text(encoding="utf-8", errors="ignore").splitlines():
+ if "=" not in raw_line:
+ continue
+ k, v = (part.strip() for part in raw_line.split("=", 1))
+ if k in ("version_info", "version"):
+ m = _VERSION_EXTRACT_RE.search(v)
+ if m:
+ parts = m.group(1).split(".")[:3]
+ return ".".join(parts)
+ except OSError:
+ pass
+
+ conda_meta = home_dir / "conda-meta"
+ if conda_meta.is_dir():
+ try:
+ for entry in sorted(conda_meta.iterdir()):
+ if entry.name.startswith("python-") and entry.name.endswith(".json") and entry.is_file():
+ data = json.loads(entry.read_text(encoding="utf-8", errors="ignore"))
+ if isinstance(data, dict) and data.get("name") == "python" and isinstance(data.get("version"), str):
+ m = _VERSION_EXTRACT_RE.match(data["version"].strip())
+ if m:
+ return m.group(1)
+ except Exception:
+ pass
+
+ # uv python directory naming fallback: cpython-3.12.6-macos-aarch64-none
+ m_uv = re.match(r"^(?:cpython|pypy)-(\d+\.\d+(?:\.\d+)?)\b", home_dir.name)
+ if m_uv:
+ return m_uv.group(1)
+
+ # pyenv versions directory naming fallback: 3.12.4
+ if re.match(r"^\d+\.\d+\.\d+$", home_dir.name):
+ return home_dir.name
+
+ return None
+
+
+def _list_subdirs_bounded(parent: Path, pattern: str = "*") -> list[Path]:
+ if not parent.is_dir():
+ return []
+ found: list[Path] = []
+ try:
+ count = 0
+ for entry in sorted(parent.iterdir(), key=lambda p: p.name):
+ if count >= _MAX_DIR_ENTRIES:
+ break
+ count += 1
+ if entry.name.startswith(".") and not pattern.startswith("."):
+ continue
+ if glob.fnmatch.fnmatch(entry.name, pattern) and entry.is_dir():
+ found.append(entry)
+ except OSError:
+ pass
+ return found
+
+
+def _pipenv_virtualenv_prefix(project_dir: Path) -> str:
+ clean_name = re.sub(r'[ $`!*@"\\\r\n\t]', "_", project_dir.name)[:42]
+ digest = hashlib.sha256(str(project_dir).encode("utf-8")).digest()[:6]
+ encoded = base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=")[:8]
+ return f"{clean_name}-{encoded}"
+
+
+def _poetry_virtualenv_prefix(project_dir: Path, project_name: Optional[str]) -> str:
+ raw_name = project_name or project_dir.name
+ sanitized = re.sub(r'[ $`!*@"\\\r\n\t]', "_", raw_name).lower()
+ norm_path = os.path.normcase(str(project_dir.resolve()))
+ digest = hashlib.sha256(norm_path.encode("utf-8")).hexdigest()[:8]
+ return f"{sanitized}-{digest}-py"
+
+
+def query_python_toolchains(
+ params: dict[str, Any],
+ ctx: CallContext,
+ *,
+ home_dir: Optional[Path] = None,
+ environ: Optional[dict[str, str]] = None,
+ platform_name: Optional[str] = None,
+ extra_workspace_roots: Optional[list[Path]] = None,
+) -> dict[str, Any]:
+ """
+ Executes `toolchains/query` for Python installations and project requirements,
+ returning `{operationID, generation, providerID, installations, statements, watch}`
+ strictly conforming to shared/plugins/contract/v1/toolchains/README.md.
+ """
+ op_id = params.get("operationID") if isinstance(params.get("operationID"), str) else ""
+ provider_id = params.get("providerID") if isinstance(params.get("providerID"), str) else PROVIDER_ID
+ generation = params.get("generation")
+
+ if (
+ not _is_valid_id(op_id)
+ or isinstance(generation, bool)
+ or not isinstance(generation, int)
+ or generation <= 0
+ or provider_id != PROVIDER_ID
+ or "workspace" not in params
+ or "context" not in params
+ ):
+ raise ToolchainQueryError(
+ "plugin.toolchain.invalidParams",
+ "Invalid query identities or missing workspace/context envelope.",
+ op_id,
+ provider_id,
+ )
+
+ authority = params.get("authority")
+ if not isinstance(authority, dict) or not isinstance(authority.get("kind"), str):
+ raise ToolchainQueryError(
+ "plugin.toolchain.invalidParams",
+ "Malformed query authority.",
+ op_id,
+ provider_id,
+ )
+ if authority["kind"] == "remote":
+ raise ToolchainQueryError(
+ "plugin.toolchain.authorityUnsupported",
+ "Remote toolchain authority is not supported.",
+ op_id,
+ provider_id,
+ )
+ if authority["kind"] != "local" or set(authority.keys()) != {"kind"}:
+ raise ToolchainQueryError(
+ "plugin.toolchain.invalidParams",
+ "Unsupported local authority shape.",
+ op_id,
+ provider_id,
+ )
+
+ tools = params.get("tools")
+ if (
+ not isinstance(tools, list)
+ or not (1 <= len(tools) <= 64)
+ or any(not isinstance(t, str) or t not in SUPPORTED_TOOLS for t in tools)
+ or len(set(tools)) != len(tools)
+ or tools != sorted(tools)
+ ):
+ raise ToolchainQueryError(
+ "plugin.toolchain.invalidParams",
+ "Invalid or undeclared tools in toolchain query.",
+ op_id,
+ provider_id,
+ )
+ target_tool = tools[0]
+
+ ws_param = params.get("workspace")
+ ctx_param = params.get("context")
+ workspace_root: Optional[Path] = None
+ queried_dir: Optional[Path] = None
+
+ if ws_param is not None:
+ if (
+ not isinstance(ctx_param, dict)
+ or not _is_valid_id(ctx_param.get("contextID"))
+ or isinstance(ctx_param.get("generation"), bool)
+ or not isinstance(ctx_param.get("generation"), int)
+ or ctx_param["generation"] <= 0
+ ):
+ raise ToolchainQueryError(
+ "plugin.toolchain.invalidParams",
+ "Workspace toolchain queries require a valid context reference.",
+ op_id,
+ provider_id,
+ )
+ if (
+ not isinstance(ws_param, dict)
+ or not _is_valid_id(ws_param.get("rootID"))
+ or not isinstance(ws_param.get("root"), str)
+ or not _is_valid_rel_dir(ws_param.get("directory"))
+ ):
+ raise ToolchainQueryError(
+ "plugin.toolchain.invalidParams",
+ "Invalid workspace query parameters.",
+ op_id,
+ provider_id,
+ )
+ raw_ws_root = Path(ws_param["root"])
+ if not raw_ws_root.is_absolute() or not raw_ws_root.is_dir():
+ raise ToolchainQueryError(
+ "plugin.toolchain.unsafePath",
+ "Workspace root must be an existing absolute directory.",
+ op_id,
+ provider_id,
+ )
+ workspace_root = raw_ws_root.resolve()
+ rel_dir = ws_param["directory"]
+ target_dir = workspace_root if rel_dir == "." else (workspace_root / Path(*rel_dir.split("/")))
+ if not target_dir.is_dir():
+ raise ToolchainQueryError(
+ "plugin.toolchain.unsafePath",
+ "Queried workspace directory does not exist.",
+ op_id,
+ provider_id,
+ )
+ queried_dir = target_dir.resolve()
+
+ eff_platform = platform_name or (
+ "windows" if sys.platform == "win32" else ("macos" if sys.platform == "darwin" else "linux")
+ )
+ case_sensitive = eff_platform != "windows"
+ if workspace_root is not None and queried_dir is not None:
+ if not _within_dir(queried_dir, workspace_root, case_sensitive):
+ raise ToolchainQueryError(
+ "plugin.toolchain.unsafePath",
+ "Queried directory escapes workspace root.",
+ op_id,
+ provider_id,
+ )
+
+ eff_env = environ if environ is not None else dict(os.environ)
+ eff_home = (home_dir if home_dir is not None else Path.home()).resolve()
+ forbidden_roots: list[Path] = []
+ if workspace_root is not None:
+ forbidden_roots.append(workspace_root)
+ for extra in extra_workspace_roots or []:
+ try:
+ forbidden_roots.append(extra.resolve())
+ except OSError:
+ pass
+
+ watch_paths: set[str] = set()
+ candidate_homes: list[Path] = []
+
+ # 1. ~/.conda/environments.txt
+ conda_envs_txt = eff_home / ".conda" / "environments.txt"
+ watch_paths.add(str(conda_envs_txt))
+ if conda_envs_txt.is_file():
+ try:
+ for line in conda_envs_txt.read_text(encoding="utf-8", errors="ignore").splitlines():
+ stripped = line.strip()
+ if not stripped or stripped.startswith("#"):
+ continue
+ p = Path(stripped)
+ if p.is_absolute() and p.is_dir():
+ candidate_homes.append(p)
+ except OSError:
+ pass
+
+ # 2. CONDA_ENVS_PATH (supports os.pathsep-separated directories) & CONDA_PREFIX & standard conda dirs
+ raw_conda_envs = eff_env.get("CONDA_ENVS_PATH", "").strip()
+ if raw_conda_envs:
+ for chunk in raw_conda_envs.split(os.pathsep):
+ chunk = chunk.strip()
+ if chunk and Path(chunk).is_absolute():
+ candidate_homes.extend(_list_subdirs_bounded(Path(chunk)))
+ raw_conda_prefix = eff_env.get("CONDA_PREFIX", "").strip()
+ if raw_conda_prefix and Path(raw_conda_prefix).is_absolute():
+ cp = Path(raw_conda_prefix)
+ if cp.is_dir():
+ candidate_homes.append(cp)
+ candidate_homes.extend(_list_subdirs_bounded(cp / "envs"))
+ for pattern in ("*conda*", "miniforge*"):
+ for base in _list_subdirs_bounded(eff_home, pattern):
+ candidate_homes.append(base)
+ candidate_homes.extend(_list_subdirs_bounded(base / "envs"))
+
+ # 3. UV_PYTHON_INSTALL_DIR / XDG_DATA_HOME / default uv python dirs
+ uv_dir_env = eff_env.get("UV_PYTHON_INSTALL_DIR", "").strip()
+ if uv_dir_env and Path(uv_dir_env).is_absolute():
+ uv_root = Path(uv_dir_env)
+ watch_paths.add(str(uv_root))
+ candidate_homes.extend(_list_subdirs_bounded(uv_root))
+ xdg_data = eff_env.get("XDG_DATA_HOME", "").strip()
+ if xdg_data and Path(xdg_data).is_absolute():
+ candidate_homes.extend(_list_subdirs_bounded(Path(xdg_data) / "uv" / "python"))
+ candidate_homes.extend(_list_subdirs_bounded(eff_home / ".local" / "share" / "uv" / "python"))
+ appdata = eff_env.get("APPDATA", "").strip()
+ if appdata and Path(appdata).is_absolute():
+ candidate_homes.extend(_list_subdirs_bounded(Path(appdata) / "uv" / "data" / "python"))
+
+ # 4. PYENV_ROOT / ~/.pyenv
+ pyenv_root = eff_env.get("PYENV_ROOT", "").strip()
+ if pyenv_root and Path(pyenv_root).is_absolute():
+ pr = Path(pyenv_root) / "versions"
+ watch_paths.add(str(pr))
+ candidate_homes.extend(_list_subdirs_bounded(pr))
+ candidate_homes.extend(_list_subdirs_bounded(eff_home / ".pyenv" / "versions"))
+ candidate_homes.extend(_list_subdirs_bounded(eff_home / ".pyenv" / "pyenv-win" / "versions"))
+
+ # 5. Poetry & Pipenv / WORKON_HOME external virtualenvs
+ poetry_roots: list[Path] = []
+ poetry_cache = eff_env.get("POETRY_CACHE_DIR", "").strip()
+ if poetry_cache and Path(poetry_cache).is_absolute():
+ poetry_roots.append(Path(poetry_cache) / "virtualenvs")
+ if eff_platform == "macos":
+ poetry_roots.append(eff_home / "Library" / "Caches" / "pypoetry" / "virtualenvs")
+ elif eff_platform == "windows":
+ local_app = eff_env.get("LOCALAPPDATA", "").strip()
+ if local_app and Path(local_app).is_absolute():
+ poetry_roots.append(Path(local_app) / "pypoetry" / "Cache" / "virtualenvs")
+ else:
+ xdg_cache = eff_env.get("XDG_CACHE_HOME", "").strip()
+ if xdg_cache and Path(xdg_cache).is_absolute():
+ poetry_roots.append(Path(xdg_cache) / "pypoetry" / "virtualenvs")
+ poetry_roots.append(eff_home / ".cache" / "pypoetry" / "virtualenvs")
+ for p_root in poetry_roots:
+ candidate_homes.extend(_list_subdirs_bounded(p_root))
+
+ workon = eff_env.get("WORKON_HOME", "").strip()
+ if workon and Path(workon).is_absolute():
+ candidate_homes.extend(_list_subdirs_bounded(Path(workon)))
+ candidate_homes.extend(_list_subdirs_bounded(eff_home / ".local" / "share" / "virtualenvs"))
+ candidate_homes.extend(_list_subdirs_bounded(eff_home / ".virtualenvs"))
+
+ layouts = _executable_layouts_for_platform(eff_platform)
+ installations_by_key: dict[str, dict[str, str]] = {}
+ probes_used = 0
+
+ for raw_home in candidate_homes:
+ ctx.raise_if_cancelled()
+ if len(installations_by_key) >= _MAX_INSTALLATIONS:
+ break
+ try:
+ canon_home = raw_home.resolve()
+ except OSError:
+ continue
+ if not canon_home.is_dir():
+ continue
+ if any(_within_dir(canon_home, root, case_sensitive) for root in forbidden_roots):
+ continue
+
+ home_key = str(canon_home) if case_sensitive else str(canon_home).lower()
+ if home_key in installations_by_key:
+ continue
+
+ matched_exec: Optional[Path] = None
+ for rel_layout in layouts:
+ candidate_exec = canon_home / Path(*rel_layout.split("/"))
+ if not candidate_exec.exists():
+ continue
+ try:
+ canon_exec = candidate_exec.resolve()
+ except OSError:
+ continue
+ if not canon_exec.is_file():
+ continue
+ if eff_platform != "windows" and not os.access(canon_exec, os.X_OK):
+ continue
+ # Core query.rs requires a provider installation's resolved executable to stay inside
+ # canonical_home and outside workspace roots.
+ if not _within_dir(canon_exec, canon_home, case_sensitive):
+ continue
+ if any(_within_dir(canon_exec, root, case_sensitive) for root in forbidden_roots):
+ continue
+ matched_exec = canon_exec
+ break
+
+ if matched_exec is None:
+ continue
+
+ version_str = _read_metadata_version(canon_home)
+ if version_str is None and probes_used < _MAX_PROBES:
+ probes_used += 1
+ probe_env = dict(eff_env)
+ probe_env["PYTHONDONTWRITEBYTECODE"] = "1"
+ try:
+ code, out, timed_out = run_bounded_process(
+ [str(matched_exec), "--version"],
+ cwd=str(canon_home),
+ env=probe_env,
+ cancel_token=ctx.cancel_token,
+ timeout_seconds=3.0,
+ max_output_bytes=4096,
+ )
+ if not timed_out and code == 0:
+ m = re.search(r"Python\s+(\d+(?:\.\d+)*)", out)
+ if m:
+ version_str = m.group(1)
+ except OSError:
+ version_str = None
+
+ if not version_str or _parse_version_tuple(version_str) is None:
+ continue
+
+ installations_by_key[home_key] = {
+ "tool": target_tool,
+ "version": version_str,
+ "home": str(canon_home),
+ }
+
+ # Sort installations deterministically: highest version first, then home path.
+ sorted_installations = sorted(
+ installations_by_key.values(),
+ key=lambda item: (
+ tuple(-part for part in (_parse_version_tuple(item["version"]) or (0,))),
+ item["home"],
+ ),
+ )
+
+ def _pick_best_installation(req_spec: str, allow_env_name: bool = False) -> Optional[str]:
+ cleaned = req_spec.strip()
+ if not cleaned:
+ return None
+ if allow_env_name:
+ for inst in sorted_installations:
+ if Path(inst["home"]).name == cleaned:
+ return inst["home"]
+ best_home: Optional[str] = None
+ best_ver: Optional[tuple[int, ...]] = None
+ for inst in sorted_installations:
+ if matches_python_requirement(inst["version"], cleaned):
+ vt = _parse_version_tuple(inst["version"])
+ if vt is not None and (best_ver is None or _compare_versions(vt, best_ver) > 0):
+ best_ver = vt
+ best_home = inst["home"]
+ return best_home
+
+ statements: list[dict[str, Any]] = []
+ if workspace_root is not None and queried_dir is not None:
+ ancestors: list[Path] = []
+ cur = queried_dir
+ for _ in range(64):
+ ancestors.append(cur)
+ if cur == workspace_root or cur.parent == cur:
+ break
+ cur = cur.parent
+
+ tomllib = _load_tomllib()
+ for anc in ancestors:
+ if len(statements) >= _MAX_STATEMENTS:
+ break
+
+ py_ver_file = anc / ".python-version"
+ watch_paths.add(str(py_ver_file))
+ if py_ver_file.is_file():
+ try:
+ lines = [
+ ln.strip()
+ for ln in py_ver_file.read_text(encoding="utf-8", errors="ignore").splitlines()
+ if ln.strip() and not ln.strip().startswith("#")
+ ]
+ if lines:
+ req_line = lines[0][:512]
+ statements.append({
+ "tool": target_tool,
+ "scope": "project",
+ "source": str(py_ver_file.resolve()),
+ "request": req_line,
+ "installation": _pick_best_installation(req_line, allow_env_name=True),
+ "kind": "declaration",
+ "reader": "compatible",
+ })
+ except OSError:
+ pass
+
+ pyproject_file = anc / "pyproject.toml"
+ watch_paths.add(str(pyproject_file))
+ project_name_hint: Optional[str] = None
+ if pyproject_file.is_file():
+ try:
+ data = tomllib.loads(pyproject_file.read_text(encoding="utf-8"))
+ if isinstance(data, dict):
+ proj_tbl = data.get("project")
+ req_py: Optional[str] = None
+ if isinstance(proj_tbl, dict):
+ if isinstance(proj_tbl.get("name"), str) and proj_tbl["name"].strip():
+ project_name_hint = proj_tbl["name"].strip()
+ if isinstance(proj_tbl.get("requires-python"), str) and proj_tbl["requires-python"].strip():
+ req_py = proj_tbl["requires-python"].strip()
+ poetry_tbl = (data.get("tool") or {}).get("poetry") if isinstance(data.get("tool"), dict) else None
+ if isinstance(poetry_tbl, dict):
+ if not project_name_hint and isinstance(poetry_tbl.get("name"), str):
+ project_name_hint = poetry_tbl["name"].strip() or None
+ deps = poetry_tbl.get("dependencies")
+ if not req_py and isinstance(deps, dict) and isinstance(deps.get("python"), str):
+ req_py = deps["python"].strip() or None
+ if req_py:
+ statements.append({
+ "tool": target_tool,
+ "scope": "project",
+ "source": str(pyproject_file.resolve()),
+ "request": req_py[:512],
+ "installation": _pick_best_installation(req_py, allow_env_name=False),
+ "kind": "declaration",
+ "reader": "native",
+ })
+ except Exception:
+ pass
+
+ poetry_lock = anc / "poetry.lock"
+ if poetry_lock.is_file():
+ watch_paths.add(str(poetry_lock))
+ prefix = _poetry_virtualenv_prefix(anc, project_name_hint)
+ matched_poetry = next(
+ (inst["home"] for inst in sorted_installations if Path(inst["home"]).name.lower().startswith(prefix)),
+ None,
+ )
+ if matched_poetry is not None:
+ statements.append({
+ "tool": target_tool,
+ "scope": "project",
+ "source": str(poetry_lock.resolve()),
+ "request": Path(matched_poetry).name[:512],
+ "installation": matched_poetry,
+ "kind": "environment",
+ "reader": "native",
+ })
+
+ pipfile = anc / "Pipfile"
+ if pipfile.is_file():
+ watch_paths.add(str(pipfile))
+ pipenv_prefix = _pipenv_virtualenv_prefix(anc)
+ matched_pipenv = next(
+ (inst["home"] for inst in sorted_installations if Path(inst["home"]).name == pipenv_prefix),
+ None,
+ )
+ if matched_pipenv is not None:
+ statements.append({
+ "tool": target_tool,
+ "scope": "project",
+ "source": str(pipfile.resolve()),
+ "request": pipenv_prefix[:512],
+ "installation": matched_pipenv,
+ "kind": "environment",
+ "reader": "native",
+ })
+
+ bounded_watch = sorted(watch_paths)[:_MAX_WATCH_PATHS]
+ return {
+ "operationID": op_id,
+ "generation": generation,
+ "providerID": provider_id,
+ "installations": sorted_installations[:_MAX_INSTALLATIONS],
+ "statements": statements[:_MAX_STATEMENTS],
+ "watch": bounded_watch,
+ }
diff --git a/io.github.lithe-idea.python-support/scripts/windows_job.py b/io.github.lithe-idea.python-support/scripts/windows_job.py
new file mode 100644
index 0000000..facd2fc
--- /dev/null
+++ b/io.github.lithe-idea.python-support/scripts/windows_job.py
@@ -0,0 +1,115 @@
+"""Own a test subprocess tree with a Windows job for the request's lifetime."""
+
+import ctypes
+from ctypes import wintypes
+import subprocess
+
+_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
+_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
+_PROCESS_TERMINATE = 0x0001
+_PROCESS_SET_QUOTA = 0x0100
+
+
+class _BasicLimitInformation(ctypes.Structure):
+ _fields_ = [
+ ("perProcessUserTimeLimit", ctypes.c_longlong),
+ ("perJobUserTimeLimit", ctypes.c_longlong),
+ ("limitFlags", wintypes.DWORD),
+ ("minimumWorkingSetSize", ctypes.c_size_t),
+ ("maximumWorkingSetSize", ctypes.c_size_t),
+ ("activeProcessLimit", wintypes.DWORD),
+ ("affinity", ctypes.c_size_t),
+ ("priorityClass", wintypes.DWORD),
+ ("schedulingClass", wintypes.DWORD),
+ ]
+
+
+class _ExtendedLimitInformation(ctypes.Structure):
+ _fields_ = [
+ ("basicLimitInformation", _BasicLimitInformation),
+ ("ioCounters", ctypes.c_ulonglong * 6),
+ ("processMemoryLimit", ctypes.c_size_t),
+ ("jobMemoryLimit", ctypes.c_size_t),
+ ("peakProcessMemoryUsed", ctypes.c_size_t),
+ ("peakJobMemoryUsed", ctypes.c_size_t),
+ ]
+
+
+_kernel = ctypes.WinDLL("kernel32", use_last_error=True)
+_create_job = _kernel.CreateJobObjectW
+_create_job.argtypes = (wintypes.LPVOID, wintypes.LPCWSTR)
+_create_job.restype = wintypes.HANDLE
+_set_job = _kernel.SetInformationJobObject
+_set_job.argtypes = (wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD)
+_set_job.restype = wintypes.BOOL
+_assign_job = _kernel.AssignProcessToJobObject
+_assign_job.argtypes = (wintypes.HANDLE, wintypes.HANDLE)
+_assign_job.restype = wintypes.BOOL
+_open_process = _kernel.OpenProcess
+_open_process.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
+_open_process.restype = wintypes.HANDLE
+_close_handle = _kernel.CloseHandle
+_close_handle.argtypes = (wintypes.HANDLE,)
+_close_handle.restype = wintypes.BOOL
+
+# The isolated bootstrap waits on stdin before launching the requested tool.
+# Popen only exposes the process ID, so this handshake keeps its child creation
+# behind job assignment without reaching into private process/thread handles.
+_BOOTSTRAP = """import subprocess, sys
+if sys.stdin.buffer.read(1) != b"1":
+ sys.exit(1)
+sys.exit(subprocess.call(sys.argv[1:], stdin=subprocess.DEVNULL))
+"""
+
+
+class WindowsJob:
+ def __init__(self):
+ self._handle = _create_job(None, None)
+ if not self._handle:
+ raise ctypes.WinError(ctypes.get_last_error())
+ limits = _ExtendedLimitInformation()
+ limits.basicLimitInformation.limitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ if not _set_job(
+ self._handle,
+ _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
+ ctypes.byref(limits),
+ ctypes.sizeof(limits),
+ ):
+ code = ctypes.get_last_error()
+ self.close()
+ raise ctypes.WinError(code)
+
+ def start(self, bootstrap_python, argv, *, cwd, env):
+ process = subprocess.Popen(
+ [bootstrap_python, "-I", "-S", "-B", "-c", _BOOTSTRAP, *argv],
+ cwd=cwd,
+ env=env,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
+ )
+ try:
+ handle = _open_process(_PROCESS_TERMINATE | _PROCESS_SET_QUOTA, False, process.pid)
+ if not handle:
+ raise ctypes.WinError(ctypes.get_last_error())
+ try:
+ if not _assign_job(self._handle, handle):
+ raise ctypes.WinError(ctypes.get_last_error())
+ finally:
+ _close_handle(handle)
+ process.stdin.write(b"1")
+ process.stdin.close()
+ return process
+ except (OSError, ValueError):
+ process.kill()
+ process.wait(timeout=2)
+ process.stdin.close()
+ process.stdout.close()
+ raise
+
+ def close(self):
+ if self._handle:
+ handle, self._handle = self._handle, None
+ if not _close_handle(handle):
+ raise ctypes.WinError(ctypes.get_last_error())
diff --git a/scripts/e2e-host.mjs b/scripts/e2e-host.mjs
index 5d8c8b2..ea647c6 100644
--- a/scripts/e2e-host.mjs
+++ b/scripts/e2e-host.mjs
@@ -7,10 +7,11 @@
// .artifacts/lithe-host (desktop/ and scripts/ only), copies e2e/host/desktop/ into
// that checkout, and runs scripts/desktop/desktop-go.sh test against real Rust Core.
-import { spawn } from "node:child_process";
-import { existsSync } from "node:fs";
+import { spawn, spawnSync } from "node:child_process";
+import { existsSync, readdirSync } from "node:fs";
import { copyFile, mkdir, readdir, readFile } from "node:fs/promises";
-import { dirname, join, relative, resolve } from "node:path";
+import { homedir } from "node:os";
+import { delimiter, dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";
@@ -18,6 +19,41 @@ const root = fileURLToPath(new URL("..", import.meta.url));
const tests = join(root, "e2e", "host");
const work = join(root, ".artifacts", "lithe-host");
+function ensureToolchainsOnPath() {
+ const extraDirs = [];
+ const cargoBin = join(homedir(), ".cargo", "bin");
+ if (existsSync(cargoBin)) extraDirs.push(cargoBin);
+ if (process.platform === "darwin" && existsSync("/opt/homebrew/opt/rustup/bin")) {
+ extraDirs.push("/opt/homebrew/opt/rustup/bin");
+ }
+ if (process.platform === "darwin" && existsSync("/opt/homebrew/bin")) {
+ extraDirs.push("/opt/homebrew/bin");
+ }
+ const probe = spawnSync(process.platform === "win32" ? "where" : "which", ["go"], { stdio: "ignore" });
+ if (probe.status !== 0) {
+ const modDir = join(homedir(), "go", "pkg", "mod", "golang.org");
+ if (existsSync(modDir)) {
+ const goArch = process.arch === "x64" ? "amd64" : process.arch;
+ const suffix = `.${process.platform}-${goArch}`;
+ const matches = readdirSync(modDir)
+ .filter((name) => name.startsWith("toolchain@") && name.endsWith(suffix))
+ .sort()
+ .reverse();
+ for (const name of matches) {
+ const binDir = join(modDir, name, "bin");
+ const goExe = join(binDir, process.platform === "win32" ? "go.exe" : "go");
+ if (existsSync(goExe)) {
+ extraDirs.push(binDir);
+ break;
+ }
+ }
+ }
+ }
+ if (extraDirs.length > 0) {
+ process.env.PATH = [...extraDirs, process.env.PATH ?? ""].filter(Boolean).join(delimiter);
+ }
+}
+
function detectHostPlatform() {
const osPart =
process.platform === "darwin"
@@ -42,6 +78,18 @@ function run(command, args, options = {}) {
});
}
+async function hasCommitLocally(dir, ref) {
+ if (!/^[0-9a-f]{40}$/i.test(ref) || !existsSync(join(dir, ".git"))) {
+ return false;
+ }
+ try {
+ await run("git", ["-C", dir, "cat-file", "-e", `${ref}^{commit}`], { stdio: "ignore" });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
async function hostTestFiles(directory = join(tests, "desktop")) {
const files = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
@@ -52,12 +100,20 @@ async function hostTestFiles(directory = join(tests, "desktop")) {
return files;
}
-async function checkoutHost(source, ref) {
+async function checkoutHost(source, ref, isRemoteUrl, explicitSource) {
await mkdir(work, { recursive: true });
await run("git", ["init", "-q", work]);
await run("git", ["-C", work, "sparse-checkout", "set", "--cone", "desktop", "scripts"]);
+ if (!explicitSource && (await hasCommitLocally(work, ref))) {
+ await run("git", ["-C", work, "checkout", "-q", "--force", "--detach", ref]);
+ await run("git", ["-C", work, "clean", "-q", "-f", "-d", "--", "desktop"]);
+ return;
+ }
await run("git", ["-C", work, "config", "remote.origin.url", source]);
- await run("git", ["-C", work, "fetch", "-q", "--depth", "1", "--filter=blob:none", "origin", ref]);
+ const fetchArgs = isRemoteUrl
+ ? ["-C", work, "fetch", "-q", "--depth", "1", "--filter=blob:none", "origin", ref]
+ : ["-C", work, "fetch", "-q", "--depth", "1", "origin", ref];
+ await run("git", fetchArgs);
await run("git", ["-C", work, "checkout", "-q", "--force", "--detach", "FETCH_HEAD"]);
await run("git", ["-C", work, "clean", "-q", "-f", "-d", "--", "desktop"]);
}
@@ -103,10 +159,11 @@ if (missing.length > 0) {
);
}
+ensureToolchainsOnPath();
const given = values.source ?? pin.repository;
const isRemoteUrl = /^[a-z]+:\/\//.test(given);
const source = isRemoteUrl ? given : resolve(given);
-await checkoutHost(source, values.ref ?? pin.revision);
+await checkoutHost(source, values.ref ?? pin.revision, isRemoteUrl, Boolean(values.source));
if (!isRemoteUrl) {
await maybeSeedDesktopArtifacts(source);
}
diff --git a/scripts/package/archives.test.mjs b/scripts/package/archives.test.mjs
index 5cb626d..3424265 100644
--- a/scripts/package/archives.test.mjs
+++ b/scripts/package/archives.test.mjs
@@ -70,7 +70,12 @@ test("every built archive has safe paths, no bytecode or symlinks, and valid pla
`${PACKAGE_ID}/LICENSE`,
`${PACKAGE_ID}/THIRD-PARTY-NOTICES.txt`,
`${PACKAGE_ID}/l10n/zh-Hans.json`,
+ `${PACKAGE_ID}/scripts/lithe_rpc.py`,
+ `${PACKAGE_ID}/scripts/windows_job.py`,
+ `${PACKAGE_ID}/scripts/backend.py`,
`${PACKAGE_ID}/scripts/build_model.py`,
+ `${PACKAGE_ID}/scripts/build_provider.py`,
+ `${PACKAGE_ID}/scripts/toolchain_provider.py`,
`${PACKAGE_ID}/scripts/debugpy_adapter.py`,
`${PACKAGE_ID}/vendor/debugpy/adapter/__main__.py`,
`${PACKAGE_ID}/vendor/debugpy/ThirdPartyNotices.txt`,
@@ -92,7 +97,13 @@ test("every built archive has safe paths, no bytecode or symlinks, and valid pla
const isWindows = archive.platform.startsWith("windows-");
const pyreflyServer = manifest.languageServers.find((s) => s.languageID === "python");
- assert.equal(pyreflyServer.launch.path, isWindows ? "bin/pyrefly.exe" : "bin/pyrefly");
+ assert.deepEqual(pyreflyServer.launch, {
+ kind: "backend",
+ function: "pyrefly.resolveLaunch",
+ timeoutMilliseconds: 30000,
+ });
+ assert.equal("arguments" in pyreflyServer, false);
+ assert.equal("validationArguments" in pyreflyServer, false);
const generator = manifest.projectGenerators.find((g) => g.id === "python-project");
const venvCommands = generator.steps.filter((s) => s.kind === "command" && s.command !== "uv").map((s) => s.command);
diff --git a/scripts/test-rpc.py b/scripts/test-rpc.py
new file mode 100644
index 0000000..6f235c3
--- /dev/null
+++ b/scripts/test-rpc.py
@@ -0,0 +1,126 @@
+"""Exercise Python request cancellation and child ownership with bounded handshakes."""
+
+import io
+from pathlib import Path
+import os
+import signal
+import socket
+import subprocess
+import sys
+import threading
+import unittest
+
+sys.path.insert(0, sys.argv.pop(1))
+from lithe_rpc import CancelToken, CancelledError, FrameDecoder, JsonRpcServer, run_bounded_process
+
+
+class DeferredExecutor:
+ def __init__(self):
+ self.tasks = []
+
+ def submit(self, callback, *args):
+ self.tasks.append((callback, args))
+
+ def run(self):
+ callback, args = self.tasks.pop(0)
+ callback(*args)
+
+
+class CancellationTests(unittest.TestCase):
+ def test_cancel_before_worker_starts(self):
+ invoked = []
+ server = JsonRpcServer(name="cancellation-test")
+ server._executor.shutdown()
+ server._executor = DeferredExecutor()
+ server._phase = "ready"
+ server._functions_version = 0
+ server._output_stream = io.BytesIO()
+ server.function("test.call", lambda params, context: invoked.append(True))
+ server._dispatch({
+ "jsonrpc": "2.0", "id": 1, "method": "lithe/function/invoke",
+ "params": {"functionID": "test.call", "params": {}},
+ })
+ server._dispatch({"jsonrpc": "2.0", "method": "$/cancelRequest", "params": {"id": 1}})
+ server._executor.run()
+ response, = FrameDecoder().push(server._output_stream.getvalue())
+ self.assertEqual(invoked, [])
+ self.assertEqual(response["error"]["code"], -32800)
+
+ def test_worker_closes_descendants_on_cancel_or_parent_exit(self):
+ child = """
+import os, signal, socket, sys, threading
+if os.name != 'nt':
+ signal.signal(signal.SIGTERM, signal.SIG_IGN)
+with socket.create_connection(('127.0.0.1', int(sys.argv[1])), timeout=5) as conn:
+ conn.sendall(str(os.getpid()).encode('ascii') + b'\\n')
+ print('ready', flush=True)
+ threading.Event().wait(20)
+"""
+ parent = """
+import subprocess, sys
+process = subprocess.Popen([sys.executable, '-I', '-B', '-c', sys.argv[1], sys.argv[2]],
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True)
+try:
+ assert process.stdout.readline() == 'ready\\n'
+ if sys.argv[3] == 'cancel':
+ process.wait(timeout=20)
+finally:
+ process.stdout.close()
+"""
+ for mode in ("cancel", "exit"):
+ with self.subTest(mode=mode), socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ listener.listen()
+ listener.settimeout(5)
+ token = CancelToken()
+ result = []
+
+ def run():
+ try:
+ result.append(run_bounded_process(
+ [sys.executable, "-I", "-B", "-c", parent, child,
+ str(listener.getsockname()[1]), mode],
+ cwd=str(Path.cwd()),
+ env=dict(os.environ),
+ cancel_token=token,
+ timeout_seconds=10,
+ ))
+ except Exception as error:
+ result.append(error)
+
+ worker = threading.Thread(target=run, daemon=True)
+ worker.start()
+ pid = None
+ try:
+ conn, _address = listener.accept()
+ with conn, conn.makefile("rb") as ready:
+ conn.settimeout(5)
+ pid = int(ready.readline(32))
+ if mode == "cancel":
+ token.cancel()
+ worker.join(6)
+ self.assertFalse(worker.is_alive(), "subprocess cleanup did not finish")
+ try:
+ self.assertEqual(ready.read(1), b"", "descendant still owns its connection")
+ except ConnectionResetError:
+ # Job termination can close a Windows socket with
+ # a reset instead of an orderly end-of-stream.
+ if os.name != "nt":
+ raise
+ pid = None
+ if mode == "cancel":
+ self.assertIsInstance(result[0], CancelledError)
+ else:
+ self.assertEqual(result, [(0, "", False)])
+ finally:
+ token.cancel()
+ if pid is not None:
+ try:
+ os.kill(pid, signal.SIGTERM if os.name == "nt" else signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ worker.join(6)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/test.mjs b/scripts/test.mjs
index 0672a57..781d6fe 100644
--- a/scripts/test.mjs
+++ b/scripts/test.mjs
@@ -1,10 +1,11 @@
#!/usr/bin/env node
-// Runs static contract checks, unit tests for scripts/build_model.py, and live
-// end-to-end smoke tests against the unpacked plugin package (pyrefly --version,
-// pyrefly lsp with .venv resolution, project template rendering, debugpy DAP launch),
+// Runs static contract checks, unit + protocol tests for scripts/{backend,build_model,build_provider,toolchain_provider}.py,
+// and live end-to-end smoke tests against the unpacked plugin package (backend-resolved pyrefly launch with
+// external tools.python.executable injection and .venv fallback, toolchains/query, pytest --collect-only discovery
+// and JUnit XML execution, cancellation process-tree cleanup, project templates, and debugpy DAP launch),
// asserting 100% file-list and SHA-256 immutability of the installed plugin directory.
//
-// PYTHON selects the Python executable (default python3 on Unix, python on Windows).
+// PYTHON selects the base Python executable (default python3 on Unix, python on Windows).
// LITHE_TEST_PLUGIN_DIR tests an already-unpacked archive directory; when unset,
// scripts/test.mjs packages (if needed) and unpacks the current platform archive
// under a temporary path containing spaces, matching Lithe's plugin install layout.
@@ -24,7 +25,7 @@ import {
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
-import { dirname, join, resolve } from "node:path";
+import { dirname, join, normalize, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { readZipEntries } from "./lib/archive.mjs";
import { ASSET_PREFIX, manifestForPlatform, PACKAGE_ID, packagePlatforms, sha256File } from "./package.mjs";
@@ -49,6 +50,11 @@ function detectHostPlatform() {
return `${osPart}-${archPart}`;
}
+function fileUri(absPath) {
+ const norm = absPath.replace(/\\/g, "/");
+ return new URL(`file://${norm.startsWith("/") ? "" : "/"}${norm}`).href;
+}
+
function run(command, args, { cwd, env = process.env } = {}) {
const result = spawnSync(command, args, {
cwd,
@@ -69,6 +75,53 @@ function run(command, args, { cwd, env = process.env } = {}) {
return result.stdout;
}
+function hasPytest(executable, extraEnv = {}) {
+ if (!executable) return false;
+ const res = spawnSync(executable, ["-I", "-B", "-c", "import pytest"], {
+ env: { ...process.env, ...extraEnv },
+ stdio: "ignore",
+ timeout: 8_000,
+ windowsHide: true,
+ });
+ if (res.status === 0) return true;
+ // Re-check without -I in case pytest is installed in user site-packages or PYTHONPATH.
+ const resUser = spawnSync(executable, ["-B", "-c", "import pytest"], {
+ env: { ...process.env, ...extraEnv },
+ stdio: "ignore",
+ timeout: 8_000,
+ windowsHide: true,
+ });
+ return resUser.status === 0;
+}
+
+function resolvePytestRuntime() {
+ const executable = process.env.PYTEST_PYTHON ?? pythonCmd;
+ assert.ok(hasPytest(executable), "Install pytest in PYTHON or set PYTEST_PYTHON to an interpreter with pytest");
+ return run(executable, ["-B", "-c", "import sys; print(sys.executable)"]).trim();
+}
+
+/** Creates an isolated virtualenv that is guaranteed NOT to have `pytest` installed. */
+function ensureNoPytestPython(scratchDir) {
+ if (!hasPytest(pythonCmd)) {
+ return run(pythonCmd, ["-B", "-c", "import sys; print(sys.executable)"]).trim();
+ }
+ const bareVenv = join(scratchDir, "bare-no-pytest-venv");
+ run(pythonCmd, ["-m", "venv", "--without-pip", bareVenv]);
+ return process.platform === "win32"
+ ? join(bareVenv, "Scripts", "python.exe")
+ : join(bareVenv, "bin", "python3");
+}
+
+function isProcessAlive(pid) {
+ if (!Number.isInteger(pid) || pid <= 0) return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
function unpackZipToDir(zipPath, destRoot) {
for (const entry of readZipEntries(readFileSync(zipPath))) {
if (entry.isDirectory) continue;
@@ -101,42 +154,13 @@ function snapshotDirectoryHashes(rootDir) {
return Object.fromEntries(map);
}
-function setDirectoryTreeReadOnly(rootDir, readOnly) {
- if (process.platform === "win32") return;
- const dirs = [];
- function walk(currentDir) {
- dirs.push(currentDir);
- for (const name of readdirSync(currentDir)) {
- const abs = join(currentDir, name);
- const stat = lstatSync(abs);
- if (stat.isDirectory()) {
- if (!readOnly) chmodSync(abs, 0o755);
- walk(abs);
- } else if (stat.isFile()) {
- const execBit = (stat.mode & 0o111) !== 0;
- if (readOnly) {
- chmodSync(abs, execBit ? 0o555 : 0o444);
- } else {
- chmodSync(abs, execBit ? 0o755 : 0o644);
- }
- }
- }
- }
- if (!readOnly) chmodSync(rootDir, 0o755);
- walk(rootDir);
- if (readOnly) {
- for (const dir of dirs.reverse()) {
- chmodSync(dir, 0o555);
- }
- }
-}
-
/** Sends framing-based JSON-RPC / DAP messages over stdio with bounded timeout. */
class FramedStdioPeer {
constructor(child) {
this.child = child;
this.buffer = Buffer.alloc(0);
this.messages = [];
+ this.allReceived = [];
this.waiters = [];
this.stderr = "";
@@ -149,6 +173,7 @@ class FramedStdioPeer {
});
child.on("close", () => {
for (const waiter of this.waiters.splice(0)) {
+ clearTimeout(waiter.timer);
waiter.reject(new Error(`Process exited early. stderr:\n${this.stderr}`));
}
});
@@ -161,13 +186,14 @@ class FramedStdioPeer {
const header = this.buffer.subarray(0, sep).toString("ascii");
const match = /Content-Length:\s*(\d+)/i.exec(header);
if (!match) {
- throw new Error(`Missing Content-Length header: ${header}`);
+ throw new Error(`Non-protocol stdout output or missing Content-Length header: ${header}`);
}
const length = Number.parseInt(match[1], 10);
const bodyStart = sep + 4;
if (this.buffer.length < bodyStart + length) return;
const payload = JSON.parse(this.buffer.subarray(bodyStart, bodyStart + length).toString("utf8"));
this.buffer = this.buffer.subarray(bodyStart + length);
+ this.allReceived.push(payload);
let consumed = false;
for (let i = 0; i < this.waiters.length; i += 1) {
if (this.waiters[i].predicate(payload)) {
@@ -211,6 +237,21 @@ class FramedStdioPeer {
});
}
+ async waitExit(timeoutMs = 5_000) {
+ if (this.child.exitCode !== null || this.child.signalCode !== null) {
+ return this.child.exitCode;
+ }
+ return new Promise((resolvePromise, rejectPromise) => {
+ const timer = setTimeout(() => {
+ rejectPromise(new Error(`Timed out waiting for process exit. stderr:\n${this.stderr}`));
+ }, timeoutMs);
+ this.child.once("close", (code) => {
+ clearTimeout(timer);
+ resolvePromise(code);
+ });
+ });
+ }
+
async closeAndKill(timeoutMs = 5_000) {
if (this.child.exitCode !== null || this.child.signalCode !== null) return;
await new Promise((resolvePromise) => {
@@ -245,7 +286,6 @@ async function check(name, body) {
const scratch = realpathSync(mkdtempSync(join(tmpdir(), "lithe-python-test-")));
let unpackedPluginDir = null;
-let madeReadOnly = false;
try {
const sourceManifest = JSON.parse(readFileSync(join(ROOT, PACKAGE_ID, "plugin.json"), "utf8"));
@@ -267,19 +307,21 @@ try {
const pluginManifest = JSON.parse(readFileSync(join(unpackedPluginDir, "plugin.json"), "utf8"));
- await check("Unix and Windows plugin.json + zh-Hans.json satisfy contract invariants", () => {
+ await check("Unix and Windows plugin.json + zh-Hans.json satisfy M3 contract invariants", () => {
for (const platform of Object.keys(lock.pyrefly.platforms)) {
const variant = manifestForPlatform(sourceManifest, platform, lock);
assert.equal(variant.schemaVersion, 0);
assert.equal(variant.pluginAPIVersion, 0);
assert.equal(variant.id, "io.github.lithe-idea.python-support");
+ assert.equal(variant.version, "0.2.0");
assert.equal(variant.vendor.id, "io.github.lithe-idea");
assert.equal(variant.vendor.signatureRequirement, "none");
assert.equal("commandInstallers" in variant, false, "must not declare commandInstallers");
+ assert.equal("toolchainProviders" in variant, false, "must omit toolchainProviders until desktop host declares it");
assert.equal("$schema" in variant, false, "plugin.json must not contain $schema");
- assert.equal("description" in variant, false, "plugin.json must not contain unknown top-level description");
- assert.equal("license" in variant, false, "plugin.json must not contain unknown top-level license");
assert.deepEqual(Object.keys(variant.requires).sort(), [
+ "backend",
+ "buildProviders",
"buildSystems",
"debugAdapters",
"languageServers",
@@ -289,22 +331,80 @@ try {
"settings",
"toolDefinitions",
]);
+ for (const ver of Object.values(variant.requires)) {
+ assert.equal(ver, 0);
+ }
+ assert.deepEqual([...variant.permissions].sort(), [
+ "backend.launch",
+ "debug.attach",
+ "debug.launch",
+ "languageServer.launch",
+ "process.build",
+ "project.generate",
+ ]);
+
+ assert.deepEqual(variant.backend, {
+ launch: {
+ kind: "runtime",
+ tool: "python",
+ minimumVersion: "3.9",
+ runtimeArguments: ["-I", "-B"],
+ entry: "scripts/backend.py",
+ },
+ arguments: ["--state", "${stateDir}"],
+ });
const pyLang = variant.languages[0];
- assert.equal("shebang" in pyLang, false, "languages[0] must not declare shebang");
+ assert.equal("shebang" in pyLang, false);
assert.deepEqual(pyLang.fileExtensions, ["py", "pyi", "pyw"]);
+ assert.deepEqual(pyLang.dependencies.projectDependencyPaths, [".venv", "venv", ".conda"]);
const pyTool = variant.toolDefinitions[0];
assert.equal("pathPrepend" in pyTool, false, "toolDefinitions[0] must omit unsafe pathPrepend");
- assert.ok(pyTool.discovery.length <= 16, "discovery rules must fit Core limit of 16");
+ assert.equal(pyTool.discovery.length, 16, "discovery rules must fit Core limit of 16");
+ const envVars = pyTool.discovery
+ .filter((d) => d.root.kind === "environment")
+ .map((d) => d.root.variable)
+ .sort();
+ assert.deepEqual(envVars, [
+ "APPDATA",
+ "CONDA_ENVS_PATH",
+ "CONDA_PREFIX",
+ "LOCALAPPDATA",
+ "PYENV_ROOT",
+ "UV_PYTHON_INSTALL_DIR",
+ "WORKON_HOME",
+ "XDG_DATA_HOME",
+ ]);
assert.deepEqual(pyTool.launch, ["${executable}", "${runtimeArguments}", "${entry}", "${arguments}"]);
assert.deepEqual(
variant.buildSystems.map((b) => b.id),
["python", "uv", "conda", "ruff"],
);
+ const pyBuild = variant.buildSystems[0];
+ assert.equal(pyBuild.provider.launch.entry, "scripts/build_provider.py");
+ assert.deepEqual(pyBuild.provider.launch.runtimeArguments, ["-I", "-B"]);
+ assert.equal(pyBuild.provider.executesProjectCode, true);
+ assert.equal(pyBuild.provider.mayUseNetwork, false);
+ assert.deepEqual(pyBuild.model, { source: "provider" });
+ assert.equal(pyBuild.test.source, "provider");
+ assert.equal(pyBuild.test.discovery, true);
+ assert.deepEqual(pyBuild.test.filters, ["suite", "case"]);
+ assert.deepEqual(pyBuild.test.arguments, []);
+ assert.deepEqual(pyBuild.test.results, {
+ decoder: "junitXml",
+ reports: [".pytest_cache/lithe-junit.xml"],
+ });
const pyServer = variant.languageServers[0];
+ assert.deepEqual(pyServer.launch, {
+ kind: "backend",
+ function: "pyrefly.resolveLaunch",
+ timeoutMilliseconds: 30000,
+ });
+ assert.equal("arguments" in pyServer, false);
+ assert.equal("validationArguments" in pyServer, false);
assert.equal("pythonPath" in (pyServer.workspaceConfiguration.python ?? {}), false);
const debugAdapter = variant.debugAdapters[0];
@@ -331,17 +431,19 @@ try {
});
// Snapshot unpacked plugin directory while keeping it writable (matching Windows and
- // user-writable plugin directories) so any stray __pycache__ write by a child process
- // such as debugpy/launcher is caught immediately instead of masked by POSIX 0555!
+ // user-writable plugin directories) so any stray __pycache__ or log file write is caught!
const beforeSnapshot = snapshotDirectoryHashes(unpackedPluginDir);
const buildModelScript = join(unpackedPluginDir, "scripts", "build_model.py");
+ const backendScript = join(unpackedPluginDir, "scripts", "backend.py");
+ const buildProviderScript = join(unpackedPluginDir, "scripts", "build_provider.py");
- await check("build_model.py discovers PEP 621 scripts, src/ packages, tests, and .venv exclusions", () => {
+ await check("build_model.py discovers PEP 621 scripts, src/ packages, tests, and .venv/.conda exclusions", () => {
const proj = join(scratch, "case-pep621");
mkdirSync(join(proj, "src", "demo_pkg"), { recursive: true });
mkdirSync(join(proj, "tests"), { recursive: true });
mkdirSync(join(proj, ".venv", "bin"), { recursive: true });
+ mkdirSync(join(proj, ".conda", "conda-meta"), { recursive: true });
writeFileSync(
join(proj, "pyproject.toml"),
[
@@ -373,12 +475,12 @@ try {
assert.ok(byName["demo_pkg"], "expected src/demo_pkg/__main__.py target");
assert.ok(byName["tests"], "expected tests target");
assert.deepEqual(model.contentRoots, [
+ { path: ".conda", kind: "excluded" },
{ path: ".venv", kind: "excluded" },
{ path: "src", kind: "source" },
{ path: "tests", kind: "testSource" },
]);
- // Execute the generated entrypoint runner to verify it invokes demo_pkg.cli:main without editable install.
run(pythonCmd, ["-I", "-B", "-c", byName["demo-cli"].properties.runner], { cwd: proj });
});
@@ -399,14 +501,8 @@ try {
join(proj, "api.py"),
`open(${JSON.stringify(canary)}, "w").write("bad")\nfrom fastapi import FastAPI\napp = FastAPI()\ndef create_app():\n return FastAPI()\n`,
);
- writeFileSync(
- join(proj, "web.py"),
- "from flask import Flask\napp = Flask(__name__)\n",
- );
- writeFileSync(
- join(proj, "worker.py"),
- 'def run():\n pass\nif __name__ == "__main__":\n run()\n',
- );
+ writeFileSync(join(proj, "web.py"), "from flask import Flask\napp = Flask(__name__)\n");
+ writeFileSync(join(proj, "worker.py"), 'def run():\n pass\nif __name__ == "__main__":\n run()\n');
writeFileSync(join(proj, "mypkg", "__init__.py"), "");
writeFileSync(join(proj, "mypkg", "__main__.py"), "print('hi')\n");
@@ -425,16 +521,10 @@ try {
assert.deepEqual(byName["mypkg"].tags, ["application", "module"]);
assert.deepEqual(byName["worker.py"].tags, ["application", "script"]);
- // Verify nested-instance invocation where host sets cwd = /services/sub and passes ${root} = "services/sub".
+ // Verify vendored tomli fallback when stdlib tomllib is unavailable (Python 3.9/3.10 simulation).
const nested = join(scratch, "workspace-nested", "services", "sub");
mkdirSync(nested, { recursive: true });
writeFileSync(join(nested, "pyproject.toml"), '[project]\nname = "nested-svc"\nversion = "0.1.0"\n');
- const nestedOut = join(scratch, "nested-out.json");
- run(pythonCmd, ["-I", "-B", buildModelScript, "services/sub", nestedOut], { cwd: nested });
- const nestedModel = JSON.parse(readFileSync(nestedOut, "utf8"));
- assert.equal(nestedModel.projects[0].name, "nested-svc");
-
- // Verify vendored tomli fallback when stdlib tomllib is unavailable (Python 3.9/3.10 simulation).
const tomliOut = join(scratch, "tomli-fallback-out.json");
run(pythonCmd, [
"-I",
@@ -447,8 +537,6 @@ try {
]);
assert.equal(JSON.parse(readFileSync(tomliOut, "utf8")).projects[0].name, "nested-svc");
- // Verify non-zero exit on missing directory so host logs host.commandFailed,
- // and assert stderr contains only controlled diagnostic code without leaking paths.
const secretMissingPath = join(scratch, "secret-path-token-do-not-log");
const missing = spawnSync(pythonCmd, ["-I", "-B", buildModelScript, secretMissingPath, tomliOut], {
encoding: "utf8",
@@ -459,11 +547,1005 @@ try {
assert.ok(!missing.stderr.includes("secret-path-token-do-not-log"), "stderr must never echo raw paths");
});
+ await check("backend.py negotiates litheLogging + litheFunctions, resolves Unix/Windows pyrefly launch, and injects external tools.python.executable into pyrefly LSP", async () => {
+ const stateDir = join(scratch, "backend-state");
+ const wsStateDir = join(scratch, "backend-ws-state");
+ const logDir = join(scratch, "backend-log");
+ const tempDir = join(scratch, "backend-temp");
+ for (const d of [stateDir, wsStateDir, logDir, tempDir]) mkdirSync(d, { recursive: true });
+
+ // Create an EXTERNAL virtual environment outside the workspace with a unique package `external_env_pkg`.
+ const extVenvRoot = join(scratch, "external-conda-like-env");
+ run(pythonCmd, ["-m", "venv", extVenvRoot]);
+ const extPython =
+ process.platform === "win32"
+ ? join(extVenvRoot, "Scripts", "python.exe")
+ : join(extVenvRoot, "bin", "python3");
+ const extSite = run(extPython, ["-I", "-B", "-c", "import site; print(site.getsitepackages()[0])"]).trim();
+ mkdirSync(join(extSite, "external_env_pkg"), { recursive: true });
+ writeFileSync(join(extSite, "external_env_pkg", "__init__.py"), "def magic_number() -> int:\n return 7\n");
+
+ const child = spawn(pythonCmd, ["-I", "-B", backendScript, "--state", stateDir], {
+ cwd: scratch,
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ });
+ const peer = new FramedStdioPeer(child);
+ let resolvedUnixAnswer = null;
+
+ try {
+ // 1. Initialize without litheLogging MUST be refused (-32600) while keeping session alive for valid retry.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: { capabilities: { experimental: { litheFunctions: { versions: [0] } } } },
+ });
+ const refusedInit = await peer.waitFor((m) => m.id === 1, "initialize refusal without litheLogging");
+ assert.equal(refusedInit.error?.code, -32600);
+
+ // 2. Initialize with litheLogging 0, litheFunctions 0, and litheToolchains 0.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 2,
+ method: "initialize",
+ params: {
+ capabilities: {
+ experimental: {
+ litheLogging: { versions: [0] },
+ litheFunctions: { versions: [0] },
+ litheToolchains: { versions: [0], providers: ["python"] },
+ },
+ },
+ },
+ });
+ const initOk = await peer.waitFor((m) => m.id === 2 && "result" in m, "backend initialize response");
+ assert.deepEqual(initOk.result.capabilities.experimental.litheLogging, { version: 0 });
+ assert.deepEqual(initOk.result.capabilities.experimental.litheFunctions, {
+ version: 0,
+ functions: [{ id: "pyrefly.resolveLaunch" }, { id: "python.inspectEnvironment" }],
+ });
+ assert.deepEqual(initOk.result.capabilities.experimental.litheToolchains, {
+ version: 0,
+ providers: ["python"],
+ });
+
+ // 3. Resolve launch with external tools.python.executable on Unix.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 3,
+ method: "lithe/function/invoke",
+ params: {
+ operationID: "op-launch-unix",
+ functionID: "pyrefly.resolveLaunch",
+ context: { contextID: "ctx-1", generation: 1 },
+ params: {
+ serverID: "python",
+ platform: { os: process.platform === "win32" ? "windows" : "macos", arch: process.arch },
+ stateDirectory: stateDir,
+ workspaceStateDirectory: wsStateDir,
+ logDirectory: logDir,
+ temporaryDirectory: tempDir,
+ settings: {
+ typeCheckingMode: "strict",
+ displayTypeErrors: "force-on",
+ diagnosticMode: "openFilesOnly",
+ autoImportCompletions: true,
+ completeFunctionParens: true,
+ importFormat: "relative",
+ },
+ tools: {
+ python: {
+ executable: extPython,
+ home: extVenvRoot,
+ version: "3.12.0",
+ },
+ },
+ },
+ },
+ });
+ const launchResp = await peer.waitFor((m) => m.id === 3, "pyrefly.resolveLaunch response");
+ resolvedUnixAnswer = launchResp.result;
+ assert.deepEqual(resolvedUnixAnswer.executable, {
+ kind: "packaged",
+ path: process.platform === "win32" ? "bin/pyrefly.exe" : "bin/pyrefly",
+ });
+ assert.deepEqual(resolvedUnixAnswer.arguments, ["lsp"]);
+ assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.pythonPath, extPython);
+ assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.pyrefly.typeCheckingMode, "strict");
+ assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.analysis.completeFunctionParens, true);
+
+ // Verify lithe/log operationFinished arrived strictly BEFORE response id=3!
+ const idxLog3 = peer.allReceived.findIndex(
+ (m) => m.method === "lithe/log" && m.params?.operationId === "op-launch-unix" && m.params?.kind === "operationFinished",
+ );
+ const idxResp3 = peer.allReceived.findIndex((m) => m.id === 3);
+ assert.ok(idxLog3 >= 0 && idxLog3 < idxResp3, "lithe/log operationFinished must precede RPC response");
+
+ // 4. Resolve launch on Windows platform without tools.python (graceful fallback without pythonPath).
+ peer.send({
+ jsonrpc: "2.0",
+ id: 4,
+ method: "lithe/function/invoke",
+ params: {
+ operationID: "op-launch-win-fallback",
+ functionID: "pyrefly.resolveLaunch",
+ context: { contextID: "ctx-2", generation: 1 },
+ params: {
+ serverID: "python",
+ platform: { os: "windows", arch: "x86_64" },
+ stateDirectory: stateDir,
+ workspaceStateDirectory: wsStateDir,
+ logDirectory: logDir,
+ temporaryDirectory: tempDir,
+ settings: {},
+ },
+ },
+ });
+ const winFallback = await peer.waitFor((m) => m.id === 4, "Windows fallback resolveLaunch");
+ assert.deepEqual(winFallback.result.executable, { kind: "packaged", path: "bin/pyrefly.exe" });
+ assert.equal("pythonPath" in winFallback.result.workspaceConfiguration.python, false);
+
+ // 5. Malformed tools.python.executable emits degraded WARN and falls back; subsequent valid call emits recovered WARN.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 5,
+ method: "lithe/function/invoke",
+ params: {
+ operationID: "op-launch-degraded",
+ functionID: "pyrefly.resolveLaunch",
+ context: { contextID: "ctx-deg", generation: 1 },
+ params: {
+ serverID: "python",
+ platform: { os: "macos", arch: "aarch64" },
+ stateDirectory: stateDir,
+ workspaceStateDirectory: wsStateDir,
+ logDirectory: logDir,
+ temporaryDirectory: tempDir,
+ settings: {},
+ tools: { python: { executable: " bad\npath " } },
+ },
+ },
+ });
+ const degResp = await peer.waitFor((m) => m.id === 5, "degraded resolveLaunch");
+ assert.equal("pythonPath" in degResp.result.workspaceConfiguration.python, false);
+ assert.ok(
+ peer.allReceived.some(
+ (m) =>
+ m.method === "lithe/log" &&
+ m.params?.operationId === "op-launch-degraded" &&
+ m.params?.kind === "degraded" &&
+ m.params?.code === "invalid_tool_hint",
+ ),
+ "Expected degraded diagnostic for malformed tool hint",
+ );
+
+ peer.send({
+ jsonrpc: "2.0",
+ id: 6,
+ method: "lithe/function/invoke",
+ params: {
+ operationID: "op-launch-recovered",
+ functionID: "pyrefly.resolveLaunch",
+ context: { contextID: "ctx-deg", generation: 2 },
+ params: {
+ serverID: "python",
+ platform: { os: "macos", arch: "aarch64" },
+ stateDirectory: stateDir,
+ workspaceStateDirectory: wsStateDir,
+ logDirectory: logDir,
+ temporaryDirectory: tempDir,
+ settings: {},
+ tools: { python: { executable: extPython } },
+ },
+ },
+ });
+ await peer.waitFor((m) => m.id === 6, "recovered resolveLaunch");
+ assert.ok(
+ peer.allReceived.some(
+ (m) =>
+ m.method === "lithe/log" &&
+ m.params?.operationId === "op-launch-recovered" &&
+ m.params?.kind === "recovered" &&
+ m.params?.code === "tool_hint_restored",
+ ),
+ "Expected recovered diagnostic after valid tool hint",
+ );
+
+ // 6. High-frequency python.inspectEnvironment suppresses INFO on success but still logs ERROR on failure.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 7,
+ method: "lithe/function/invoke",
+ params: {
+ operationID: "op-inspect-quiet",
+ functionID: "python.inspectEnvironment",
+ params: { executable: extPython },
+ },
+ });
+ const inspectOk = await peer.waitFor((m) => m.id === 7, "inspectEnvironment success");
+ assert.equal(inspectOk.result.isVirtualEnv, true);
+ assert.equal(
+ peer.allReceived.some((m) => m.method === "lithe/log" && m.params?.operationId === "op-inspect-quiet"),
+ false,
+ "suppressSuccessDiagnostics must suppress operationFinished INFO",
+ );
+
+ peer.send({
+ jsonrpc: "2.0",
+ id: 8,
+ method: "lithe/function/invoke",
+ params: {
+ operationID: "op-inspect-fail",
+ functionID: "python.inspectEnvironment",
+ params: { executable: "relative/secret-path-token/python" },
+ },
+ });
+ const inspectErr = await peer.waitFor((m) => m.id === 8, "inspectEnvironment failure");
+ assert.equal(inspectErr.error?.code, -32000);
+ assert.equal(inspectErr.error?.data?.code, "python.invalidExecutable");
+ assert.ok(!inspectErr.error.message.includes("secret-path-token"));
+ assert.ok(
+ peer.allReceived.some(
+ (m) =>
+ m.method === "lithe/log" &&
+ m.params?.operationId === "op-inspect-fail" &&
+ m.params?.kind === "operationFailed" &&
+ m.params?.code === "python.invalidExecutable",
+ ),
+ "Suppressed functions MUST still emit operationFailed ERROR",
+ );
+
+ // 6b. Unknown method and unknown functionID return static messages without echoing raw input.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 81,
+ method: "secret/path/unknown-method",
+ params: {},
+ });
+ const unknownMethodErr = await peer.waitFor((m) => m.id === 81, "unknown method error");
+ assert.equal(unknownMethodErr.error?.code, -32601);
+ assert.equal(unknownMethodErr.error?.message, "The requested method is not supported.");
+ assert.ok(!unknownMethodErr.error.message.includes("secret"));
+
+ peer.send({
+ jsonrpc: "2.0",
+ id: 82,
+ method: "lithe/function/invoke",
+ params: {
+ operationID: "op-unknown-fn",
+ functionID: "secret.unregistered.fn",
+ params: {},
+ },
+ });
+ const unknownFnErr = await peer.waitFor((m) => m.id === 82, "unknown function error");
+ assert.equal(unknownFnErr.error?.code, -32602);
+ assert.equal(unknownFnErr.error?.message, "The requested plugin function is not registered.");
+ assert.ok(!unknownFnErr.error.message.includes("secret"));
+
+ // 7. Clean shutdown + exit without creating any custom log files.
+ peer.send({ jsonrpc: "2.0", id: 9, method: "shutdown", params: null });
+ await peer.waitFor((m) => m.id === 9 && m.result === null, "backend shutdown");
+ peer.send({ jsonrpc: "2.0", method: "exit", params: null });
+ const exitCode = await peer.waitExit();
+ assert.equal(exitCode, 0);
+ assert.deepEqual(readdirSync(logDir), [], "backend.py must create zero custom log files");
+ } finally {
+ await peer.closeAndKill();
+ }
+
+ // 8. Verify live packaged pyrefly LSP uses the backend-injected python.pythonPath to resolve external_env_pkg
+ // in a bare workspace that has NO .venv!
+ const bareWs = join(scratch, "ws-external-env-lsp");
+ mkdirSync(bareWs, { recursive: true });
+ const srcFile = join(bareWs, "use_ext.py");
+ const srcContent = "from external_env_pkg import magic_number\nbad: str = magic_number()\n";
+ writeFileSync(srcFile, srcContent);
+
+ const pyreflyBin = join(unpackedPluginDir, ...resolvedUnixAnswer.executable.path.split("/"));
+ const versionOut = run(pyreflyBin, ["--version"], { cwd: bareWs }).trim();
+ assert.match(versionOut, /pyrefly\s+1\.4\.1/i);
+
+ const lspChild = spawn(pyreflyBin, resolvedUnixAnswer.arguments, {
+ cwd: bareWs,
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ });
+ const lspPeer = new FramedStdioPeer(lspChild);
+ try {
+ const rootUri = fileUri(bareWs);
+ const docUri = fileUri(srcFile);
+ lspPeer.send({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ processId: process.pid,
+ rootUri,
+ workspaceFolders: [{ uri: rootUri, name: "ext-ws" }],
+ capabilities: {
+ workspace: { configuration: true },
+ textDocument: { publishDiagnostics: {} },
+ },
+ },
+ });
+ await lspPeer.waitFor((m) => m.id === 1 && "result" in m, "pyrefly initialize");
+ lspPeer.send({ jsonrpc: "2.0", method: "initialized", params: {} });
+
+ let opened = false;
+ let diagMsg = null;
+ const deadline = Date.now() + 20_000;
+ while (Date.now() < deadline) {
+ const msg = await lspPeer.waitFor(() => true, "pyrefly LSP message", 15_000);
+ if (msg.method === "workspace/configuration" && msg.id !== undefined) {
+ const items = msg.params?.items ?? [];
+ lspPeer.send({
+ jsonrpc: "2.0",
+ id: msg.id,
+ result: items.map((it) =>
+ it.section === "python" ? resolvedUnixAnswer.workspaceConfiguration.python : {},
+ ),
+ });
+ if (!opened) {
+ opened = true;
+ lspPeer.send({
+ jsonrpc: "2.0",
+ method: "textDocument/didOpen",
+ params: {
+ textDocument: { uri: docUri, languageId: "python", version: 1, text: srcContent },
+ },
+ });
+ }
+ } else if (msg.id !== undefined && msg.method) {
+ lspPeer.send({ jsonrpc: "2.0", id: msg.id, result: null });
+ } else if (msg.method === "textDocument/publishDiagnostics" && msg.params?.uri === docUri) {
+ if ((msg.params.diagnostics ?? []).length > 0) {
+ diagMsg = msg;
+ break;
+ }
+ }
+ }
+ assert.ok(diagMsg, "Expected diagnostics from pyrefly with injected pythonPath");
+ const codes = diagMsg.params.diagnostics.map((d) => d.code);
+ assert.ok(
+ !codes.includes("missing-import"),
+ `Expected backend-injected pythonPath to resolve external_env_pkg, got: ${JSON.stringify(diagMsg.params.diagnostics)}`,
+ );
+ lspPeer.send({ jsonrpc: "2.0", id: 2, method: "shutdown", params: null });
+ await lspPeer.waitFor((m) => m.id === 2, "pyrefly shutdown", 10_000);
+ lspPeer.send({ jsonrpc: "2.0", method: "exit", params: null });
+ } finally {
+ await lspPeer.closeAndKill();
+ }
+ });
+
+ await check("toolchain_provider.py answers toolchains/query for conda, uv, pyenv, Poetry, Pipenv, .python-version, and pyproject.toml", async () => {
+ const fakeHome = join(scratch, "fake-home");
+ const condaEnvDir = join(scratch, "conda-envs", "ml-311");
+ const uvPyDir = join(scratch, "uv-pythons", "cpython-3.12.6-macos-aarch64-none");
+ const pyenvVerDir = join(scratch, "pyenv-root", "versions", "3.10.14");
+ const workonRoot = join(scratch, "workon-envs");
+ const wsRoot = join(scratch, "tc-workspace");
+ mkdirSync(wsRoot, { recursive: true });
+ // Workspace-local .venv MUST be excluded from provider installations per toolchains contract!
+ const wsLocalVenv = join(wsRoot, ".venv");
+
+ const makeFakePythonHome = (dir, ver, isConda = false) => {
+ const binDir = process.platform === "win32" ? (isConda ? dir : join(dir, "Scripts")) : join(dir, "bin");
+ mkdirSync(binDir, { recursive: true });
+ const exeName = process.platform === "win32" ? "python.exe" : "python3";
+ const exePath = join(binDir, exeName);
+ writeFileSync(exePath, process.platform === "win32" ? "MZ" : "#!/bin/sh\necho Python " + ver + "\n");
+ if (process.platform !== "win32") chmodSync(exePath, 0o755);
+ if (isConda) {
+ mkdirSync(join(dir, "conda-meta"), { recursive: true });
+ writeFileSync(
+ join(dir, "conda-meta", `python-${ver}-0.json`),
+ JSON.stringify({ name: "python", version: ver }),
+ );
+ } else {
+ writeFileSync(join(dir, "pyvenv.cfg"), `version_info = ${ver}\n`);
+ }
+ };
+
+ makeFakePythonHome(condaEnvDir, "3.11.9", true);
+ makeFakePythonHome(uvPyDir, "3.12.6", false);
+ makeFakePythonHome(pyenvVerDir, "3.10.14", false);
+ makeFakePythonHome(wsLocalVenv, "3.12.1", false);
+
+ mkdirSync(join(fakeHome, ".conda"), { recursive: true });
+ const condaRegistry = join(fakeHome, ".conda", "environments.txt");
+ writeFileSync(condaRegistry, `# comment\n${condaEnvDir}\n`);
+ writeFileSync(join(wsRoot, ".python-version"), "3.11\n");
+ writeFileSync(
+ join(wsRoot, "pyproject.toml"),
+ '[project]\nname = "tc-demo"\nrequires-python = ">=3.12"\n',
+ );
+ writeFileSync(join(wsRoot, "Pipfile"), '[[source]]\nname = "pypi"\n');
+
+ // Compute pipenv prefix via python helper to create matching WORKON_HOME env.
+ const pipenvName = run(pythonCmd, [
+ "-I",
+ "-B",
+ "-c",
+ `import sys; sys.path.insert(0, ${JSON.stringify(join(unpackedPluginDir, "scripts"))}); from pathlib import Path; from toolchain_provider import _pipenv_virtualenv_prefix; print(_pipenv_virtualenv_prefix(Path(sys.argv[1]).resolve()))`,
+ wsRoot,
+ ]).trim();
+ const pipenvDir = join(workonRoot, pipenvName);
+ makeFakePythonHome(pipenvDir, "3.12.3", false);
+
+ const discoveryEnv = {
+ HOME: fakeHome,
+ USERPROFILE: fakeHome,
+ UV_PYTHON_INSTALL_DIR: dirname(uvPyDir),
+ PYENV_ROOT: join(scratch, "pyenv-root"),
+ WORKON_HOME: workonRoot,
+ CONDA_ENVS_PATH: "",
+ CONDA_PREFIX: "",
+ };
+ // Windows environment variable names are case-insensitive. Ensure inherited
+ // entries with different capitalization cannot shadow the fixture values.
+ const inherited = Object.fromEntries(
+ Object.entries(process.env).filter(([key]) => !(key.toUpperCase() in discoveryEnv)),
+ );
+ const child = spawn(pythonCmd, ["-I", "-B", backendScript, "--state", join(scratch, "tc-state")], {
+ cwd: scratch,
+ env: { ...inherited, ...discoveryEnv },
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ });
+ const peer = new FramedStdioPeer(child);
+ try {
+ peer.send({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ capabilities: {
+ experimental: {
+ litheLogging: { versions: [0] },
+ litheToolchains: { versions: [0], providers: ["python"] },
+ },
+ },
+ },
+ });
+ await peer.waitFor((m) => m.id === 1 && "result" in m, "toolchain backend init");
+
+ peer.send({
+ jsonrpc: "2.0",
+ id: 2,
+ method: "toolchains/query",
+ params: {
+ operationID: "tc-op-1",
+ generation: 3,
+ providerID: "python",
+ authority: { kind: "local" },
+ tools: ["python"],
+ workspace: { rootID: "root-1", root: wsRoot, directory: "." },
+ context: { contextID: "ctx-tc", generation: 1 },
+ },
+ });
+ const reply = await peer.waitFor((m) => m.id === 2, "toolchains/query reply");
+ assert.equal(reply.result.operationID, "tc-op-1");
+ assert.equal(reply.result.generation, 3);
+ assert.equal(reply.result.providerID, "python");
+
+ // Python and Node may preserve different drive letter and directory
+ // casing for a real path on Windows. Compare native path identities.
+ const pathKey = (path) => {
+ const nativePath = normalize(path);
+ return process.platform === "win32" ? nativePath.toLowerCase() : nativePath;
+ };
+ const expectedPath = (path) => pathKey(realpathSync.native(path));
+ assert.ok(
+ reply.result.watch.map(pathKey).includes(expectedPath(condaRegistry)),
+ "Expected toolchain discovery to read the fixture home",
+ );
+ const homes = reply.result.installations.map((installation) => pathKey(installation.home));
+ assert.ok(homes.includes(expectedPath(condaEnvDir)), "Expected ~/.conda/environments.txt installation");
+ assert.ok(homes.includes(expectedPath(uvPyDir)), "Expected UV_PYTHON_INSTALL_DIR installation");
+ assert.ok(homes.includes(expectedPath(pyenvVerDir)), "Expected PYENV_ROOT installation");
+ assert.ok(homes.includes(expectedPath(pipenvDir)), "Expected WORKON_HOME Pipenv installation");
+ assert.equal(homes.includes(expectedPath(wsLocalVenv)), false, "Must NEVER return workspace-local .venv");
+
+ const bySource = new Map(reply.result.statements.map((statement) => [pathKey(statement.source), statement]));
+ const pyVerStmt = bySource.get(expectedPath(join(wsRoot, ".python-version")));
+ assert.ok(pyVerStmt);
+ assert.equal(pathKey(pyVerStmt.installation), expectedPath(condaEnvDir));
+ const pyprojStmt = bySource.get(expectedPath(join(wsRoot, "pyproject.toml")));
+ assert.ok(pyprojStmt);
+ assert.equal(pathKey(pyprojStmt.installation), expectedPath(uvPyDir));
+ const pipfileStmt = bySource.get(expectedPath(join(wsRoot, "Pipfile")));
+ assert.ok(pipfileStmt);
+ assert.equal(pipfileStmt.kind, "environment");
+ assert.equal(pathKey(pipfileStmt.installation), expectedPath(pipenvDir));
+
+ // Remote authority must return -32071 plugin.toolchain.authorityUnsupported.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 3,
+ method: "toolchains/query",
+ params: {
+ operationID: "tc-op-remote",
+ generation: 4,
+ providerID: "python",
+ authority: { kind: "remote", hostID: "ssh-box" },
+ tools: ["python"],
+ workspace: null,
+ context: null,
+ },
+ });
+ const remoteErr = await peer.waitFor((m) => m.id === 3, "remote authority error");
+ assert.equal(remoteErr.error?.code, -32071);
+ assert.equal(remoteErr.error?.data?.code, "plugin.toolchain.authorityUnsupported");
+
+ peer.send({ jsonrpc: "2.0", id: 4, method: "shutdown", params: null });
+ await peer.waitFor((m) => m.id === 4, "shutdown");
+ peer.send({ jsonrpc: "2.0", method: "exit", params: null });
+ await peer.waitExit();
+ } finally {
+ await peer.closeAndKill();
+ }
+ });
+
+ await check("build_provider.py executes model (with degraded/recovered), pytest --collect-only discovery, pytest JUnit XML test runs, runEntrypoints, and cancellation cleanup", async () => {
+ const pytestExecutable = resolvePytestRuntime();
+ const noPytestExec = ensureNoPytestPython(scratch);
+
+ const wsDir = join(scratch, "pytest-workspace");
+ const cacheDir = join(scratch, "pytest-ws-state");
+ mkdirSync(join(wsDir, "tests"), { recursive: true });
+ mkdirSync(cacheDir, { recursive: true });
+
+ // Start with an intentionally malformed pyproject.toml to verify degraded -> recovered!
+ writeFileSync(join(wsDir, "pyproject.toml"), "[project\nname = 'broken'\n");
+ writeFileSync(join(wsDir, "worker.py"), 'if __name__ == "__main__":\n print("run worker")\n');
+ writeFileSync(
+ join(wsDir, "tests", "test_calc.py"),
+ [
+ "import pytest",
+ "",
+ "@pytest.mark.parametrize('x,expected', [(2, 6), (3, 9)])",
+ "def test_scale(x, expected):",
+ " assert x * 3 == expected",
+ "",
+ "class TestCalc:",
+ " def test_add(self):",
+ " assert 1 + 2 == 3",
+ ].join("\n") + "\n",
+ );
+
+ const child = spawn(pythonCmd, ["-I", "-B", buildProviderScript, "--cache", cacheDir], {
+ cwd: wsDir,
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ });
+ const peer = new FramedStdioPeer(child);
+
+ try {
+ const rootUri = fileUri(wsDir);
+ peer.send({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ rootUri,
+ workspaceFolders: [{ uri: rootUri, name: "pytest-ws" }],
+ capabilities: {
+ experimental: {
+ litheLogging: { versions: [0] },
+ litheBuild: { versions: [1, 0] },
+ },
+ },
+ },
+ });
+ const initResp = await peer.waitFor((m) => m.id === 1 && "result" in m, "build provider initialize");
+ assert.deepEqual(initResp.result.capabilities.experimental.litheBuild, { version: 1 });
+
+ // 1. Degraded lithe/build/model on malformed pyproject.toml.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 2,
+ method: "lithe/build/model",
+ params: {
+ operationID: "op-model-broken",
+ buildSystemID: "python",
+ root: ".",
+ options: {},
+ optionArguments: [],
+ environment: {},
+ },
+ });
+ const brokenModel = await peer.waitFor((m) => m.id === 2, "broken pyproject model");
+ assert.equal(brokenModel.result.format, "litheBuildModel");
+ assert.ok(
+ peer.allReceived.some(
+ (m) =>
+ m.method === "lithe/log" &&
+ m.params?.operationId === "op-model-broken" &&
+ m.params?.kind === "degraded" &&
+ m.params?.code === "pyproject_parse_failed",
+ ),
+ "Expected degraded pyproject_parse_failed log",
+ );
+
+ // Fix pyproject.toml and keep UTF-8 parameter IDs to exercise the Core byte limit.
+ writeFileSync(join(wsDir, "pyproject.toml"), [
+ "[project]",
+ 'name = "calc-suite"',
+ 'version = "0.2.0"',
+ "[tool.pytest.ini_options]",
+ "disable_test_id_escaping_and_forfeit_all_rights_to_community_support = true",
+ "",
+ ].join("\n"));
+ peer.send({
+ jsonrpc: "2.0",
+ id: 3,
+ method: "lithe/build/model",
+ params: {
+ operationID: "op-model-fixed",
+ buildSystemID: "python",
+ root: ".",
+ refresh: true,
+ options: {},
+ optionArguments: [],
+ environment: {},
+ },
+ });
+ const fixedModel = await peer.waitFor((m) => m.id === 3, "fixed pyproject model");
+ assert.equal(fixedModel.result.projects[0].name, "calc-suite");
+ assert.ok(
+ peer.allReceived.some(
+ (m) =>
+ m.method === "lithe/log" &&
+ m.params?.operationId === "op-model-fixed" &&
+ m.params?.kind === "recovered" &&
+ m.params?.code === "pyproject_restored",
+ ),
+ "Expected recovered pyproject_restored log",
+ );
+
+ // 2. lithe/build/discoverTests via pytest --collect-only.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 4,
+ method: "lithe/build/discoverTests",
+ params: {
+ operationID: "op-discover-1",
+ buildSystemID: "python",
+ root: ".",
+ tool: { executable: pytestExecutable },
+ options: {},
+ optionArguments: [],
+ environment: {},
+ },
+ });
+ const discResp = await peer.waitFor((m) => m.id === 4, "discoverTests response");
+ assert.equal(discResp.result.format, "litheTestDiscovery");
+ assert.equal(discResp.result.version, 0);
+ assert.equal(existsSync(join(wsDir, ".pytest_cache")), false, "discoverTests must write cache to workspaceStateDir, not workspace");
+
+ const discoveredCases = discResp.result.tests.map((t) => `${t.suite}::${t.case}`).sort();
+ assert.deepEqual(discoveredCases, [
+ "tests/test_calc.py::TestCalc::test_add",
+ "tests/test_calc.py::test_scale[2-6]",
+ "tests/test_calc.py::test_scale[3-9]",
+ ]);
+ for (const item of discResp.result.tests) {
+ assert.deepEqual(item.project, { name: "calc-suite", path: "." });
+ }
+
+ // 3. Missing pytest returns controlled PluginError python.pytestUnavailable + operationFailed ERROR.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 5,
+ method: "lithe/build/discoverTests",
+ params: {
+ operationID: "op-discover-missing",
+ buildSystemID: "python",
+ root: ".",
+ tool: { executable: noPytestExec },
+ options: {},
+ optionArguments: [],
+ environment: {},
+ },
+ });
+ const missingPytest = await peer.waitFor((m) => m.id === 5, "missing pytest error");
+ assert.equal(missingPytest.error?.code, -32000);
+ assert.equal(missingPytest.error?.data?.code, "python.pytestUnavailable");
+ assert.ok(
+ peer.allReceived.some(
+ (m) =>
+ m.method === "lithe/log" &&
+ m.params?.operationId === "op-discover-missing" &&
+ m.params?.kind === "operationFailed" &&
+ m.params?.code === "python.pytestUnavailable",
+ ),
+ );
+
+ // 4. Execute a single discovered parameterized test via lithe/build/test and verify progress + JUnit XML.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 6,
+ method: "lithe/build/test",
+ params: {
+ operationID: "op-test-single",
+ buildSystemID: "python",
+ root: ".",
+ tool: { executable: pytestExecutable },
+ project: { name: "calc-suite", path: "." },
+ suite: "tests/test_calc.py",
+ case: "test_scale[2-6]",
+ options: {},
+ optionArguments: [],
+ userArguments: [],
+ environment: {},
+ },
+ });
+ const testRunResp = await peer.waitFor((m) => m.id === 6, "lithe/build/test response");
+ assert.equal(testRunResp.result.exitCode, 0);
+ assert.ok(
+ peer.allReceived.some(
+ (m) => m.method === "lithe/build/progress" && m.params?.operationID === "op-test-single",
+ ),
+ "Expected lithe/build/progress notifications during test execution",
+ );
+ const junitXmlPath = join(wsDir, ".pytest_cache", "lithe-junit.xml");
+ assert.ok(existsSync(junitXmlPath), "Expected JUnit XML report at .pytest_cache/lithe-junit.xml");
+ const junitXml = readFileSync(junitXmlPath, "utf8");
+ assert.match(junitXml, /tests="1"/);
+ assert.match(junitXml, /test_scale\[2-6\]/);
+
+ writeFileSync(join(wsDir, "tests", "test_names.py"), [
+ "import pytest",
+ "def test_add():",
+ " assert True",
+ "def test_additional():",
+ " assert True",
+ "@pytest.mark.parametrize('value', [pytest.param(1, id='é' * 600)])",
+ "def test_long_id(value):",
+ " assert value == 1",
+ "",
+ ].join("\n"));
+ writeFileSync(join(wsDir, "test_notes.txt"), ">>> 1 + 1\n2\n");
+ peer.send({
+ jsonrpc: "2.0", id: 67, method: "lithe/build/test",
+ params: {
+ operationID: "op-case-only",
+ buildSystemID: "python", root: ".", tool: { executable: pytestExecutable },
+ case: "test_add", options: {}, optionArguments: [], userArguments: [], environment: {},
+ },
+ });
+ const caseOnly = await peer.waitFor((m) => m.id === 67, "case without a suite");
+ assert.equal(caseOnly.error?.data?.code, "python.invalidTestSelector");
+ assert.equal(readFileSync(junitXmlPath, "utf8"), junitXml);
+
+ peer.send({
+ jsonrpc: "2.0", id: 69, method: "lithe/build/discoverTests",
+ params: {
+ operationID: "op-discover-long-id",
+ buildSystemID: "python", root: ".", tool: { executable: pytestExecutable },
+ options: {}, optionArguments: [], environment: {},
+ },
+ });
+ const withLongId = await peer.waitFor((m) => m.id === 69, "discover with oversized UTF-8 test ID");
+ assert.deepEqual(
+ withLongId.result.tests.filter(({ suite }) => suite === "tests/test_names.py").map(({ case: name }) => name).sort(),
+ ["test_add", "test_additional"],
+ );
+ assert.ok(peer.allReceived.some((m) => m.method === "lithe/log"
+ && m.params?.operationId === "op-discover-long-id" && m.params?.code === "test_discovery_truncated"));
+ const doctest = withLongId.result.tests.find(({ suite }) => suite === "test_notes.txt");
+ assert.ok(doctest, "pytest must discover a root-level doctest");
+ peer.send({
+ jsonrpc: "2.0", id: 70, method: "lithe/build/test",
+ params: {
+ operationID: "op-exact-doctest",
+ buildSystemID: "python", root: ".", tool: { executable: pytestExecutable },
+ options: {}, optionArguments: [], userArguments: [], environment: {}, ...doctest,
+ },
+ });
+ const doctestRun = await peer.waitFor((m) => m.id === 70, "run discovered root-level doctest");
+ assert.equal(doctestRun.result?.exitCode, 0);
+ assert.match(readFileSync(junitXmlPath, "utf8"), /tests="1"/);
+
+ // 4b. Security & contract selector regressions: traversal, symlink escape, flag injection, and stale/deleted suites
+ // MUST reject with controlled PluginError (never bypassing _safe_within or widening to -k), while valid dot-directories work!
+ const outsideDir = join(scratch, "outside-evil-tests");
+ const outsideCanary = join(scratch, "OUTSIDE_CANARY_MUST_NOT_EXIST");
+ mkdirSync(outsideDir, { recursive: true });
+ const outsidePy = join(outsideDir, "test_evil.py");
+ writeFileSync(
+ outsidePy,
+ `open(${JSON.stringify(outsideCanary)}, "w").write("pwned")\ndef test_evil():\n assert True\n`,
+ );
+ if (process.platform !== "win32") {
+ const { symlinkSync } = await import("node:fs");
+ symlinkSync(outsidePy, join(wsDir, "tests", "test_escape_link.py"));
+ }
+
+ for (const [reqId, opId, badParams, expectedCode] of [
+ [61, "op-sel-traversal", { suite: "tests/../../outside-evil-tests/test_evil.py", case: "test_evil" }, "python.invalidTestSelector"],
+ [62, "op-sel-flag", { suite: "tests/test_calc.py", case: "--collect-only" }, "python.invalidTestSelector"],
+ [63, "op-sel-stale-path", { suite: "tests/test_deleted.py", case: "test_add" }, "python.staleTestSelector"],
+ [64, "op-sel-stale-dotted", { suite: "tests.test_deleted.TestCalc", case: "test_add" }, "python.staleTestSelector"],
+ [67, "op-sel-stale-case", { suite: "tests/test_calc.py", case: "TestCalc::test_removed" }, "python.staleTestSelector"],
+ [68, "op-sel-stale-project", { project: { name: "removed-project", path: "removed-project" } }, "python.staleTestSelector"],
+ [69, "op-sel-stale-target", { target: { properties: { directory: "removed-tests" } } }, "python.staleTestSelector"],
+ ]) {
+ peer.send({
+ jsonrpc: "2.0",
+ id: reqId,
+ method: "lithe/build/test",
+ params: {
+ operationID: opId,
+ buildSystemID: "python",
+ root: ".",
+ tool: { executable: pytestExecutable },
+ project: { name: "calc-suite", path: "." },
+ ...badParams,
+ options: {},
+ optionArguments: [],
+ userArguments: [],
+ environment: {},
+ },
+ });
+ const rej = await peer.waitFor((m) => m.id === reqId, `rejected selector ${opId}`);
+ assert.equal(rej.error?.code, -32000);
+ assert.equal(rej.error?.data?.code, expectedCode);
+ assert.ok(
+ peer.allReceived.some(
+ (m) => m.method === "lithe/log" && m.params?.operationId === opId && m.params?.kind === "operationFailed" && m.params?.code === expectedCode,
+ ),
+ );
+ }
+
+ if (process.platform !== "win32") {
+ peer.send({
+ jsonrpc: "2.0",
+ id: 65,
+ method: "lithe/build/test",
+ params: {
+ operationID: "op-sel-symlink",
+ buildSystemID: "python",
+ root: ".",
+ tool: { executable: pytestExecutable },
+ project: { name: "calc-suite", path: "." },
+ suite: "tests/test_escape_link.py",
+ case: "test_evil",
+ options: {},
+ optionArguments: [],
+ userArguments: [],
+ environment: {},
+ },
+ });
+ const symRej = await peer.waitFor((m) => m.id === 65, "rejected symlink escape selector");
+ assert.equal(symRej.error?.code, -32000);
+ assert.equal(symRej.error?.data?.code, "python.invalidTestSelector");
+ rmSync(join(wsDir, "tests", "test_escape_link.py"), { force: true });
+ }
+ assert.equal(existsSync(outsideCanary), false, "Outside test file must NEVER be executed");
+
+ // Valid dot-prefixed subdirectory (e.g. `.bench/test_dotdir.py`) must NOT be mangled by lstrip("./")!
+ mkdirSync(join(wsDir, ".bench"), { recursive: true });
+ writeFileSync(join(wsDir, ".bench", "test_dotdir.py"), "def test_dot_ok():\n assert 2 * 2 == 4\n");
+ peer.send({
+ jsonrpc: "2.0",
+ id: 66,
+ method: "lithe/build/test",
+ params: {
+ operationID: "op-test-dotdir",
+ buildSystemID: "python",
+ root: ".",
+ tool: { executable: pytestExecutable },
+ project: { name: "calc-suite", path: "." },
+ suite: ".bench/test_dotdir.py",
+ case: "test_dot_ok",
+ options: {},
+ optionArguments: [],
+ userArguments: [],
+ environment: {},
+ },
+ });
+ const dotDirResp = await peer.waitFor((m) => m.id === 66, "dot-directory test run");
+ assert.equal(dotDirResp.result.exitCode, 0);
+
+ // 5. lithe/build/runEntrypoints returns worker.py entrypoint and suppresses success INFO log.
+ peer.send({
+ jsonrpc: "2.0",
+ id: 7,
+ method: "lithe/build/runEntrypoints",
+ params: {
+ operationID: "op-entrypoints",
+ buildSystemID: "python",
+ root: ".",
+ file: "worker.py",
+ options: {},
+ optionArguments: [],
+ environment: {},
+ },
+ });
+ const epResp = await peer.waitFor((m) => m.id === 7, "runEntrypoints response");
+ assert.equal(epResp.result.format, "litheRunEntrypoints");
+ assert.equal(epResp.result.entrypoints.length, 1);
+ assert.equal(epResp.result.entrypoints[0].name, "worker.py");
+ assert.equal(
+ peer.allReceived.some((m) => m.method === "lithe/log" && m.params?.operationId === "op-entrypoints"),
+ false,
+ "runEntrypoints must suppress high-frequency success INFO logs",
+ );
+
+ // 6. $/cancelRequest terminates active pytest subprocess tree cleanly with zero orphan processes!
+ const pidFile = join(scratch, "slow-collect.pid");
+ writeFileSync(
+ join(wsDir, "tests", "test_blocking.py"),
+ [
+ "import os, pathlib, time",
+ `pathlib.Path(${JSON.stringify(pidFile)}).write_text(str(os.getpid()), encoding='utf-8')`,
+ "time.sleep(30)",
+ "def test_never_reached():",
+ " assert True",
+ ].join("\n") + "\n",
+ );
+
+ peer.send({
+ jsonrpc: "2.0",
+ id: 8,
+ method: "lithe/build/discoverTests",
+ params: {
+ operationID: "op-discover-cancel",
+ buildSystemID: "python",
+ root: ".",
+ tool: { executable: pytestExecutable },
+ options: {},
+ optionArguments: [],
+ environment: {},
+ },
+ });
+
+ const waitPidDeadline = Date.now() + 10_000;
+ while (!existsSync(pidFile) && Date.now() < waitPidDeadline) {
+ await new Promise((r) => setTimeout(r, 40));
+ }
+ assert.ok(existsSync(pidFile), "Expected blocking pytest child process to start and record its PID");
+ const childPid = Number.parseInt(readFileSync(pidFile, "utf8").trim(), 10);
+ assert.ok(Number.isInteger(childPid) && childPid > 0);
+
+ peer.send({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id: 8 } });
+ const cancelResp = await peer.waitFor((m) => m.id === 8, "cancelled discoverTests response", 10_000);
+ assert.equal(cancelResp.error?.code, -32800);
+ assert.equal(
+ peer.allReceived.some((m) => m.method === "lithe/log" && m.params?.operationId === "op-discover-cancel"),
+ false,
+ "Cancelled requests must NOT emit operationFinished or operationFailed logs",
+ );
+
+ // Bounded check that the spawned pytest process exited completely.
+ const killCheckDeadline = Date.now() + 3_000;
+ while (isProcessAlive(childPid) && Date.now() < killCheckDeadline) {
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ assert.equal(isProcessAlive(childPid), false, `Child pytest PID ${childPid} must be terminated on cancel`);
+
+ peer.send({ jsonrpc: "2.0", id: 9, method: "shutdown", params: null });
+ await peer.waitFor((m) => m.id === 9 && m.result === null, "build provider shutdown");
+ peer.send({ jsonrpc: "2.0", method: "exit", params: null });
+ const exitCode = await peer.waitExit();
+ assert.equal(exitCode, 0);
+ } finally {
+ await peer.closeAndKill();
+ }
+ });
+
+ await check("RPC cancellation covers queued requests and child process tree ownership", () => {
+ run(pythonCmd, ["-I", "-B", join(ROOT, "scripts", "test-rpc.py"), join(unpackedPluginDir, "scripts")]);
+ });
+
await check("lineMatcher and outputLinkMatchers match mypy, Ruff, and Python Traceback output", () => {
const pyBuild = pluginManifest.buildSystems.find((b) => b.id === "python");
const mypyPattern = pyBuild.diagnostics.patterns[0];
const mypyRe = new RegExp(mypyPattern.regex);
- const mypyMatch = mypyRe.exec('src/app.py:42:13: error: Incompatible types in assignment [assignment]');
+ const mypyMatch = mypyRe.exec("src/app.py:42:13: error: Incompatible types in assignment [assignment]");
assert.ok(mypyMatch);
assert.equal(mypyMatch[mypyPattern.file], "src/app.py");
assert.equal(mypyMatch[mypyPattern.line], "42");
@@ -481,7 +1563,6 @@ try {
assert.equal(ruffMatch[ruffPattern.column], "8");
assert.equal(ruffMatch[ruffPattern.message], "F401 `os` imported but unused");
- // JS equivalent of Rust named capture group (?P...) -> (?...)
const tbRe = new RegExp(pluginManifest.outputLinkMatchers[0].pattern.replaceAll("(?P<", "(?<"));
const tbMatch = tbRe.exec(' File "/workspace/Lithe Python Demo/main.py", line 9, in ');
assert.ok(tbMatch);
@@ -519,13 +1600,12 @@ try {
assert.equal(runOut, "Hello from Lithe Python Demo!");
});
- await check("packaged pyrefly answers --version and resolves .venv packages over LSP without pythonPath: ''", async () => {
- const pyreflyServer = pluginManifest.languageServers.find((s) => s.languageID === "python");
- const pyreflyBin = join(unpackedPluginDir, ...pyreflyServer.launch.path.split("/"));
- const versionOut = run(pyreflyBin, pyreflyServer.validationArguments, { cwd: demoDir }).trim();
- assert.match(versionOut, /pyrefly\s+1\.4\.1/i);
+ await check("packaged pyrefly resolves .venv packages over LSP when tools.python is omitted (graceful fallback)", async () => {
+ const pyreflyBin = join(
+ unpackedPluginDir,
+ ...(process.platform === "win32" ? ["bin", "pyrefly.exe"] : ["bin", "pyrefly"]),
+ );
- // Add a synthetic package inside demoDir/.venv site-packages so only .venv resolution can find it.
const venvPython =
process.platform === "win32"
? join(demoDir, ".venv", "Scripts", "python.exe")
@@ -535,16 +1615,16 @@ try {
}).trim();
const customPkgDir = join(sitePackages, "venv_only_pkg");
mkdirSync(customPkgDir, { recursive: true });
- writeFileSync(join(customPkgDir, "__init__.py"), " def answer() -> int:\n return 42\n".trimStart());
+ writeFileSync(join(customPkgDir, "__init__.py"), "def answer() -> int:\n return 42\n");
const checkFile = join(demoDir, "check_types.py");
const checkContent = "from venv_only_pkg import answer\nx: str = answer()\n";
writeFileSync(checkFile, checkContent);
- const fileUri = new URL(`file://${checkFile.startsWith("/") ? "" : "/"}${checkFile.replace(/\\/g, "/")}`).href;
- const rootUri = new URL(`file://${demoDir.startsWith("/") ? "" : "/"}${demoDir.replace(/\\/g, "/")}`).href;
+ const fileUriStr = fileUri(checkFile);
+ const rootUriStr = fileUri(demoDir);
- const child = spawn(pyreflyBin, pyreflyServer.arguments, {
+ const child = spawn(pyreflyBin, ["lsp"], {
cwd: demoDir,
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
@@ -557,8 +1637,8 @@ try {
method: "initialize",
params: {
processId: process.pid,
- rootUri,
- workspaceFolders: [{ uri: rootUri, name: "demo" }],
+ rootUri: rootUriStr,
+ workspaceFolders: [{ uri: rootUriStr, name: "demo" }],
capabilities: {
workspace: { configuration: true },
textDocument: { publishDiagnostics: {} },
@@ -569,7 +1649,6 @@ try {
await peer.waitFor((m) => m.id === 1 && "result" in m, "pyrefly initialize response");
peer.send({ jsonrpc: "2.0", method: "initialized", params: {} });
- // Respond to workspace/configuration with our exact manifest defaults (no pythonPath!).
const expandedPythonConfig = {
pyrefly: {
typeCheckingMode: "default",
@@ -604,7 +1683,7 @@ try {
method: "textDocument/didOpen",
params: {
textDocument: {
- uri: fileUri,
+ uri: fileUriStr,
languageId: "python",
version: 1,
text: checkContent,
@@ -614,7 +1693,7 @@ try {
}
} else if (msg.id !== undefined && msg.method) {
peer.send({ jsonrpc: "2.0", id: msg.id, result: null });
- } else if (msg.method === "textDocument/publishDiagnostics" && msg.params?.uri === fileUri) {
+ } else if (msg.method === "textDocument/publishDiagnostics" && msg.params?.uri === fileUriStr) {
if ((msg.params.diagnostics ?? []).length > 0) {
diagnosticsMsg = msg;
break;
@@ -624,7 +1703,10 @@ try {
assert.ok(diagnosticsMsg, "Expected publishDiagnostics from pyrefly");
const codes = diagnosticsMsg.params.diagnostics.map((d) => d.code);
- assert.ok(!codes.includes("missing-import"), `Expected .venv import to resolve, got: ${JSON.stringify(diagnosticsMsg.params.diagnostics)}`);
+ assert.ok(
+ !codes.includes("missing-import"),
+ `Expected .venv import to resolve without pythonPath, got: ${JSON.stringify(diagnosticsMsg.params.diagnostics)}`,
+ );
assert.ok(diagnosticsMsg.params.diagnostics.length >= 1, "Expected type mismatch diagnostic on x: str = answer()");
peer.send({ jsonrpc: "2.0", id: 2, method: "shutdown", params: null });
@@ -737,15 +1819,6 @@ try {
assert.deepEqual(afterSnapshot, beforeSnapshot);
});
} finally {
- if (madeReadOnly && unpackedPluginDir && !process.env.LITHE_TEST_PLUGIN_DIR) {
- try {
- setDirectoryTreeReadOnly(unpackedPluginDir, false);
- } catch {}
- } else if (madeReadOnly && unpackedPluginDir && process.env.LITHE_TEST_PLUGIN_DIR) {
- try {
- setDirectoryTreeReadOnly(unpackedPluginDir, false);
- } catch {}
- }
rmSync(scratch, { recursive: true, force: true });
}