Merge pull request #190 from Nwflower/feat/plugin-host-api-catalog

feat(plugin): catalog the Host API, open secret typing and extend the SDK
This commit is contained in:
千川白浪 authored and GitHub committed 2026-12-05 16:48:49 +08:00
commit 22c01cee5b
32 files changed
+2493 -472

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"group": "improvements",
"order": 2,
"authors": ["TODO-github-username"],
"zh": "插件在客体里按住键或鼠标键后退出、停用或两分钟不再调用时,宿主会替它抬起,虚拟机不再卡在修饰键按下的状态。按住按键时可同时带修饰键,截图宽度超出支持范围时会被收进范围内而不是被拒绝。",
"en": "When a plugin leaves a key or a pointer button held in a guest and then exits, is disabled or stops calling for two minutes, the host lifts it, so a VM no longer stays stuck with a modifier down. A held key may carry modifiers, and a screenshot width outside the supported range is brought into range instead of being refused."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "improvements",
"order": 1,
"authors": ["TODO-github-username"],
"zh": "插件宿主接口新增统一目录,每个 `host/*` 方法的权限与请求、结果字段只定义一次,宿主、SDK 与插件共用。键入敏感设置不再只对官方 MCP 插件开放,任何持有 `qmp:write` 且用户已按虚拟机授权访问的插件都可使用,宿主只键入该插件自己的设置且不返回明文。恢复点还原对已授权访问的虚拟机开放,克隆名称由插件自定。",
"en": "Add one authoritative catalog for the plugin Host API, so each `host/*` method's permissions and request and result fields are defined once and shared by the host, the SDK and plugins. Typing a secret setting is no longer reserved for the official MCP plugin, so any plugin holding `qmp:write` that the user authorized for that VM can use it, and the host only types the plugin's own setting without returning it. Restoring a snapshot works on any authorized VM, and a plugin names its own clones."
}
+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 1,
"authors": ["TODO-github-username"],
"zh": "`pkg/pluginsdk` 新增虚拟机与控制台方法,插件无需自写 JSON-RPC 客户端即可列出和操作虚拟机、截图、按键、键入文本与敏感设置、抬起仍按住的输入。宿主未在握手中宣告的方法会在发送前被拒绝,宿主返回的 JSON-RPC 错误码也会保留给调用方。",
"en": "Add VM and console methods to `pkg/pluginsdk`, so a plugin can list and control VMs, take screenshots, press keys, type text and secrets and release held input without writing its own JSON-RPC client. A method the host did not advertise in the handshake is refused before it is sent, and the host's JSON-RPC error code reaches the caller."
}
+6 -3
View File
@@ -37,7 +37,9 @@ flowchart TB
L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。每条连接带一个会话标识,宿主随 `channel/<通道>/message` 一并转发,插件按会话区分请求 ID 和取消。连接结束后,宿主向正在运行的 Sidecar 发送 `channel/<通道>/closed` 通知,插件据此取消该连接的调用并释放按住的输入。官方 MCP 插件实现工具、虚拟机状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态和恢复点列表要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。截图可指定一块区域,区域坐标默认按源分辨率计算,也可附带参考图像尺寸,由宿主换算到源分辨率。宿主在全分辨率帧上裁剪区域后再缩放。按键可单独按住和松开,释放接口一次抬起指定的按键和鼠标键;驱动控制台只支持按键单击。关机可指定强制停止。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向 MCP 插件返回明文。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态和恢复点列表要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。截图可指定一块区域,区域坐标默认按源分辨率计算,也可附带参考图像尺寸,由宿主换算到源分辨率;宿主在全分辨率帧上裁剪区域后再缩放,超出支持范围的宽度会被收进范围内而不是被拒绝。按键可单独按住和松开,按住时可同时带修饰键,宿主一并按住或抬起;释放接口一次抬起指定的按键和鼠标键;驱动控制台只支持按键单击。关机可指定强制停止。宿主记录每个插件在各台虚拟机上仍按住的键与鼠标键,包括驱动控制台上的鼠标键,在插件进程退出、插件停用、虚拟机停止或两分钟不再调用时替它抬起;按住状态只由输入事件维护,不依赖连接存活,虚拟机未运行时记录直接丢弃,不在开机后补发过期的释放。
键入敏感设置对所有持有 `qmp:write` 且用户已按虚拟机授权访问的插件开放,不再只对官方插件开放。宿主只键入该插件自己的设置,不向插件返回明文,审计日志只记录设置名与长度。恢复点还原对已授权访问的虚拟机开放;删除虚拟机仍只限插件自己创建的临时虚拟机,克隆名称由插件自定,宿主以自己写入的归属标记识别临时虚拟机。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。
## 生命周期、参数账本与资源预算
@@ -72,12 +74,13 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V
| 版本面 | 覆盖范围 | 权威契约清单与自动校验 |
| :--- | :--- | :--- |
| `pluginApi` | 清单结构、扩展点、钩子载荷、权限名与子进程 JSON-RPC 协议 | [`internal/plugin/contract.go`](../internal/plugin/contract.go) |
| `pluginApi` 的宿主接口 | Sidecar 可调用的 `host/*` 方法、所需权限与请求和结果的字段 | [`pkg/pluginproto`](../pkg/pluginproto)(宿主、SDK 与插件共用同一份类型) |
| `uiApi` | 主题令牌、部件类名、状态属性、槽位、全窗图层、布局选项、图标名与交互事件 | [`frontend/ui-contract.json`](../frontend/ui-contract.json)(前端构建校验每个稳定项均已渲染) |
| `bridgeApi` | 沙箱面板与宿主之间的消息方法与事件 | [`frontend/bridge-contract.json`](../frontend/bridge-contract.json)(前后端单测双向同步校验) |
每个公开的稳定契约项在发布时均具备宿主实现与契约测试;尚未实现的预留项在契约文件中标记为 `experimental`,清单校验予以放行但 `reims-go plugin doctor` 会给出实验性提示,正式版市场插件不得依赖实验项。主版本内只做向后兼容的可选扩展,插件在握手阶段根据宿主下发的 `features` 特性列表按需降级,未知清单字段忽略并提示。
每个公开的稳定契约项在发布时均具备宿主实现与契约测试;尚未实现的预留项在契约文件中标记为 `experimental`,清单校验予以放行但 `reims-go plugin doctor` 会给出实验性提示,正式版市场插件不得依赖实验项。主版本内只做向后兼容的可选扩展,插件在握手阶段根据宿主下发的 `features` 特性列表按需降级,未知清单字段忽略并提示。宿主接口目录中的每个方法同样以特性名宣告,测试保证目录中的稳定方法都有实现、宿主实现的方法都在目录内。
当前插件契约为 `pluginApi 1.2.0`,界面契约为 `uiApi 2.1.0`。客体驱动在清单中以 `runtimeKind` 为 `external` 声明自带运行环境,并可用 `consoleEndpoint`、`pasteCombo`、`keymap` 声明控制台接入方式、客体粘贴组合键与键位映射。`driver.console`、`host.secret.materialize`、`host.download` 与 `host.elevate.request` 均已进入稳定契约,并在 Sidecar 握手特性列表中宣告。
当前插件契约为 `pluginApi 1.3.0`,界面契约为 `uiApi 2.1.0`。客体驱动在清单中以 `runtimeKind` 为 `external` 声明自带运行环境,并可用 `consoleEndpoint`、`pasteCombo`、`keymap` 声明控制台接入方式、客体粘贴组合键与键位映射。`driver.console`、`host.secret.materialize`、`host.download` 与 `host.elevate.request` 均已进入稳定契约,并在 Sidecar 握手特性列表中宣告。声明 `pluginApi` 1.3 或更高范围的插件,其虚拟机与控制台方法的请求中未定义的字段会以 JSON-RPC `-32602` 拒绝;更早的插件继续忽略未知字段,以便已发布插件在宿主补齐字段前照常工作。
## 客体驱动的 Sidecar 协议
+7 -3
View File
@@ -157,9 +157,13 @@ type App struct {
// computerUseOwnedVMs caches ownership markers for MCP-created temporary VMs.
computerUseOwnedVMs map[string]map[string]bool
computerUseCloneMu sync.Mutex
fullscreenHotkey host.FullscreenHotkeyService
fullscreenSyncMu sync.Mutex
fullscreenTargets fullscreenHotkeyTargetCache
// computerUseHeld records the keys and pointer buttons each plugin left
// held in a guest, so the host can release them when the plugin goes away.
computerUseHeld map[string]map[string]*heldInputs
computerUseHeldMu sync.Mutex
fullscreenHotkey host.FullscreenHotkeyService
fullscreenSyncMu sync.Mutex
fullscreenTargets fullscreenHotkeyTargetCache
// Plugin elevation requests (elevate_flow.go).
elevatePromptMu sync.Mutex
+244
View File
@@ -0,0 +1,244 @@
package app
import (
"context"
"sort"
"time"
"github.com/Nwflower/reims-go/internal/driver"
)
// heldInputIdleTimeout bounds how long a plugin may leave a key or a pointer
// button held in a guest without touching that console again. A plugin that
// stops calling without releasing must not leave the guest stuck with a
// modifier down, so the record carries its own timer instead of waiting for the
// plugin's next call.
var heldInputIdleTimeout = 2 * time.Minute
// heldReleaseTimeout bounds one fallback release, which runs while the plugin
// that held the input may already be gone.
const heldReleaseTimeout = 5 * time.Second
// heldInputs is what one plugin currently holds in one guest. QEMU and a
// driver's own console keep a pressed key or button down in the guest until a
// release arrives, and that state does not depend on the connection, so the
// host has to remember what it pressed and lift it when the plugin can no
// longer do so.
type heldInputs struct {
keys map[string]bool
buttons map[string]bool
touched time.Time
timer *time.Timer
}
// noteHeldKey records or forgets one key transition. code must already be a
// QKeyCode.
func (a *App) noteHeldKey(pluginID, vmKey, code string, down bool) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
held := a.heldLocked(pluginID, vmKey)
if down {
held.keys[code] = true
} else {
delete(held.keys, code)
}
a.touchHeldLocked(pluginID, vmKey, held)
}
// noteHeldButton records or forgets one pointer button transition.
func (a *App) noteHeldButton(pluginID, vmKey, button string, down bool) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
held := a.heldLocked(pluginID, vmKey)
if down {
held.buttons[button] = true
} else {
delete(held.buttons, button)
}
a.touchHeldLocked(pluginID, vmKey, held)
}
// heldLocked returns the record for one plugin and VM, creating it when
// needed. The caller holds computerUseHeldMu.
func (a *App) heldLocked(pluginID, vmKey string) *heldInputs {
if a.computerUseHeld == nil {
a.computerUseHeld = map[string]map[string]*heldInputs{}
}
byVM := a.computerUseHeld[pluginID]
if byVM == nil {
byVM = map[string]*heldInputs{}
a.computerUseHeld[pluginID] = byVM
}
held := byVM[vmKey]
if held == nil {
held = &heldInputs{keys: map[string]bool{}, buttons: map[string]bool{}}
byVM[vmKey] = held
}
return held
}
// touchHeldLocked drops a record that holds nothing and rearms the idle timer
// of one that still does. The caller holds computerUseHeldMu.
func (a *App) touchHeldLocked(pluginID, vmKey string, held *heldInputs) {
held.touched = time.Now()
if held.timer != nil {
held.timer.Stop()
held.timer = nil
}
if len(held.keys)+len(held.buttons) == 0 {
a.pruneHeldLocked(pluginID, vmKey)
return
}
held.timer = time.AfterFunc(heldInputIdleTimeout, func() {
a.releaseHeldForVM(pluginID, vmKey)
})
}
// pruneHeldLocked drops a record that holds nothing, so an idle plugin leaves
// no state behind. The caller holds computerUseHeldMu.
func (a *App) pruneHeldLocked(pluginID, vmKey string) {
byVM := a.computerUseHeld[pluginID]
if byVM == nil {
return
}
if held := byVM[vmKey]; held != nil {
if held.timer != nil {
held.timer.Stop()
held.timer = nil
}
delete(byVM, vmKey)
}
if len(byVM) == 0 {
delete(a.computerUseHeld, pluginID)
}
}
// heldState returns what one plugin holds in one VM, sorted.
func (a *App) heldState(pluginID, vmKey string) (keys, buttons []string) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
byVM := a.computerUseHeld[pluginID]
if byVM == nil {
return nil, nil
}
held := byVM[vmKey]
if held == nil {
return nil, nil
}
for code := range held.keys {
keys = append(keys, code)
}
for button := range held.buttons {
buttons = append(buttons, button)
}
sort.Strings(keys)
sort.Strings(buttons)
return keys, buttons
}
// heldVMs lists the VMs one plugin currently holds input in.
func (a *App) heldVMs(pluginID string) map[string]bool {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
out := map[string]bool{}
for vmKey := range a.computerUseHeld[pluginID] {
out[vmKey] = true
}
return out
}
// dropHeld forgets the named keys and buttons of one plugin and VM. It is
// called only after the release reached the guest.
func (a *App) dropHeld(pluginID, vmKey string, keys, buttons []string) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
byVM := a.computerUseHeld[pluginID]
if byVM == nil {
return
}
held := byVM[vmKey]
if held == nil {
return
}
for _, code := range keys {
delete(held.keys, code)
}
for _, button := range buttons {
delete(held.buttons, button)
}
a.touchHeldLocked(pluginID, vmKey, held)
}
// forgetHeld drops the record of one plugin and VM without touching the
// guest. It is for a VM that is not running: nothing in a powered-off guest
// can still be held, and a release sent later could lift a key the user is
// pressing after the VM starts again.
func (a *App) forgetHeld(pluginID, vmKey string) {
a.computerUseHeldMu.Lock()
defer a.computerUseHeldMu.Unlock()
a.pruneHeldLocked(pluginID, vmKey)
}
// heldConsoleRoute resolves the console a held release has to go through. It
// reports false when the VM is gone or not running, because then nothing can
// be held in it.
func (a *App) heldConsoleRoute(vmKey string) (consoleRoute, bool) {
ref, ok := driver.ParseVMRef(vmKey)
if !ok {
return consoleRoute{}, false
}
vm, err := a.resolveVMInfo(ref.DriverID, ref.Name)
if err != nil {
return consoleRoute{}, false
}
current, ok := a.polledVMForDriver(vm.DriverID, vm.Name)
if !ok || current.State != "running" {
return consoleRoute{}, false
}
if vm.Directory == "" {
vm.Directory = current.Dir
}
route, err := a.resolveConsoleRoute(vm)
if err != nil {
return consoleRoute{}, false
}
route.vm = vm
return route, true
}
// releaseHeldForVM lifts everything one plugin still holds in one VM. It is the
// fallback for a plugin that can no longer release: its process exited, its
// scope was disposed, or it stopped calling. A VM that is not running has
// nothing held, so its record is dropped instead of retried; a release that
// fails on a running VM keeps its record for the next attempt.
func (a *App) releaseHeldForVM(pluginID, vmKey string) {
keys, buttons := a.heldState(pluginID, vmKey)
if len(keys)+len(buttons) == 0 {
a.forgetHeld(pluginID, vmKey)
return
}
route, ok := a.heldConsoleRoute(vmKey)
if !ok {
a.forgetHeld(pluginID, vmKey)
return
}
ctx, cancel := context.WithTimeout(context.Background(), heldReleaseTimeout)
defer cancel()
if err := a.consoleRelease(ctx, route, keys, buttons); err != nil {
// The VM may have stopped while the release was in flight.
if _, stillRunning := a.heldConsoleRoute(vmKey); !stillRunning {
a.forgetHeld(pluginID, vmKey)
return
}
a.emitLog("plugin", "Could not release input held by "+pluginID+" in "+vmKey+": "+err.Error())
return
}
a.dropHeld(pluginID, vmKey, keys, buttons)
}
// releaseHeldForPlugin lifts everything one plugin holds in any VM.
func (a *App) releaseHeldForPlugin(pluginID string) {
for vmKey := range a.heldVMs(pluginID) {
a.releaseHeldForVM(pluginID, vmKey)
}
}
+215 -215
View File
@@ -14,24 +14,20 @@ import (
"time"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/console"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/thumb"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
const computerUsePreviewWidth = 1280
const computerUseMaxImageWidth = 2560
const computerUseMinImageWidth = 64
const computerUseMaxTextRunes = 4000
const computerUseSecretPluginID = "reims.agent"
const computerUseOwnershipFile = ".reims-go-computer-use"
const computerUseCloneRequestPrefix = "__agent-"
const computerUseCloneNamePrefix = "reims-agent-"
func isComputerUseCloneName(name string) bool {
return strings.HasPrefix(name, computerUseCloneNamePrefix) || strings.HasPrefix(name, computerUseCloneRequestPrefix)
}
type computerUseOwnership struct {
Version int `json:"version"`
@@ -44,52 +40,45 @@ type computerUseOwnership struct {
SourceVM string `json:"source_vm,omitempty"`
}
// computerUseHostHandlers serves the VM and console Host API. Every method is
// registered through hostMethod, which authorizes from the contract catalog in
// pkg/pluginproto and audits under the method name.
func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
if mgr == nil || mgr.Broker() == nil {
return nil
}
handlers := map[string]plugin.RPCRequestHandler{
"host/vm.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.list", a.handleComputerUseVMList),
"host/vm.get": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.get", a.handleComputerUseVMGet),
"host/vm.start": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.start", a.handleComputerUseVMStart),
"host/vm.shutdown": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.shutdown", a.handleComputerUseVMShutdown),
"host/vm.suspend": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.suspend", a.handleComputerUseVMStateChange(a.SuspendVM)),
"host/vm.resume": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.resume", a.handleComputerUseVMStateChange(a.ResumeVM)),
"host/vm.clone": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.clone", a.handleComputerUseVMClone),
"host/vm.delete": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.delete", a.handleComputerUseVMDelete),
"host/vm.snapshot.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
"host/vm.snapshot.create": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
"host/vm.snapshot.restore": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
"host/console.screenshot": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:screen", "host/console.screenshot", a.handleComputerUseScreenshot),
"host/console.pointer": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.pointer", a.handleComputerUsePointer),
"host/console.key": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.key", a.handleComputerUseKey),
"host/console.type": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.type", a.handleComputerUseType),
"host/console.release": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.release", a.handleComputerUseRelease),
return map[string]plugin.RPCRequestHandler{
"host/vm.list": a.hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
"host/vm.get": a.hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
"host/vm.start": a.hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
"host/vm.shutdown": a.hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
"host/vm.suspend": a.hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
"host/vm.resume": a.hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
"host/vm.clone": a.hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
"host/vm.delete": a.hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
"host/vm.snapshot.list": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
"host/vm.snapshot.create": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
"host/vm.snapshot.restore": a.hostVMMethod(mgr, pluginID, "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
"host/console.screenshot": a.hostVMMethod(mgr, pluginID, "host/console.screenshot", a.handleComputerUseScreenshot),
"host/console.pointer": a.hostVMMethod(mgr, pluginID, "host/console.pointer", a.handleComputerUsePointer),
"host/console.key": a.hostVMMethod(mgr, pluginID, "host/console.key", a.handleComputerUseKey),
"host/console.type": a.hostVMMethod(mgr, pluginID, "host/console.type", a.handleComputerUseType),
"host/console.typeSecret": a.hostVMMethod(mgr, pluginID, "host/console.typeSecret", a.handleComputerUseTypeSecret),
"host/console.release": a.hostVMMethod(mgr, pluginID, "host/console.release", a.handleComputerUseRelease),
}
// The plugin ID is supplied by the manager while wiring the sidecar, never
// by the channel payload. Keep the handler registered for a stable method
// table, then reject every plugin except the official MCP service below.
handlers["host/console.typeSecret"] = a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.typeSecret", a.handleComputerUseTypeSecret)
return handlers
}
type computerUseVMHandler func(context.Context, json.RawMessage, *plugin.Manager, string) (any, error)
func (a *App) authorizedComputerUseVMHandler(mgr *plugin.Manager, pluginID, permission, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
return a.authorizedComputerUseHandler(mgr, pluginID, permission, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
return run(ctx, raw, mgr, pluginID)
})
}
// handleComputerUseTypeSecret types one of the calling plugin's own settings
// into a VM the user authorized that plugin to access. The host never returns
// the value, so a plugin can use a secret it stored without ever reading it.
// The method is open to every plugin that holds qmp:write; the user's per-VM
// access consent is the only gate, and the audit log records the setting name
// and its length.
func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
if pluginID != computerUseSecretPluginID {
return nil, errors.New("secret typing is reserved for reims.agent")
}
var req struct {
VM string `json:"vm"`
Setting string `json:"setting"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.TypeSecretParams](mgr, pluginID, "host/console.typeSecret", raw)
if err != nil {
return nil, err
}
if strings.TrimSpace(req.Setting) == "" {
@@ -126,15 +115,18 @@ func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessa
if err != nil {
return nil, err
}
return map[string]any{"characters": count}, nil
return pluginproto.CharactersResult{Characters: count}, nil
}
func (a *App) handleComputerUseVMList(ctx context.Context, _ json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
func (a *App) handleComputerUseVMList(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
if _, err := decodeHostParams[struct{}](mgr, pluginID, "host/vm.list", raw); err != nil {
return nil, err
}
items, err := a.listVMsInternal(ctx)
if err != nil {
return nil, err
}
vms := make([]map[string]any, 0, len(items))
vms := make([]pluginproto.VMView, 0, len(items))
for _, item := range items {
info, err := a.resolveVMInfo(item.DriverID, item.Name)
if err != nil {
@@ -142,14 +134,12 @@ func (a *App) handleComputerUseVMList(ctx context.Context, _ json.RawMessage, mg
}
vms = append(vms, a.computerUseVMView(info, mgr, pluginID))
}
return map[string]any{"vms": vms}, nil
return pluginproto.VMListResult{VMs: vms}, nil
}
func (a *App) handleComputerUseVMGet(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.get", raw)
if err != nil {
return nil, err
}
info, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -159,45 +149,43 @@ func (a *App) handleComputerUseVMGet(_ context.Context, raw json.RawMessage, mgr
return a.computerUseVMView(info, mgr, pluginID), nil
}
func (a *App) computerUseVMView(vm driver.VMInfo, mgr *plugin.Manager, pluginID string) map[string]any {
func (a *App) computerUseVMView(vm driver.VMInfo, mgr *plugin.Manager, pluginID string) pluginproto.VMView {
accessEnabled := a.computerUseVMAccessEnabled(mgr, pluginID, vm.Ref().Key())
view := map[string]any{
"vm": vm.Ref().Key(),
"name": vm.Name,
"driver_id": vm.DriverID,
"state": vm.State,
"authorized": accessEnabled,
"phase": computerUseVMPhase(vm),
"owned": a.computerUseOwned(pluginID, vm.Ref().Key()),
view := pluginproto.VMView{
VM: vm.Ref().Key(),
Name: vm.Name,
DriverID: vm.DriverID,
State: vm.State,
Authorized: accessEnabled,
Phase: computerUseVMPhase(vm),
Owned: a.computerUseOwned(pluginID, vm.Ref().Key()),
}
if vm.CPUs > 0 {
view["cpus"] = vm.CPUs
view.CPUs = vm.CPUs
}
if vm.Memory != "" {
view["memory"] = vm.Memory
view.Memory = vm.Memory
}
if vm.DiskSummary != "" {
view["disk_summary"] = vm.DiskSummary
view.DiskSummary = vm.DiskSummary
}
if accessEnabled && vm.SSHPort > 0 {
view["ssh_port"] = vm.SSHPort
view.SSHPort = vm.SSHPort
}
if len(vm.Capabilities) > 0 {
view["capabilities"] = append([]string(nil), vm.Capabilities...)
view.Capabilities = append([]string(nil), vm.Capabilities...)
}
if accessEnabled {
if username := a.computerUseSSHUser(mgr, pluginID, vm); username != "" {
view["ssh_username"] = username
view.SSHUsername = username
}
}
return view
}
func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.start", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -207,15 +195,12 @@ func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, m
if err := a.StartVM(vm.DriverID, vm.Name); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Force bool `json:"force"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMShutdownParams](mgr, pluginID, "host/vm.shutdown", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -225,15 +210,13 @@ func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage
if err := a.StopVM(vm.DriverID, vm.Name, req.Force); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseVMStateChange(change func(driverID, name string) error) computerUseVMHandler {
func (a *App) handleComputerUseVMStateChange(method string, change func(driverID, name string) error) computerUseVMHandler {
return func(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, method, raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -243,28 +226,19 @@ func (a *App) handleComputerUseVMStateChange(change func(driverID, name string)
if err := change(vm.DriverID, vm.Name); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
return pluginproto.OKResult{OK: true}, nil
}
}
func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
CloneName string `json:"clone_name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMCloneParams](mgr, pluginID, "host/vm.clone", raw)
if err != nil {
return nil, err
}
cloneName := strings.TrimSpace(req.CloneName)
if cloneName == "" {
return nil, errors.New("clone_name is required")
}
suffix, ok := strings.CutPrefix(cloneName, computerUseCloneRequestPrefix)
if !ok || suffix == "" {
return nil, errors.New("temporary MCP clone identifiers must begin with __agent- and include a suffix")
}
// Preserve the wire prefix used by released sidecars and register a valid VM name.
cloneName = computerUseCloneNamePrefix + suffix
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
@@ -294,20 +268,22 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage,
// inventory poll. Return the canonical reference immediately so callers can
// start the clone without turning a successful clone into a false failure.
a.markComputerUseOwnedVM(pluginID, cloneRef.Key(), true)
return map[string]any{"vm": cloneRef.Key(), "name": cloneName, "driver_id": vm.DriverID, "state": "stopped", "owned": true}, nil
return pluginproto.VMCloneResult{
VM: cloneRef.Key(), Name: cloneName, DriverID: vm.DriverID, State: "stopped", Owned: true,
}, nil
}
func (a *App) handleComputerUseVMDelete(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.delete", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveComputerUseVMInfo(req.VM)
if err != nil {
return nil, err
}
// Deleting a VM is irreversible, so it stays limited to the temporary VMs
// this plugin created. Every other VM keeps its own lifecycle.
if !a.computerUseOwned(pluginID, vm.Ref().Key()) {
return nil, a.computerUseHostError("not_authorized", "err.computer_use.not_owned", i18n.Vars{"name": vm.Name})
}
@@ -323,14 +299,14 @@ func (a *App) handleComputerUseVMDelete(ctx context.Context, raw json.RawMessage
}
removeComputerUseOwnership(vm.Directory)
a.markComputerUseOwnedVM(pluginID, vm.Ref().Key(), false)
return map[string]any{"ok": true}, nil
// The guest is gone, so nothing it held can still be held.
a.forgetHeld(pluginID, vm.Ref().Key())
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseVMSnapshotList(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.snapshot.list", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -341,15 +317,18 @@ func (a *App) handleComputerUseVMSnapshotList(ctx context.Context, raw json.RawM
if err != nil {
return nil, err
}
return map[string]any{"snapshots": snapshots}, nil
out := make([]pluginproto.Snapshot, 0, len(snapshots))
for _, snap := range snapshots {
out = append(out, pluginproto.Snapshot{
ID: snap.ID, Name: snap.Name, CreatedAt: snap.CreatedAt, VMStateBytes: snap.VMStateBytes,
})
}
return pluginproto.SnapshotListResult{Snapshots: out}, nil
}
func (a *App) handleComputerUseVMSnapshotCreate(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.SnapshotNameParams](mgr, pluginID, "host/vm.snapshot.create", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
@@ -359,46 +338,26 @@ func (a *App) handleComputerUseVMSnapshotCreate(_ context.Context, raw json.RawM
if err := a.CreateSnapshot(vm.DriverID, vm.Name, req.Name); err != nil {
return nil, err
}
return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil
return pluginproto.SnapshotResult{OK: true, Name: strings.TrimSpace(req.Name)}, nil
}
// handleComputerUseVMSnapshotRestore restores a snapshot of any VM the user
// authorized this plugin to access. Restoring replaces the guest's state, which
// the plugin can already stop, start and clone, so it needs no separate
// consent; the call is audited like every other VM control.
func (a *App) handleComputerUseVMSnapshotRestore(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.SnapshotNameParams](mgr, pluginID, "host/vm.snapshot.restore", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if !a.computerUseOwned(pluginID, vm.Ref().Key()) {
return nil, a.computerUseHostError("confirmation_required", "err.computer_use.restore_confirmation", i18n.Vars{"name": vm.Name})
}
if err := a.RestoreSnapshot(vm.DriverID, vm.Name, req.Name); err != nil {
return nil, err
}
return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil
}
type computerUseHandler func(context.Context, json.RawMessage) (any, error)
func (a *App) authorizedComputerUseHandler(mgr *plugin.Manager, pluginID, permission, method string, run computerUseHandler) plugin.RPCRequestHandler {
return func(ctx context.Context, raw json.RawMessage) (any, error) {
broker := mgr.Broker()
if err := broker.Authorize(pluginID, permission); err != nil {
return nil, err
}
result, err := run(ctx, raw)
if err != nil {
broker.Audit(pluginID, "HOST_API_ERROR", method)
return nil, err
}
broker.Audit(pluginID, "HOST_API", method)
return result, nil
}
return pluginproto.SnapshotResult{OK: true, Name: strings.TrimSpace(req.Name)}, nil
}
// resolveComputerUseVM returns the VM and the console route Agent calls use.
@@ -413,15 +372,20 @@ func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (d
if err != nil {
return driver.VMInfo{}, consoleRoute{}, err
}
// A plugin that stopped calling mid-hold must not leave a key down.
route, err := a.resolveConsoleRoute(vm)
if err != nil {
return driver.VMInfo{}, consoleRoute{}, err
}
current, ok := a.polledVMForDriver(vm.DriverID, vm.Name)
if !ok || current.State != "running" {
// A powered-off guest holds nothing, so the record is dropped rather
// than retried: a later release could lift a key the user is pressing.
a.forgetHeld(pluginID, vm.Ref().Key())
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("vm_not_running", "err.computer_use.vm_not_running", i18n.Vars{"name": vm.Name})
}
if route.kind == consoleRouteQMP && (current.PID == nil || *current.PID <= 0) {
a.forgetHeld(pluginID, vm.Ref().Key())
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("vm_not_running", "err.computer_use.vm_not_running", i18n.Vars{"name": vm.Name})
}
if vm.Phase == "" {
@@ -561,8 +525,11 @@ func removeComputerUseOwnership(vmDir string) {
_ = os.Remove(filepath.Join(vmDir, computerUseOwnershipFile))
}
// readComputerUseOwnership reads the marker the host wrote when it cloned a VM
// for a plugin. The marker, not the VM name, is what makes a VM a plugin's
// temporary clone, so a plugin may name its clones freely.
func readComputerUseOwnership(vm driver.VMInfo) (computerUseOwnership, bool) {
if vm.Directory == "" || !isComputerUseCloneName(vm.Name) {
if vm.Directory == "" {
return computerUseOwnership{}, false
}
raw, err := os.ReadFile(filepath.Join(vm.Directory, computerUseOwnershipFile))
@@ -635,7 +602,7 @@ func persistComputerUseOwnership(vm driver.VMInfo, pluginID, vmKey, sourceVM str
func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) {
for _, item := range vms {
vm := driver.VMInfo{Name: item.Name, DriverID: item.DriverID, Directory: item.Dir}
if vm.Directory == "" || !isComputerUseCloneName(vm.Name) {
if vm.Directory == "" {
continue
}
marker, ok := readComputerUseOwnership(vm)
@@ -827,26 +794,23 @@ func computerUseRegionToSource(region computerUseRegion, refW, refH int, source
return computerUseRegion{X: x0, Y: y0, Width: x1 - x0, Height: y1 - y0}
}
func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Region *computerUseRegion `json:"region"`
MaxWidth int `json:"max_width"`
// Width and Height name the image the region was measured in; without
// them the region is in source pixels.
Width int `json:"width"`
Height int `json:"height"`
// computerUseScreenshotWidth returns the width the returned image is scaled
// to. A request outside the supported range is brought into it rather than
// refused, so a caller that asks for more than the host encodes still gets a
// usable frame.
func computerUseScreenshotWidth(requested int) int {
if requested == 0 {
return computerUsePreviewWidth
}
if err := json.Unmarshal(raw, &req); err != nil {
return min(max(requested, computerUseMinImageWidth), computerUseMaxImageWidth)
}
func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.ScreenshotParams](mgr, pluginID, "host/console.screenshot", raw)
if err != nil {
return nil, err
}
maxWidth := req.MaxWidth
if maxWidth == 0 {
maxWidth = computerUsePreviewWidth
}
if maxWidth < 64 || maxWidth > computerUseMaxImageWidth {
return nil, fmt.Errorf("max_width must be between 64 and %d", computerUseMaxImageWidth)
}
maxWidth := computerUseScreenshotWidth(req.MaxWidth)
if req.Region != nil && (req.Region.Width <= 0 || req.Region.Height <= 0) {
return nil, errors.New("region width and height must be positive")
}
@@ -873,7 +837,9 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa
frame image.Image
blank bool
)
result := map[string]any{"mime_type": "image/jpeg", "source_width": sourceSize.X, "source_height": sourceSize.Y}
result := pluginproto.ScreenshotResult{
MIMEType: "image/jpeg", SourceWidth: sourceSize.X, SourceHeight: sourceSize.Y,
}
if req.Region == nil {
// A blank frame is a normal screen state during boot, login and display
// switches. Return it with a flag so pollers can keep waiting through it.
@@ -887,115 +853,149 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa
return nil, err
}
var applied computerUseRegion
region := computerUseRegionToSource(*req.Region, req.Width, req.Height, full.Bounds().Size())
result["source_width"], result["source_height"] = full.Bounds().Dx(), full.Bounds().Dy()
region := computerUseRegionToSource(computerUseRegion{
X: req.Region.X, Y: req.Region.Y, Width: req.Region.Width, Height: req.Region.Height,
}, req.Width, req.Height, full.Bounds().Size())
result.SourceWidth, result.SourceHeight = full.Bounds().Dx(), full.Bounds().Dy()
frame, applied, err = computerUseRegionFrame(full, region, maxWidth)
if err != nil {
return nil, err
}
blank = thumb.Blank(full)
result["region"] = applied
result.Region = &pluginproto.Region{X: applied.X, Y: applied.Y, Width: applied.Width, Height: applied.Height}
}
encoded, err := thumb.JPEG(frame, 84)
if err != nil {
return nil, err
}
bounds := frame.Bounds()
result["width"] = bounds.Dx()
result["height"] = bounds.Dy()
result["blank"] = blank
result["data"] = base64.StdEncoding.EncodeToString(encoded)
result.Width = bounds.Dx()
result.Height = bounds.Dy()
result.Blank = blank
result.Data = base64.StdEncoding.EncodeToString(encoded)
return result, nil
}
// computerUseHeldButtons normalizes the pointer buttons of a held gesture the
// way consoleRelease does, so the ledger records what will be lifted later.
func computerUseHeldButtons(buttons []string) ([]string, error) {
return normalizeReleaseButtons(buttons)
}
func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Action string `json:"action"`
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
Button string `json:"button"`
Down *bool `json:"down"`
Delta int `json:"delta"`
Horizontal bool `json:"horizontal"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
req, err := decodeHostParams[pluginproto.PointerParams](mgr, pluginID, "host/console.pointer", raw)
if err != nil {
return nil, err
}
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
// A button left down stays down in the guest until a release arrives, so
// the host records it on both console kinds and can lift it if the plugin
// goes away.
held := req.Action == "button" && req.Down != nil
button := ""
if held {
names, err := computerUseHeldButtons([]string{req.Button})
if err != nil {
return nil, err
}
button = names[0]
if *req.Down {
a.noteHeldButton(pluginID, vm.Ref().Key(), button, true)
}
}
if err := a.consolePointer(ctx, route, driver.ConsolePointerRequest{
Action: req.Action, X: req.X, Y: req.Y, Width: req.Width, Height: req.Height,
Button: req.Button, Down: req.Down, Delta: req.Delta, Horizontal: req.Horizontal,
}); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
if held && !*req.Down {
a.noteHeldButton(pluginID, vm.Ref().Key(), button, false)
}
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Key string `json:"key"`
Modifiers []string `json:"modifiers"`
// Down holds (true) or releases (false) one key instead of pressing it.
Down *bool `json:"down"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.KeyParams](mgr, pluginID, "host/console.key", raw)
if err != nil {
return nil, err
}
if strings.TrimSpace(req.Key) == "" {
return nil, errors.New("key is required")
}
if req.Down != nil && len(req.Modifiers) > 0 {
return nil, errors.New("a held key takes no modifiers; hold each key separately")
}
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if req.Down != nil {
err = a.consoleKeyState(ctx, route, req.Key, *req.Down)
} else {
err = a.consoleKey(ctx, route, req.Key, req.Modifiers)
if req.Down == nil {
if err := a.consoleKey(ctx, route, req.Key, req.Modifiers); err != nil {
return nil, err
}
return pluginproto.OKResult{OK: true}, nil
}
if err != nil {
return nil, err
// A held key may carry modifiers: each one is held or released with it, so
// a caller can hold Command and click without a second round trip.
names := append([]string{req.Key}, req.Modifiers...)
codes := make([]string, 0, len(names))
for _, name := range names {
code, err := console.NormalizeHeldKey(name)
if err != nil {
return nil, err
}
codes = append(codes, code)
}
return map[string]any{"ok": true}, nil
// Record a press before sending it: a call that never returns still left
// the key down, and the fallback release has to know about it.
if *req.Down {
for _, code := range codes {
a.noteHeldKey(pluginID, vm.Ref().Key(), code, true)
}
}
for _, code := range codes {
if err := a.consoleKeyState(ctx, route, code, *req.Down); err != nil {
return nil, err
}
}
if !*req.Down {
for _, code := range codes {
a.noteHeldKey(pluginID, vm.Ref().Key(), code, false)
}
}
return pluginproto.OKResult{OK: true}, nil
}
// handleComputerUseRelease lifts the given keys and pointer buttons in one
// report, so a client that stops mid-gesture never leaves input held.
func (a *App) handleComputerUseRelease(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Keys []string `json:"keys"`
Buttons []string `json:"buttons"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.ReleaseParams](mgr, pluginID, "host/console.release", raw)
if err != nil {
return nil, err
}
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.consoleRelease(ctx, route, req.Keys, req.Buttons); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
// Whatever the caller lifted is no longer held on the host's books either.
codes := make([]string, 0, len(req.Keys))
for _, key := range req.Keys {
if code, err := console.NormalizeHeldKey(key); err == nil {
codes = append(codes, code)
}
}
buttons, _ := computerUseHeldButtons(req.Buttons)
a.dropHeld(pluginID, vm.Ref().Key(), codes, buttons)
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
var req struct {
VM string `json:"vm"`
Text string `json:"text"`
}
if err := json.Unmarshal(raw, &req); err != nil {
req, err := decodeHostParams[pluginproto.TypeParams](mgr, pluginID, "host/console.type", raw)
if err != nil {
return nil, err
}
if len(req.Text) == 0 || !utf8.ValidString(req.Text) {
@@ -1018,5 +1018,5 @@ func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mg
if err != nil {
return nil, err
}
return map[string]any{"characters": n}, nil
return pluginproto.CharactersResult{Characters: n}, nil
}
+15 -35
View File
@@ -20,6 +20,7 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/netproxy"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
const (
@@ -50,7 +51,7 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
}
broker := mgr.Broker()
return map[string]plugin.RPCRequestHandler{
"host/download.start": func(_ context.Context, raw json.RawMessage) (any, error) {
"host/download.start": a.hostMethod(mgr, pluginID, "host/download.start", func(_ context.Context, raw json.RawMessage) (any, error) {
a.mu.Lock()
dataRoot := ""
if a.cfg != nil {
@@ -59,22 +60,11 @@ func (a *App) downloadHostHandlers(mgr *plugin.Manager, pluginID string) map[str
a.mu.Unlock()
roots := downloadRoots(mgr, pluginID, dataRoot)
notify := func(method string, params any) { mgr.NotifySidecar(pluginID, method, params) }
res, err := a.startPluginDownload(broker, notify, pluginID, roots, raw)
if err != nil {
broker.Audit(pluginID, "HOST_API_ERROR", "host/download.start")
return nil, err
}
broker.Audit(pluginID, "HOST_API", "host/download.start")
return res, nil
},
"host/download.cancel": func(_ context.Context, raw json.RawMessage) (any, error) {
res, err := cancelPluginDownload(pluginID, raw)
if err != nil {
return nil, err
}
broker.Audit(pluginID, "HOST_API", "host/download.cancel")
return res, nil
},
return a.startPluginDownload(mgr, broker, notify, pluginID, roots, raw)
}),
"host/download.cancel": a.hostMethod(mgr, pluginID, "host/download.cancel", func(_ context.Context, raw json.RawMessage) (any, error) {
return cancelPluginDownload(mgr, pluginID, raw)
}),
}
}
@@ -222,17 +212,9 @@ type downloadEvent struct {
// startPluginDownload validates a download request and runs it in the
// background as a task. It returns the download ID at once.
func (a *App) startPluginDownload(broker *plugin.Broker, notify downloadNotifier, pluginID string, roots []string, raw json.RawMessage) (any, error) {
var req struct {
URL string `json:"url"`
SHA256 string `json:"sha256"`
SHA256URL string `json:"sha256_url"`
SHA256Name string `json:"sha256_name"`
Dest string `json:"dest"`
Size int64 `json:"size"`
Label string `json:"label"`
}
if err := json.Unmarshal(raw, &req); err != nil {
func (a *App) startPluginDownload(kernel hostMethodHost, broker *plugin.Broker, notify downloadNotifier, pluginID string, roots []string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.DownloadParams](kernel, pluginID, "host/download.start", raw)
if err != nil {
return nil, err
}
if err := broker.AuthorizeNetOrigin(pluginID, req.URL); err != nil {
@@ -325,15 +307,13 @@ func (a *App) startPluginDownload(broker *plugin.Broker, notify downloadNotifier
notify("download/progress", ev)
broker.Audit(pluginID, "DOWNLOAD_"+strings.ToUpper(ev.Status), id)
}()
return map[string]any{"id": id, "task_id": taskID}, nil
return pluginproto.DownloadResult{ID: id, TaskID: taskID}, nil
}
// cancelPluginDownload stops one of pluginID's own downloads.
func cancelPluginDownload(pluginID string, raw json.RawMessage) (any, error) {
var req struct {
ID string `json:"id"`
}
if err := json.Unmarshal(raw, &req); err != nil {
func cancelPluginDownload(kernel hostMethodHost, pluginID string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.DownloadCancelParams](kernel, pluginID, "host/download.cancel", raw)
if err != nil {
return nil, err
}
pluginDownloads.mu.Lock()
@@ -343,5 +323,5 @@ func cancelPluginDownload(pluginID string, raw json.RawMessage) (any, error) {
return nil, fmt.Errorf("no download %q of this plugin is running", req.ID)
}
d.cancel()
return map[string]any{"ok": true}, nil
return pluginproto.OKResult{OK: true}, nil
}
+4 -3
View File
@@ -17,6 +17,7 @@ import (
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
type downloadTestEnv struct {
@@ -60,11 +61,11 @@ func (e *downloadTestEnv) notify(method string, params any) {
func (e *downloadTestEnv) start(t *testing.T, pluginID string, req map[string]any) (string, error) {
t.Helper()
raw, _ := json.Marshal(req)
res, err := e.app.startPluginDownload(e.h.Broker, e.notify, pluginID, e.roots, raw)
res, err := e.app.startPluginDownload(nil, e.h.Broker, e.notify, pluginID, e.roots, raw)
if err != nil {
return "", err
}
return res.(map[string]any)["id"].(string), nil
return res.(pluginproto.DownloadResult).ID, nil
}
// final waits for the last notification of a download and returns it.
@@ -206,7 +207,7 @@ func TestHostDownloadCancelIsPerPlugin(t *testing.T) {
}
cancelBy := func(plugin string) error {
raw, _ := json.Marshal(map[string]any{"id": id})
_, err := cancelPluginDownload(plugin, raw)
_, err := cancelPluginDownload(nil, plugin, raw)
return err
}
if err := cancelBy(e.other); err == nil {
+14 -18
View File
@@ -12,6 +12,7 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// elevatePromptTimeout is how long a confirmation waits for the person.
@@ -38,15 +39,9 @@ func (a *App) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[stri
}
broker := mgr.Broker()
return map[string]plugin.RPCRequestHandler{
"host/elevate.request": func(ctx context.Context, raw json.RawMessage) (any, error) {
res, err := a.requestElevation(ctx, broker, mgr.Registry(), pluginID, raw)
if err != nil {
broker.Audit(pluginID, "HOST_API_ERROR", "host/elevate.request")
return nil, err
}
broker.Audit(pluginID, "HOST_API", "host/elevate.request")
return res, nil
},
"host/elevate.request": a.hostMethod(mgr, pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
return a.requestElevation(ctx, mgr, broker, mgr.Registry(), pluginID, raw)
}),
}
}
@@ -54,14 +49,9 @@ func (a *App) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[stri
// the closed action list, ask the person in the desktop window, and only after
// a yes run the action (which raises the Windows UAC prompt). A no,
// a timeout or a missing window ends the request before anything runs.
func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg *plugin.Registry, pluginID string, raw json.RawMessage) (any, error) {
if err := broker.Authorize(pluginID, "driver:vm"); err != nil {
return nil, err
}
var req struct {
Action string `json:"action"`
}
if err := json.Unmarshal(raw, &req); err != nil {
func (a *App) requestElevation(ctx context.Context, kernel hostMethodHost, broker *plugin.Broker, reg *plugin.Registry, pluginID string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.ElevateParams](kernel, pluginID, "host/elevate.request", raw)
if err != nil {
return nil, err
}
spec, ok := host.LookupElevationAction(req.Action)
@@ -176,7 +166,13 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg *
return nil, err
}
broker.Audit(pluginID, "ELEVATE_OK", spec.Action)
return res, nil
return pluginproto.ElevateResult{
OK: res.OK,
Action: res.Action,
ExitCode: res.ExitCode,
RebootRequired: res.RebootRequired,
LogoffRequired: res.LogoffRequired,
}, nil
}
// ResolveElevationRequest delivers the person's answer to a pending plugin
+21 -2
View File
@@ -14,7 +14,9 @@ import (
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
type elevateTestEnv struct {
@@ -65,9 +67,26 @@ func newElevateTestEnv(t *testing.T) *elevateTestEnv {
return e
}
// testHostMethodHost lets a test serve a host/* method through the same
// catalog-driven wrapper the app registers, without a full plugin manager.
type testHostMethodHost struct {
broker *plugin.Broker
reg *plugin.Registry
}
func (h testHostMethodHost) Broker() *plugin.Broker { return h.broker }
func (h testHostMethodHost) Registry() *plugin.Registry { return h.reg }
func (e *elevateTestEnv) kernel() testHostMethodHost {
return testHostMethodHost{broker: e.h.Broker, reg: e.h.Registry}
}
func (e *elevateTestEnv) request(ctx context.Context, pluginID, action string) (any, error) {
raw, _ := json.Marshal(map[string]any{"action": action})
return e.app.requestElevation(ctx, e.h.Broker, e.h.Registry, pluginID, raw)
handler := e.app.hostMethod(e.kernel(), pluginID, "host/elevate.request", func(ctx context.Context, raw json.RawMessage) (any, error) {
return e.app.requestElevation(ctx, e.kernel(), e.h.Broker, e.h.Registry, pluginID, raw)
})
return handler(ctx, raw)
}
func (e *elevateTestEnv) promptCount() int {
@@ -155,7 +174,7 @@ func TestElevationApprovedRunsTheActionOnce(t *testing.T) {
if err != nil {
t.Fatal(err)
}
got, ok := res.(host.ElevationResult)
got, ok := res.(pluginproto.ElevateResult)
if !ok || !got.OK || !got.RebootRequired {
t.Fatalf("result = %#v", res)
}
+101
View File
@@ -0,0 +1,101 @@
package app
import (
"context"
"encoding/json"
"errors"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// hostMethodHandler serves one host/* request. The caller has already been
// authorized for the method.
type hostMethodHandler func(ctx context.Context, raw json.RawMessage) (any, error)
// hostMethodHost is what serving a host/* method needs from the plugin kernel.
// *plugin.Manager satisfies it; a test can supply a broker and a registry.
type hostMethodHost interface {
Broker() *plugin.Broker
Registry() *plugin.Registry
}
// authorizeHostMethod checks every permission the contract catalog lists for
// method. A method whose authorization depends on the request URL carries
// pluginproto.OriginPermission and is authorized by its own handler, which is
// the only place that sees the URL.
func authorizeHostMethod(host hostMethodHost, pluginID, method string) error {
spec, ok := pluginproto.Lookup(method)
if !ok {
return &plugin.RPCError{Code: plugin.RPCMethodNotFound, Message: "method not found: " + method}
}
if host == nil || host.Broker() == nil {
return errors.New("plugin manager is unavailable")
}
for _, perm := range spec.Permissions {
if perm == pluginproto.OriginPermission {
continue
}
if err := host.Broker().Authorize(pluginID, perm); err != nil {
return err
}
}
return nil
}
// strictHostParams reports whether requests of pluginID to method are decoded
// strictly. Only a plugin that declares pluginApi 1.3 or newer opts in, so a
// released plugin sending a field this host has not implemented keeps working
// until it is updated, while a new plugin learns about a typo at once.
func strictHostParams(host hostMethodHost, pluginID, method string) bool {
spec, ok := pluginproto.Lookup(method)
if !ok || !spec.StrictParams || host == nil {
return false
}
manifest, found := host.Registry().ManifestOf(pluginID)
if !found || manifest.Engines.PluginAPI == "" {
return false
}
return plugin.RangeRequiresAtLeast(manifest.Engines.PluginAPI, pluginproto.StrictParamsVersion)
}
// decodeHostParams decodes one host request through the shared contract types
// and answers a request the contract rejects with JSON-RPC -32602.
func decodeHostParams[T any](host hostMethodHost, pluginID, method string, raw json.RawMessage) (T, error) {
out, err := pluginproto.DecodeParams[T](method, raw, strictHostParams(host, pluginID, method))
if err != nil {
var invalid *pluginproto.InvalidParamsError
if errors.As(err, &invalid) {
return out, &plugin.RPCError{Code: plugin.RPCInvalidParams, Message: invalid.Error()}
}
return out, err
}
return out, nil
}
// hostMethod wraps one host/* method: it authorizes from the contract catalog,
// audits the call under the method name, and hands the request to run. No
// handler states its own permission, so a permission cannot drift from the
// method it guards.
func (a *App) hostMethod(host hostMethodHost, pluginID, method string, run hostMethodHandler) plugin.RPCRequestHandler {
return func(ctx context.Context, raw json.RawMessage) (any, error) {
if err := authorizeHostMethod(host, pluginID, method); err != nil {
return nil, err
}
result, err := run(ctx, raw)
broker := host.Broker()
if err != nil {
broker.Audit(pluginID, "HOST_API_ERROR", method)
return nil, err
}
broker.Audit(pluginID, "HOST_API", method)
return result, nil
}
}
// hostVMMethod wraps a handler that needs the manager and the calling plugin.
func (a *App) hostVMMethod(mgr *plugin.Manager, pluginID, method string, run computerUseVMHandler) plugin.RPCRequestHandler {
return a.hostMethod(mgr, pluginID, method, func(ctx context.Context, raw json.RawMessage) (any, error) {
return run(ctx, raw, mgr, pluginID)
})
}
+255
View File
@@ -0,0 +1,255 @@
package app
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
const hostContractPlugin = "test.host.contract"
// newHostContractEnv builds a plugin manager with one plugin whose manifest a
// test can vary, plus an App that serves the host API through it.
func newHostContractEnv(t *testing.T, manifest plugin.Manifest) (*App, *plugin.Manager) {
t.Helper()
cfg := config.Default()
cfg.DataRoot = t.TempDir()
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: cfg.DataRoot, HostVersion: "0.0.0"})
if err != nil {
t.Fatal(err)
}
t.Cleanup(mgr.Close)
manifest.ID = hostContractPlugin
manifest.Version = "1.0.0"
manifest.Name = plugin.LocalizedText{EnUS: hostContractPlugin}
if err := mgr.Registry().Register(plugin.PluginDef{
Manifest: manifest,
Source: plugin.SourceBuiltin,
Desired: true,
Activate: func(context.Context, *plugin.Scope) error { return nil },
}); err != nil {
t.Fatal(err)
}
mgr.Registry().Reconcile(context.Background())
return &App{cfg: cfg, pluginMgr: mgr}, mgr
}
// TestEveryStableHostMethodIsServed is the gate that keeps the host and the
// contract catalog from drifting: every stable method must be implemented
// somewhere, and nothing may be served that the catalog does not list.
func TestEveryStableHostMethodIsServed(t *testing.T) {
app, mgr := newHostContractEnv(t, plugin.Manifest{})
served := map[string]bool{}
for _, method := range plugin.ReverseHostAPIMethods() {
served[method] = true
}
for method := range app.hostHandlers(mgr, hostContractPlugin) {
if _, ok := pluginproto.Lookup(method); !ok {
t.Errorf("%s is served but not in the contract catalog", method)
}
served[method] = true
}
for _, method := range pluginproto.Methods() {
spec, _ := pluginproto.Lookup(method)
if spec.Status != pluginproto.StatusStable {
continue
}
if !served[method] {
t.Errorf("%s is stable in the catalog but nothing serves it", method)
}
}
}
// TestCataloguedPermissionsAreReal checks that every permission a method
// declares is one the permission classifier knows, so a typo cannot silently
// turn a method into an always-denied or always-allowed one.
func TestCataloguedPermissionsAreReal(t *testing.T) {
for _, method := range pluginproto.Methods() {
spec, _ := pluginproto.Lookup(method)
for _, perm := range spec.Permissions {
if perm == pluginproto.OriginPermission {
continue
}
if plugin.ClassifyPermission(perm) == plugin.PermForbidden {
t.Errorf("%s requires %q, which the host does not recognize", method, perm)
}
}
}
}
// TestReadingSnapshotsNeedsOnlyReadPermission keeps the catalog from asking for
// more than the operation needs.
func TestReadingSnapshotsNeedsOnlyReadPermission(t *testing.T) {
spec, ok := pluginproto.Lookup("host/vm.snapshot.list")
if !ok || len(spec.Permissions) != 1 || spec.Permissions[0] != "vm:read" {
t.Fatalf("host/vm.snapshot.list requires %v, want vm:read only", spec.Permissions)
}
}
func TestStrictParamsFollowTheDeclaredPluginAPI(t *testing.T) {
cases := map[string]bool{
"": false,
"^1.1.0": false,
"^1.2.0": false,
"^1.3.0": true,
">=1.3.0": true,
}
for engines, want := range cases {
_, mgr := newHostContractEnv(t, plugin.Manifest{Engines: plugin.Engines{PluginAPI: engines}})
raw := json.RawMessage(`{"vm":"a","max_width":640,"nope":1}`)
_, err := decodeHostParams[pluginproto.ScreenshotParams](mgr, hostContractPlugin, "host/console.screenshot", raw)
var rpcErr *plugin.RPCError
strict := errors.As(err, &rpcErr) && rpcErr.Code == plugin.RPCInvalidParams
if strict != want {
t.Errorf("pluginApi %q: strict = %v (%v), want %v", engines, strict, err, want)
}
}
}
func TestUnknownFieldIsRejectedWithInvalidParams(t *testing.T) {
_, mgr := newHostContractEnv(t, plugin.Manifest{Engines: plugin.Engines{PluginAPI: "^1.3.0"}})
_, err := decodeHostParams[pluginproto.KeyParams](mgr, hostContractPlugin, "host/console.key",
json.RawMessage(`{"vm":"a","key":"cmd","down":true,"hold_ms":5}`))
var rpcErr *plugin.RPCError
if !errors.As(err, &rpcErr) || rpcErr.Code != plugin.RPCInvalidParams {
t.Fatalf("err = %v, want JSON-RPC %d", err, plugin.RPCInvalidParams)
}
if !strings.Contains(rpcErr.Message, "hold_ms") {
t.Fatalf("message %q does not name the offending field", rpcErr.Message)
}
}
func TestShutdownForceReachesTheHost(t *testing.T) {
_, mgr := newHostContractEnv(t, plugin.Manifest{Engines: plugin.Engines{PluginAPI: "^1.3.0"}})
req, err := decodeHostParams[pluginproto.VMShutdownParams](mgr, hostContractPlugin, "host/vm.shutdown",
json.RawMessage(`{"vm":"a","force":true}`))
if err != nil {
t.Fatalf("a known field was rejected: %v", err)
}
if !req.Force || req.VM != "a" {
t.Fatalf("request = %+v, want force on vm a", req)
}
if _, err := decodeHostParams[pluginproto.VMShutdownParams](mgr, hostContractPlugin, "host/vm.shutdown",
json.RawMessage(`{"vm":"a","hard":true}`)); err == nil {
t.Fatal("an undefined field was accepted")
}
}
// TestSecretTypingIsOpenToEveryAuthorizedPlugin checks that typing a secret is
// no longer reserved for one plugin id: any plugin reaches the same path and
// is stopped only by the VM reference and the user's per-VM access consent.
func TestSecretTypingIsOpenToEveryAuthorizedPlugin(t *testing.T) {
app, mgr := newHostContractEnv(t, plugin.Manifest{})
_, err := app.handleComputerUseTypeSecret(context.Background(),
json.RawMessage(`{"vm":"","setting":"login_password"}`), mgr, hostContractPlugin)
if err == nil {
t.Fatal("an empty VM reference was accepted")
}
if strings.Contains(err.Error(), "reserved for") {
t.Fatalf("err = %v, want no plugin-id refusal", err)
}
}
// TestCloneOwnershipDoesNotDependOnTheName checks that a plugin may name its
// temporary clones freely: the marker the host writes is what makes a VM a
// clone.
func TestCloneOwnershipDoesNotDependOnTheName(t *testing.T) {
dir := t.TempDir()
vm := driver.VMInfo{Name: "my-own-name", DriverID: "acme.driver", Directory: dir}
key := vm.Ref().Key()
if err := writeComputerUseOwnership(dir, hostContractPlugin, key, ""); err != nil {
t.Fatal(err)
}
marker, ok := readComputerUseOwnership(vm)
if !ok || marker.PluginID != hostContractPlugin || marker.VMKey != key {
t.Fatalf("marker = %+v, ok = %v", marker, ok)
}
}
func TestScreenshotWidthIsBroughtIntoRange(t *testing.T) {
cases := map[int]int{
0: computerUsePreviewWidth,
-5: computerUseMinImageWidth,
1: computerUseMinImageWidth,
640: 640,
9999: computerUseMaxImageWidth,
}
for requested, want := range cases {
if got := computerUseScreenshotWidth(requested); got != want {
t.Errorf("max_width %d = %d, want %d", requested, got, want)
}
}
}
func TestHeldLedgerTracksAndForgets(t *testing.T) {
app := &App{}
const vmKey = "driver:vm"
app.noteHeldKey("p", vmKey, "meta_l", true)
app.noteHeldButton("p", vmKey, "left", true)
app.noteHeldKey("p", vmKey, "a", true)
keys, buttons := app.heldState("p", vmKey)
if len(keys) != 2 || len(buttons) != 1 {
t.Fatalf("held = %v %v", keys, buttons)
}
// Releasing one key keeps the rest.
app.dropHeld("p", vmKey, []string{"a"}, nil)
if keys, _ := app.heldState("p", vmKey); len(keys) != 1 || keys[0] != "meta_l" {
t.Fatalf("keys after drop = %v", keys)
}
// Lifting everything leaves no record behind.
app.dropHeld("p", vmKey, []string{"meta_l"}, []string{"left"})
if vms := app.heldVMs("p"); len(vms) != 0 {
t.Fatalf("ledger still holds %v", vms)
}
// A VM that is not running is forgotten without touching a console.
app.noteHeldKey("p", vmKey, "shift", true)
app.forgetHeld("p", vmKey)
if vms := app.heldVMs("p"); len(vms) != 0 {
t.Fatalf("ledger still holds %v after forget", vms)
}
}
// TestHeldLedgerReleasesAfterTheIdleTimeout checks that a plugin which stops
// calling mid-hold does not leave the guest stuck: the record carries its own
// timer, and a VM that is not running has nothing left to lift.
func TestHeldLedgerReleasesAfterTheIdleTimeout(t *testing.T) {
previous := heldInputIdleTimeout
heldInputIdleTimeout = 20 * time.Millisecond
t.Cleanup(func() { heldInputIdleTimeout = previous })
app := &App{}
app.noteHeldKey("p", "driver:vm", "meta_l", true)
if vms := app.heldVMs("p"); len(vms) != 1 {
t.Fatalf("ledger = %v, want one record", vms)
}
deadline := time.Now().Add(2 * time.Second)
for len(app.heldVMs("p")) > 0 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if vms := app.heldVMs("p"); len(vms) != 0 {
t.Fatalf("the idle timer left %v behind", vms)
}
}
func TestHeldLedgerIsPerPlugin(t *testing.T) {
app := &App{}
app.noteHeldKey("p1", "driver:vm", "meta_l", true)
if vms := app.heldVMs("p2"); len(vms) != 0 {
t.Fatalf("another plugin sees %v", vms)
}
if vms := app.heldVMs("p1"); len(vms) != 1 {
t.Fatalf("own record = %v", vms)
}
}
+5
View File
@@ -91,6 +91,11 @@ func (a *App) initPlugins() {
OnSettingsChanged: func(pluginID, vmName string) {
a.onPluginSettingsChanged(pluginID, vmName)
},
OnSidecarStopped: func(pluginID string) {
// A plugin that held a key or a pointer button in a guest can no
// longer release it, so the host lifts what it left down.
a.releaseHeldForPlugin(pluginID)
},
})
if err != nil {
a.emitLog("plugin", "Plugin state warning: "+err.Error())
+13 -24
View File
@@ -17,6 +17,7 @@ import (
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
const (
@@ -61,14 +62,11 @@ func (a *App) secretHostHandlers(mgr *plugin.Manager, pluginID string) map[strin
return value, err
}
return map[string]plugin.RPCRequestHandler{
"host/secret.materialize": a.authorizedComputerUseHandler(mgr, pluginID, "driver:vm", "host/secret.materialize", func(_ context.Context, raw json.RawMessage) (any, error) {
if err := broker.Authorize(pluginID, "fs:vm_dir"); err != nil {
return nil, err
}
return a.materializeSecret(broker, source, pluginID, raw)
"host/secret.materialize": a.hostMethod(mgr, pluginID, "host/secret.materialize", func(_ context.Context, raw json.RawMessage) (any, error) {
return a.materializeSecret(mgr, broker, source, pluginID, raw)
}),
"host/secret.discard": a.authorizedComputerUseHandler(mgr, pluginID, "driver:vm", "host/secret.discard", func(_ context.Context, raw json.RawMessage) (any, error) {
return a.discardSecret(broker, pluginID, raw)
"host/secret.discard": a.hostMethod(mgr, pluginID, "host/secret.discard", func(_ context.Context, raw json.RawMessage) (any, error) {
return a.discardSecret(mgr, broker, pluginID, raw)
}),
}
}
@@ -96,15 +94,9 @@ func encodeSecret(secret, format string) (string, error) {
// materializeSecret fills template with a secret setting and writes the
// result into the VM's folder. The plugin gets back only the path.
func (a *App) materializeSecret(broker *plugin.Broker, source secretSource, pluginID string, raw json.RawMessage) (any, error) {
var req struct {
Setting string `json:"setting"`
Ref plugin.VMRef `json:"ref"`
Template string `json:"template"`
Dest string `json:"dest"`
Format string `json:"format"`
}
if err := json.Unmarshal(raw, &req); err != nil {
func (a *App) materializeSecret(kernel hostMethodHost, broker *plugin.Broker, source secretSource, pluginID string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.SecretMaterializeParams](kernel, pluginID, "host/secret.materialize", raw)
if err != nil {
return nil, err
}
if strings.TrimSpace(req.Setting) == "" {
@@ -167,7 +159,7 @@ func (a *App) materializeSecret(broker *plugin.Broker, source secretSource, plug
}
// The audit line names the setting and its size, never the value.
broker.Audit(pluginID, "SECRET_MATERIALIZE", fmt.Sprintf("vm=%s setting=%s bytes=%d", vm.Ref().Key(), req.Setting, len(secret)))
return map[string]any{"path": dest}, nil
return pluginproto.SecretMaterializeResult{Path: dest}, nil
}
func writeSecretFile(dest string, content []byte) error {
@@ -306,12 +298,9 @@ func (a *App) removeMaterialized(match func(materializedSecret) bool) (int, erro
// discardSecret deletes the files a plugin materialized for one VM, or just
// the one named by path.
func (a *App) discardSecret(broker *plugin.Broker, pluginID string, raw json.RawMessage) (any, error) {
var req struct {
Ref plugin.VMRef `json:"ref"`
Path string `json:"path"`
}
if err := json.Unmarshal(raw, &req); err != nil {
func (a *App) discardSecret(kernel hostMethodHost, broker *plugin.Broker, pluginID string, raw json.RawMessage) (any, error) {
req, err := decodeHostParams[pluginproto.SecretDiscardParams](kernel, pluginID, "host/secret.discard", raw)
if err != nil {
return nil, err
}
driverID, err := broker.ResolveRefDriver(pluginID, req.Ref.DriverID)
@@ -330,7 +319,7 @@ func (a *App) discardSecret(broker *plugin.Broker, pluginID string, raw json.Raw
return nil, err
}
broker.Audit(pluginID, "SECRET_DISCARD", fmt.Sprintf("vm=%s files=%d", vmKey, n))
return map[string]any{"removed": n}, nil
return pluginproto.SecretDiscardResult{Removed: n}, nil
}
// discardMaterializedSecretsForVM deletes every secret file of a VM that is
+8 -7
View File
@@ -15,6 +15,7 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
const testSecret = `p@ss<&>w0rd"é`
@@ -70,7 +71,7 @@ func newSecretTestEnv(t *testing.T) *secretTestEnv {
func (e *secretTestEnv) materialize(t *testing.T, pluginID string, req map[string]any) (any, error) {
t.Helper()
raw, _ := json.Marshal(req)
return e.app.materializeSecret(e.h.Broker, e.source, pluginID, raw)
return e.app.materializeSecret(nil, e.h.Broker, e.source, pluginID, raw)
}
func (e *secretTestEnv) request(dest, format string) map[string]any {
@@ -85,7 +86,7 @@ func (e *secretTestEnv) request(dest, format string) map[string]any {
func (e *secretTestEnv) read(t *testing.T, res any) string {
t.Helper()
path := res.(map[string]any)["path"].(string)
path := res.(pluginproto.SecretMaterializeResult).Path
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
@@ -102,7 +103,7 @@ func TestMaterializeSecretFormats(t *testing.T) {
if got := e.read(t, res); got != "<Password>"+testSecret+"</Password>" {
t.Fatalf("raw = %q", got)
}
path := res.(map[string]any)["path"].(string)
path := res.(pluginproto.SecretMaterializeResult).Path
if !pathInside(e.vmDir, path) {
t.Fatalf("%s is outside the VM folder %s", path, e.vmDir)
}
@@ -213,15 +214,15 @@ func TestDiscardSecretAndVMDeletionRemoveTheFiles(t *testing.T) {
if err != nil {
t.Fatal(err)
}
p1, p2 := first.(map[string]any)["path"].(string), second.(map[string]any)["path"].(string)
p1, p2 := first.(pluginproto.SecretMaterializeResult).Path, second.(pluginproto.SecretMaterializeResult).Path
discard := func(plugin string, req map[string]any) int {
raw, _ := json.Marshal(req)
res, err := e.app.discardSecret(e.h.Broker, plugin, raw)
res, err := e.app.discardSecret(nil, e.h.Broker, plugin, raw)
if err != nil {
t.Fatal(err)
}
return res.(map[string]any)["removed"].(int)
return res.(pluginproto.SecretDiscardResult).Removed
}
ref := map[string]any{"driver_id": e.ownerDriver.ID(), "name": "dev"}
if n := discard(e.ownerPlugin, map[string]any{"ref": ref, "path": p1}); n != 1 {
@@ -274,7 +275,7 @@ func TestDiscardSecretRetriesAFileItCouldNotDelete(t *testing.T) {
if err != nil {
t.Fatal(err)
}
path := res.(map[string]any)["path"].(string)
path := res.(pluginproto.SecretMaterializeResult).Path
// A non-empty folder in the file's place cannot be removed.
if err := os.Remove(path); err != nil {
t.Fatal(err)
+14 -1
View File
@@ -8,6 +8,8 @@ import (
"regexp"
"sort"
"strings"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// Contract catalogs (see docs/plugin-architecture.md).
@@ -290,8 +292,19 @@ func HostFeatures() []string {
out = append(out, feature)
}
}
// Every stable host/* method is advertised from the wire contract catalog,
// so a plugin can feature-detect a method without comparing versions.
out = append(out, pluginproto.Features()...)
sort.Strings(out)
return out
// Two catalogs may name the same feature; advertise each one once.
unique := out[:0]
for i, feature := range out {
if i > 0 && out[i-1] == feature {
continue
}
unique = append(unique, feature)
}
return unique
}
var reContributionID = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`)
+74
View File
@@ -0,0 +1,74 @@
package plugin
import (
"context"
"encoding/json"
"errors"
"net"
"testing"
"time"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// TestSupervisorHostMethodsAreCatalogued keeps the methods the supervisor
// serves itself inside the wire contract. A method that is not catalogued is
// not part of the contract, so a plugin must never be able to call it.
func TestSupervisorHostMethodsAreCatalogued(t *testing.T) {
for _, method := range ReverseHostAPIMethods() {
spec, ok := pluginproto.Lookup(method)
if !ok {
t.Errorf("%s is served but not in the contract catalog", method)
continue
}
if spec.Status != pluginproto.StatusStable {
t.Errorf("%s is served but marked %q", method, spec.Status)
}
}
}
// TestHandlerErrorKeepsItsCode checks that a handler that names a JSON-RPC
// code keeps it, so a rejected request stays distinguishable from a failed
// one on the plugin side.
func TestHandlerErrorKeepsItsCode(t *testing.T) {
hostRead, pluginWrite := net.Pipe()
pluginRead, hostWrite := net.Pipe()
host := NewRPCConn(hostRead, hostWrite)
plugin := NewRPCConn(pluginRead, pluginWrite)
t.Cleanup(func() {
host.Close()
plugin.Close()
})
host.Handle("host/console.key", func(context.Context, json.RawMessage) (any, error) {
return nil, &RPCError{Code: RPCInvalidParams, Message: "unknown field"}
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := plugin.Call(ctx, "host/console.key", map[string]any{"key": "a"}, nil)
var rpcErr *RPCError
if !errors.As(err, &rpcErr) {
t.Fatalf("err = %v, want *RPCError", err)
}
if rpcErr.Code != RPCInvalidParams {
t.Fatalf("code = %d, want %d", rpcErr.Code, RPCInvalidParams)
}
}
// TestHostFeaturesAdvertiseEveryStableHostMethod checks that a plugin can
// feature-detect each stable host method from the handshake.
func TestHostFeaturesAdvertiseEveryStableHostMethod(t *testing.T) {
advertised := map[string]bool{}
for _, feature := range HostFeatures() {
advertised[feature] = true
}
for _, method := range pluginproto.Methods() {
spec, _ := pluginproto.Lookup(method)
if spec.Status != pluginproto.StatusStable {
continue
}
if !advertised[pluginproto.Feature(method)] {
t.Errorf("%s is stable but its feature %q is not advertised", method, pluginproto.Feature(method))
}
}
}
+13
View File
@@ -35,6 +35,11 @@ type ManagerOptions struct {
SidecarDriverFactory SidecarDriverFactory
HostHandlers HostHandlerFactory
OnSettingsChanged func(pluginID, vmName string)
// OnSidecarStopped runs when a plugin's Sidecar process goes away or its
// scope is disposed, so the embedder can release what that process left
// held. It may run more than once for the same plugin and must be
// idempotent.
OnSidecarStopped func(pluginID string)
}
// ActiveThemePayload is sent to the frontend to apply L1/L2/Tier-3 themes (§5.1).
@@ -434,6 +439,11 @@ func (m *Manager) buildSidecarActivator(man Manifest, exePath string, blockingAl
Registry: m.registry,
IdleTimeout: 5 * time.Minute,
ExtraHandlers: extraHandlers,
OnExit: func() {
if m.opts.OnSidecarStopped != nil {
m.opts.OnSidecarStopped(pid)
}
},
LocaleProvider: func() (string, []string, map[string]string) {
loc := m.CurrentLocale()
chain := i18n.FallbackChain(loc)
@@ -455,6 +465,9 @@ func (m *Manager) buildSidecarActivator(man Manifest, exePath string, blockingAl
delete(m.supervisors, pid)
}
m.mu.Unlock()
if m.opts.OnSidecarStopped != nil {
m.opts.OnSidecarStopped(pid)
}
})
// Wire Sidecar hooks.
+11
View File
@@ -18,6 +18,10 @@ const maxRPCFrameBytes = 8 << 20 // 8 MiB per JSON-RPC frame (large blobs go via
// RPCMethodNotFound is the code a peer answers for a method it does not serve.
const RPCMethodNotFound = -32601
// RPCInvalidParams is the code a peer answers for a request whose params the
// contract does not accept, such as a field the method does not define.
const RPCInvalidParams = -32602
// RPCError is a JSON-RPC 2.0 error object.
type RPCError struct {
Code int `json:"code"`
@@ -258,6 +262,13 @@ func (c *RPCConn) dispatchInbound(env rpcEnvelope) {
return // notification
}
if err != nil {
// A handler that names a JSON-RPC code keeps it, so a rejected request
// is distinguishable from a failed one.
var rpcErr *RPCError
if errors.As(err, &rpcErr) {
c.sendResponse(env.ID, nil, rpcErr)
return
}
c.sendResponse(env.ID, nil, &RPCError{Code: -32000, Message: err.Error()})
return
}
+68
View File
@@ -133,6 +133,74 @@ func MatchesRange(version, expr string) bool {
return false
}
// RangeRequiresAtLeast reports whether every version that satisfies expr is at
// least min. It is how a host tells that a plugin opted into a contract
// revision: "^1.3.0" and ">=1.3.0" do, "^1.1.0" and an empty range do not.
// An expression it cannot decide reports false.
func RangeRequiresAtLeast(expr, min string) bool {
want, err := ParseSemVer(min)
if err != nil {
return false
}
expr = strings.TrimSpace(expr)
if expr == "" || expr == "*" {
return false
}
for _, branch := range strings.Split(expr, "||") {
branch = strings.TrimSpace(branch)
if branch == "" {
continue
}
if !branchRequiresAtLeast(branch, want) {
return false
}
}
return true
}
// branchRequiresAtLeast reports whether one conjunction of constraints already
// forces a version of at least want.
func branchRequiresAtLeast(clause string, want SemVer) bool {
tokens := strings.Fields(strings.ReplaceAll(clause, ",", " "))
if len(tokens) == 0 {
return false
}
for _, tok := range tokens {
if lowerBoundAtLeast(tok, want) {
return true
}
}
return false
}
// lowerBoundAtLeast reports whether one constraint excludes every version
// below want. An upper bound constrains nothing below.
func lowerBoundAtLeast(tok string, want SemVer) bool {
tok = strings.TrimSpace(tok)
switch {
case tok == "" || tok == "*":
return false
case strings.HasPrefix(tok, "<="), strings.HasPrefix(tok, "<"):
return false
case strings.HasPrefix(tok, ">="):
tok = tok[2:]
case strings.HasPrefix(tok, ">"):
tok = tok[1:]
case strings.HasPrefix(tok, "="):
tok = tok[1:]
case strings.HasPrefix(tok, "^"), strings.HasPrefix(tok, "~"):
tok = tok[1:]
}
if strings.HasSuffix(tok, ".x") || strings.HasSuffix(tok, ".*") {
tok = strings.TrimSuffix(strings.TrimSuffix(tok, ".x"), ".*")
}
target, err := ParseSemVer(tok)
if err != nil {
return false
}
return target.Compare(want) >= 0
}
func matchesAndClauses(v SemVer, clause string) bool {
// Normalize comma separators into spaces.
norm := strings.ReplaceAll(clause, ",", " ")
+34
View File
@@ -0,0 +1,34 @@
package plugin
import "testing"
func TestRangeRequiresAtLeast(t *testing.T) {
cases := []struct {
expr string
want bool
}{
{"", false},
{"*", false},
{"^1.1.0", false},
{"^1.2.0", false},
{"^1.3.0", true},
{">=1.3.0", true},
{">=1.3", true},
{">1.3.0", true},
{"=1.3.0", true},
{"~1.3.0", true},
{"1.3.x", true},
{"1.x", false},
{">=1.2.0 <2.0.0", false},
{">=1.3.0 <2.0.0", true},
{"^1.1.0 || ^1.3.0", false},
{"^1.3.0 || ^2.0.0", true},
{"<2.0.0", false},
{"garbage", false},
}
for _, tc := range cases {
if got := RangeRequiresAtLeast(tc.expr, "1.3.0"); got != tc.want {
t.Errorf("RangeRequiresAtLeast(%q, 1.3.0) = %v, want %v", tc.expr, got, tc.want)
}
}
}
+136 -102
View File
@@ -7,11 +7,15 @@ import (
"errors"
"fmt"
"io"
"maps"
"os"
"os/exec"
"slices"
"sync"
"sync/atomic"
"time"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// SidecarOptions configures an L3 (or future L2) supervised child process (§8).
@@ -27,6 +31,9 @@ type SidecarOptions struct {
MaxRestarts int // circuit breaker threshold (default 3)
ExtraHandlers map[string]RPCRequestHandler
LocaleProvider func() (string, []string, map[string]string) // returns (locale, fallbackChain, mergedBundle)
// OnExit runs whenever a Sidecar process goes away, whether it crashed or
// was stopped, so the embedder can undo state only that process could undo.
OnExit func()
}
type sidecarInstance struct {
@@ -294,114 +301,132 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
return inst, initResp.Capabilities, nil
}
// ReverseHostAPIMethods lists the host/* methods the supervisor serves itself,
// as opposed to the ones the embedder adds through ExtraHandlers. It is derived
// from the registration table, so the list cannot drift from what is served.
func ReverseHostAPIMethods() []string {
return slices.Sorted(maps.Keys((&SidecarSupervisor{}).reverseHostAPIHandlers()))
}
// reverseHostAPIHandlers builds the methods this supervisor serves itself.
func (s *SidecarSupervisor) reverseHostAPIHandlers() map[string]func(context.Context, json.RawMessage) (any, error) {
pid := s.opts.PluginID
broker := s.opts.Broker
return map[string]func(context.Context, json.RawMessage) (any, error){
"host/notify": func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
req, err := pluginproto.DecodeParams[pluginproto.NotifyParams]("host/notify", raw, false)
if err != nil {
return nil, err
}
return pluginproto.OKResult{OK: true}, broker.Notify(pid, req.Title, req.Body)
},
"host/audit": func(_ context.Context, raw json.RawMessage) (any, error) {
req, err := pluginproto.DecodeParams[pluginproto.AuditParams]("host/audit", raw, false)
if err != nil {
return nil, err
}
if broker != nil {
if !broker.allowRate(pid) {
return nil, fmt.Errorf("plugin %q exceeded audit rate limit", pid)
}
broker.Audit(pid, "PLUGIN", req.Message)
}
return pluginproto.OKResult{OK: true}, nil
},
"host/vm.spawn": func(ctx context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
req, err := pluginproto.DecodeParams[pluginproto.SpawnParams]("host/vm.spawn", raw, false)
if err != nil {
return nil, err
}
ref := VMRef{Name: req.VMName}
if req.Ref != nil {
ref = *req.Ref
if ref.Name == "" {
ref.Name = req.VMName
}
}
vmPID, err := broker.SpawnManagedVMProcessWithRef(ctx, pid, ref, req.ExePath, req.Args, req.WorkDir, req.Env)
if err != nil {
return nil, err
}
return pluginproto.SpawnResult{PID: vmPID}, nil
},
"host/vm.stop": func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
req, err := pluginproto.DecodeParams[pluginproto.ProcessParams]("host/vm.stop", raw, false)
if err != nil {
return nil, err
}
if req.Ref != nil {
return pluginproto.OKResult{OK: true}, broker.StopManagedVMProcessByRef(pid, *req.Ref)
}
return pluginproto.OKResult{OK: true}, broker.StopManagedVMProcess(pid, req.PID)
},
"host/vm.isRunning": func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return pluginproto.IsRunningResult{Running: false}, nil
}
req, err := pluginproto.DecodeParams[pluginproto.ProcessParams]("host/vm.isRunning", raw, false)
if err != nil {
return nil, err
}
if req.Ref != nil {
return pluginproto.IsRunningResult{Running: broker.IsManagedVMRunningForPlugin(pid, *req.Ref)}, nil
}
return pluginproto.IsRunningResult{Running: broker.IsManagedProcessRunningForPlugin(pid, req.PID)}, nil
},
"host/vm.reportState": func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
rep, err := pluginproto.DecodeParams[pluginproto.ReportedVMState]("host/vm.reportState", raw, false)
if err != nil {
return nil, err
}
if err := broker.ReportVMState(pid, rep); err != nil {
return nil, err
}
return pluginproto.OKResult{OK: true}, nil
},
}
}
func (s *SidecarSupervisor) registerReverseHostAPI(conn *RPCConn) {
pid := s.opts.PluginID
broker := s.opts.Broker
conn.Handle("host/notify", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
var req struct {
Title string `json:"title"`
Body string `json:"body"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
return map[string]any{"ok": true}, broker.Notify(pid, req.Title, req.Body)
})
conn.Handle("host/audit", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker != nil {
if !broker.allowRate(pid) {
return nil, fmt.Errorf("plugin %q exceeded audit rate limit", pid)
// Every method authorizes from the contract catalog, so a permission can
// never drift from the method it guards. The broker repeats the check for
// the calls it owns.
handlers := s.reverseHostAPIHandlers()
for _, method := range ReverseHostAPIMethods() {
run := handlers[method]
conn.Handle(method, func(ctx context.Context, raw json.RawMessage) (any, error) {
spec, ok := pluginproto.Lookup(method)
if !ok {
return nil, &RPCError{Code: RPCMethodNotFound, Message: "method not found: " + method}
}
var req struct {
Message string `json:"message"`
if broker != nil {
for _, perm := range spec.Permissions {
if perm == pluginproto.OriginPermission {
continue
}
if err := broker.Authorize(pid, perm); err != nil {
return nil, err
}
}
}
_ = json.Unmarshal(raw, &req)
broker.Audit(pid, "PLUGIN", req.Message)
}
return map[string]any{"ok": true}, nil
})
conn.Handle("host/vm.spawn", func(ctx context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
var req struct {
VMName string `json:"vm_name"`
Ref *VMRef `json:"ref"`
ExePath string `json:"exe_path"`
Args []string `json:"args"`
WorkDir string `json:"work_dir"`
Env []string `json:"env"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
ref := VMRef{Name: req.VMName}
if req.Ref != nil {
ref = *req.Ref
if ref.Name == "" {
ref.Name = req.VMName
}
}
vmPID, err := broker.SpawnManagedVMProcessWithRef(ctx, pid, ref, req.ExePath, req.Args, req.WorkDir, req.Env)
if err != nil {
return nil, err
}
return map[string]any{"pid": vmPID}, nil
})
conn.Handle("host/vm.stop", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
var req struct {
PID int `json:"pid"`
Ref *VMRef `json:"ref"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
if req.Ref != nil {
return map[string]any{"ok": true}, broker.StopManagedVMProcessByRef(pid, *req.Ref)
}
return map[string]any{"ok": true}, broker.StopManagedVMProcess(pid, req.PID)
})
conn.Handle("host/vm.isRunning", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return map[string]any{"running": false}, nil
}
var req struct {
PID int `json:"pid"`
Ref *VMRef `json:"ref"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
if req.Ref != nil {
return map[string]any{"running": broker.IsManagedVMRunningForPlugin(pid, *req.Ref)}, nil
}
return map[string]any{"running": broker.IsManagedProcessRunningForPlugin(pid, req.PID)}, nil
})
conn.Handle("host/vm.reportState", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
var rep ReportedVMState
if err := json.Unmarshal(raw, &rep); err != nil {
return nil, err
}
if err := broker.ReportVMState(pid, rep); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
})
return run(ctx, raw)
})
}
for method, h := range s.opts.ExtraHandlers {
conn.Handle(method, h)
@@ -415,6 +440,15 @@ func (s *SidecarSupervisor) onInstanceExit(inst *sidecarInstance, exitErr error)
if isCurrent {
s.cur = nil
}
s.mu.Unlock()
// The process that held input is gone only when the instance that exited
// was the live one. A zero-downtime reload retires the previous instance
// after the replacement is already serving, so releasing there would lift
// keys the replacement just pressed.
if (isCurrent || stopped) && s.opts.OnExit != nil {
s.opts.OnExit()
}
s.mu.Lock()
if !stopped && isCurrent {
s.crashCount++
s.lastCrash = time.Now()
+32
View File
@@ -0,0 +1,32 @@
package plugin
import (
"sync/atomic"
"testing"
)
// TestRetiredInstanceExitDoesNotReleaseHeldInput checks that a zero-downtime
// reload does not make the embedder lift input the replacement process just
// pressed: only the exit of the live instance, or a stopped supervisor, reports
// that the plugin can no longer release what it holds.
func TestRetiredInstanceExitDoesNotReleaseHeldInput(t *testing.T) {
var exits atomic.Int32
sup := NewSidecarSupervisor(SidecarOptions{
PluginID: "acme.tool",
OnExit: func() { exits.Add(1) },
})
live := &sidecarInstance{}
sup.cur = live
sup.onInstanceExit(live, nil)
if got := exits.Load(); got != 1 {
t.Fatalf("the live instance exiting reported %d times, want 1", got)
}
replacement := &sidecarInstance{}
sup.cur = replacement
sup.onInstanceExit(live, nil)
if got := exits.Load(); got != 1 {
t.Fatalf("a retired instance reported %d times, want the count to stay at 1", got)
}
}
+6 -29
View File
@@ -11,11 +11,12 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
const (
// PluginAPIVersion is the host plugin API contract version (SemVer).
PluginAPIVersion = "1.2.0"
PluginAPIVersion = "1.3.0"
// UIAPIVersion is the frontend UI contract version (SemVer); the contract
// itself lives in frontend/src/styles/ui-contract.ts (§5.1, §6.3).
UIAPIVersion = "2.1.0"
@@ -555,41 +556,17 @@ type GuestDriverContribution struct {
}
// VMRef identifies a VM by owning driver and name on the Sidecar wire.
type VMRef struct {
DriverID string `json:"driver_id"`
Name string `json:"name"`
}
type VMRef = pluginproto.VMRef
// VMEndpoint is one way to reach a guest, as a Sidecar reports it. The
// internal/driver package validates and acts on it.
type VMEndpoint struct {
Kind string `json:"kind"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
User string `json:"user,omitempty"`
Distro string `json:"distro,omitempty"`
VM string `json:"vm,omitempty"`
Serial string `json:"serial,omitempty"`
Ready bool `json:"ready"`
}
type VMEndpoint = pluginproto.VMEndpoint
// GuestOSInfo describes the guest operating system on the Sidecar wire.
type GuestOSInfo struct {
Family string `json:"family,omitempty"`
Distro string `json:"distro,omitempty"`
Version string `json:"version,omitempty"`
Arch string `json:"arch,omitempty"`
}
type GuestOSInfo = pluginproto.GuestOSInfo
// ReportedVMState is the payload of `host/vm.reportState`.
type ReportedVMState struct {
Ref VMRef `json:"ref"`
State string `json:"state"`
Ready *bool `json:"ready,omitempty"`
Phase string `json:"phase,omitempty"`
Endpoints []VMEndpoint `json:"endpoints,omitempty"`
GuestOS *GuestOSInfo `json:"guest_os,omitempty"`
}
type ReportedVMState = pluginproto.ReportedVMState
// HookContribution subscribes a Sidecar or L2 script to a lifecycle event.
type HookContribution struct {
+257
View File
@@ -0,0 +1,257 @@
// Package pluginproto is the single source of truth for the Sidecar Host API:
// which host/* methods exist, which permissions each one needs, and the request
// and result shapes both sides decode. It imports only the standard library, so
// the host, pkg/pluginsdk and third-party plugins share one copy of the wire
// contract instead of each declaring its own anonymous structs.
//
// A method that is not in HostMethods is not part of the contract: the host
// answers it with JSON-RPC -32601, and a plugin must not call it.
package pluginproto
import (
"bytes"
"encoding/json"
"errors"
"io"
"sort"
"strings"
)
// Status marks whether the host acts on a method.
type Status string
const (
// StatusStable methods are implemented by the host and covered by the
// compatibility promise.
StatusStable Status = "stable"
// StatusExperimental methods are published so plugins can feature-detect
// them, but carry no compatibility promise.
StatusExperimental Status = "experimental"
)
// OriginPermission marks a method whose authorization depends on the request
// URL: the caller must declare net:<origin> for the URL it passes.
const OriginPermission = "net:<origin>"
// StrictParamsVersion is the pluginApi version from which a plugin's requests
// are decoded strictly. Older plugins keep tolerant decoding so a released
// plugin that sends a field this host has not implemented yet keeps working.
const StrictParamsVersion = "1.3.0"
// MethodSpec describes one host/* method.
type MethodSpec struct {
Status Status
// Permissions lists every permission the caller must hold. An empty list
// means the method needs none beyond being a registered plugin.
Permissions []string
// Feature is the handshake feature that advertises the method. An empty
// value derives one from the method name.
Feature string
// StrictParams makes the host reject request fields the contract does not
// define (JSON-RPC -32602) instead of ignoring them.
StrictParams bool
// Summary is one line for `plugin doctor` and the generated reference.
Summary string
}
// HostMethods is the authoritative catalog of reverse Host API methods.
var HostMethods = map[string]MethodSpec{
"host/notify": {
Status: StatusStable, Permissions: []string{"ui:notify"},
Summary: "Show a host notification.",
},
"host/audit": {
Status: StatusStable,
Summary: "Append one line to the plugin's audit log (rate limited).",
},
"host/vm.spawn": {
Status: StatusStable, Permissions: []string{"process:spawn"}, Feature: "host.vm.spawn.ref",
Summary: "Start a process for a VM and put it into that VM's job object.",
},
"host/vm.stop": {
Status: StatusStable, Permissions: []string{"vm:control"},
Summary: "Terminate a process this plugin started, by pid or by VM ref.",
},
"host/vm.isRunning": {
Status: StatusStable,
Summary: "Report whether a process this plugin started is still alive.",
},
"host/vm.reportState": {
Status: StatusStable, Permissions: []string{"driver:vm"}, Feature: "host.vm.reportState",
Summary: "Push the state of a VM the calling driver owns.",
},
"host/download.start": {
Status: StatusStable, Permissions: []string{OriginPermission}, Feature: "host.download",
Summary: "Download a checksum-verified file in the background.",
},
"host/download.cancel": {
Status: StatusStable, Feature: "host.download",
Summary: "Cancel one of this plugin's downloads.",
},
"host/secret.materialize": {
Status: StatusStable, Permissions: []string{"driver:vm", "fs:vm_dir"}, Feature: "host.secret.materialize",
Summary: "Have the host write one secret setting into a VM folder without revealing it.",
},
"host/secret.discard": {
Status: StatusStable, Permissions: []string{"driver:vm"}, Feature: "host.secret.materialize",
Summary: "Delete the secret files the host materialized for a VM.",
},
"host/elevate.request": {
Status: StatusStable, Permissions: []string{"driver:vm"}, Feature: "host.elevate.request",
Summary: "Ask the user to confirm one whitelisted Windows elevation action.",
},
"host/vm.list": {
Status: StatusStable, Permissions: []string{"vm:read"}, StrictParams: true,
Summary: "List the VMs this plugin may see.",
},
"host/vm.get": {
Status: StatusStable, Permissions: []string{"vm:read"}, StrictParams: true,
Summary: "Read one VM's details.",
},
"host/vm.start": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Start a VM.",
},
"host/vm.shutdown": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Shut a VM down, or stop it outright when force is set.",
},
"host/vm.suspend": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Suspend a VM.",
},
"host/vm.resume": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Resume a VM.",
},
"host/vm.clone": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Clone a VM into a temporary VM this plugin owns.",
},
"host/vm.delete": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Delete a temporary VM this plugin owns.",
},
"host/vm.snapshot.list": {
Status: StatusStable, Permissions: []string{"vm:read"}, StrictParams: true,
Summary: "List a VM's snapshots.",
},
"host/vm.snapshot.create": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Create a snapshot.",
},
"host/vm.snapshot.restore": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Restore a snapshot of a VM the user authorized this plugin to access.",
},
"host/console.screenshot": {
Status: StatusStable, Permissions: []string{"vm:screen"}, StrictParams: true,
Summary: "Capture the guest screen, optionally one region of it, as JPEG.",
},
"host/console.pointer": {
Status: StatusStable, Permissions: []string{"qmp:write"}, StrictParams: true,
Summary: "Move the pointer, press or release a button, click or scroll.",
},
"host/console.key": {
Status: StatusStable, Permissions: []string{"qmp:write"}, StrictParams: true,
Summary: "Press a key, or hold and release it with down.",
},
"host/console.type": {
Status: StatusStable, Permissions: []string{"qmp:write"}, StrictParams: true,
Summary: "Type text as US-layout key strokes.",
},
"host/console.typeSecret": {
Status: StatusStable, Permissions: []string{"qmp:write"}, StrictParams: true,
Summary: "Type one of this plugin's own secret settings without revealing it.",
},
"host/console.release": {
Status: StatusStable, Permissions: []string{"qmp:write"}, StrictParams: true,
Summary: "Release the keys and pointer buttons this plugin still holds.",
},
}
// Lookup returns the spec of one method.
func Lookup(method string) (MethodSpec, bool) {
spec, ok := HostMethods[method]
return spec, ok
}
// Methods lists every catalogued method, sorted.
func Methods() []string {
out := make([]string, 0, len(HostMethods))
for method := range HostMethods {
out = append(out, method)
}
sort.Strings(out)
return out
}
// Feature returns the handshake feature that advertises method.
func Feature(method string) string {
if spec, ok := HostMethods[method]; ok && spec.Feature != "" {
return spec.Feature
}
return "host." + strings.ReplaceAll(strings.TrimPrefix(method, "host/"), "/", ".")
}
// Features lists the handshake features of every stable method, sorted and
// without duplicates. Plugins feature-detect with these instead of comparing
// version numbers.
func Features() []string {
seen := map[string]bool{}
out := []string{}
for method, spec := range HostMethods {
if spec.Status != StatusStable {
continue
}
feature := Feature(method)
if seen[feature] {
continue
}
seen[feature] = true
out = append(out, feature)
}
sort.Strings(out)
return out
}
// InvalidParamsError reports a request the contract does not accept. The host
// answers it with JSON-RPC -32602.
type InvalidParamsError struct {
Method string
Reason string
}
func (e *InvalidParamsError) Error() string {
if e.Method == "" {
return e.Reason
}
return e.Method + ": " + e.Reason
}
// DecodeParams decodes one request into out. An absent or null params member
// leaves out at its zero value. With strict set, a field the contract does not
// define, or trailing data after the request object, is an error instead of
// being dropped silently.
func DecodeParams[T any](method string, raw json.RawMessage, strict bool) (T, error) {
var out T
trimmed := bytes.TrimSpace(raw)
if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
return out, nil
}
if !strict {
if err := json.Unmarshal(trimmed, &out); err != nil {
return out, &InvalidParamsError{Method: method, Reason: err.Error()}
}
return out, nil
}
dec := json.NewDecoder(bytes.NewReader(trimmed))
dec.DisallowUnknownFields()
if err := dec.Decode(&out); err != nil {
return out, &InvalidParamsError{Method: method, Reason: err.Error()}
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return out, &InvalidParamsError{Method: method, Reason: "unexpected data after the request object"}
}
return out, nil
}
+162
View File
@@ -0,0 +1,162 @@
package pluginproto
import (
"encoding/json"
"errors"
"sort"
"strings"
"testing"
)
func TestEveryMethodIsFullyDescribed(t *testing.T) {
for method, spec := range HostMethods {
if !strings.HasPrefix(method, "host/") {
t.Errorf("%s is not a host/* method", method)
}
if spec.Status != StatusStable && spec.Status != StatusExperimental {
t.Errorf("%s has status %q", method, spec.Status)
}
if strings.TrimSpace(spec.Summary) == "" {
t.Errorf("%s has no summary", method)
}
if Feature(method) == "" || !strings.HasPrefix(Feature(method), "host.") {
t.Errorf("%s advertises feature %q", method, Feature(method))
}
for _, perm := range spec.Permissions {
if strings.TrimSpace(perm) == "" {
t.Errorf("%s lists an empty permission", method)
}
}
}
}
func TestFeaturesAreSortedUniqueAndStableOnly(t *testing.T) {
features := Features()
if !sort.StringsAreSorted(features) {
t.Fatalf("features are not sorted: %v", features)
}
seen := map[string]bool{}
for _, feature := range features {
if seen[feature] {
t.Fatalf("feature %q is advertised twice", feature)
}
seen[feature] = true
}
stable := map[string]bool{}
for method, spec := range HostMethods {
if spec.Status == StatusStable {
stable[Feature(method)] = true
}
}
if len(stable) != len(features) {
t.Fatalf("features = %v, want one per stable method (%d)", features, len(stable))
}
for feature := range stable {
if !seen[feature] {
t.Fatalf("stable feature %q is not advertised", feature)
}
}
}
func TestConsoleMethodsNeedTheWritePermission(t *testing.T) {
for _, method := range []string{
"host/console.screenshot", "host/console.pointer", "host/console.key",
"host/console.type", "host/console.typeSecret", "host/console.release",
} {
spec, ok := Lookup(method)
if !ok {
t.Fatalf("%s is missing from the catalog", method)
}
want := "vm:screen"
if method != "host/console.screenshot" {
want = "qmp:write"
}
if len(spec.Permissions) != 1 || spec.Permissions[0] != want {
t.Errorf("%s requires %v, want %s", method, spec.Permissions, want)
}
if !spec.StrictParams {
t.Errorf("%s does not decode its params strictly", method)
}
}
}
func TestVMAndConsoleMethodsDecodeStrictly(t *testing.T) {
// The driver-side methods the supervisor serves keep tolerant decoding; the
// VM and console methods the app serves are strict.
strict := []string{
"host/vm.list", "host/vm.get", "host/vm.start", "host/vm.shutdown", "host/vm.suspend",
"host/vm.resume", "host/vm.clone", "host/vm.delete", "host/vm.snapshot.list",
"host/vm.snapshot.create", "host/vm.snapshot.restore",
"host/console.screenshot", "host/console.pointer", "host/console.key",
"host/console.type", "host/console.typeSecret", "host/console.release",
}
for _, method := range strict {
spec, ok := Lookup(method)
if !ok {
t.Errorf("%s is missing from the catalog", method)
continue
}
if !spec.StrictParams {
t.Errorf("%s does not decode its params strictly", method)
}
}
}
func TestDecodeParamsTolerantKeepsUnknownFields(t *testing.T) {
out, err := DecodeParams[ScreenshotParams]("host/console.screenshot", json.RawMessage(`{"vm":"a","nope":1}`), false)
if err != nil {
t.Fatalf("tolerant decode failed: %v", err)
}
if out.VM != "a" {
t.Fatalf("vm = %q", out.VM)
}
}
func TestDecodeParamsStrictRejectsUnknownFields(t *testing.T) {
_, err := DecodeParams[ScreenshotParams]("host/console.screenshot", json.RawMessage(`{"vm":"a","nope":1}`), true)
var invalid *InvalidParamsError
if !errors.As(err, &invalid) {
t.Fatalf("err = %v, want InvalidParamsError", err)
}
if invalid.Method != "host/console.screenshot" {
t.Fatalf("method = %q", invalid.Method)
}
}
func TestDecodeParamsStrictRejectsTrailingData(t *testing.T) {
_, err := DecodeParams[KeyParams]("host/console.key", json.RawMessage(`{"key":"a"}{"key":"b"}`), true)
var invalid *InvalidParamsError
if !errors.As(err, &invalid) {
t.Fatalf("err = %v, want InvalidParamsError", err)
}
}
func TestDecodeParamsAcceptsMissingAndNullParams(t *testing.T) {
for _, raw := range []json.RawMessage{nil, json.RawMessage("null"), json.RawMessage(" ")} {
out, err := DecodeParams[VMParams]("host/vm.list", raw, true)
if err != nil {
t.Fatalf("decode %q failed: %v", raw, err)
}
if out != (VMParams{}) {
t.Fatalf("decode %q = %+v, want the zero value", raw, out)
}
}
}
func TestDecodeParamsReportsATypeErrorAsInvalidParams(t *testing.T) {
_, err := DecodeParams[ScreenshotParams]("host/console.screenshot", json.RawMessage(`{"max_width":"wide"}`), false)
var invalid *InvalidParamsError
if !errors.As(err, &invalid) {
t.Fatalf("err = %v, want InvalidParamsError", err)
}
}
func TestMethodsAreSorted(t *testing.T) {
methods := Methods()
if !sort.StringsAreSorted(methods) {
t.Fatalf("methods are not sorted: %v", methods)
}
if len(methods) != len(HostMethods) {
t.Fatalf("methods = %d, catalog = %d", len(methods), len(HostMethods))
}
}
+326
View File
@@ -0,0 +1,326 @@
package pluginproto
// The wire types of every host/* method. Both the host handlers and
// pkg/pluginsdk decode and encode these, so a field cannot exist on one side
// only.
// VMRef identifies a VM by owning driver and name. Two drivers may own VMs
// with the same name, so a caller that knows the driver always sends the ref.
type VMRef struct {
DriverID string `json:"driver_id"`
Name string `json:"name"`
}
// VMEndpoint is one way to reach a guest. Kind is one of "ssh", "wsl", "rdp",
// "vmconnect" and "adb".
type VMEndpoint struct {
Kind string `json:"kind"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
User string `json:"user,omitempty"`
Distro string `json:"distro,omitempty"`
VM string `json:"vm,omitempty"`
Serial string `json:"serial,omitempty"`
Ready bool `json:"ready"`
}
// GuestOSInfo describes the guest operating system. Family is one of "macos",
// "linux", "windows" and "android".
type GuestOSInfo struct {
Family string `json:"family,omitempty"`
Distro string `json:"distro,omitempty"`
Version string `json:"version,omitempty"`
Arch string `json:"arch,omitempty"`
}
// ReportedVMState is the payload of host/vm.reportState.
type ReportedVMState struct {
Ref VMRef `json:"ref"`
State string `json:"state"`
Ready *bool `json:"ready,omitempty"`
Phase string `json:"phase,omitempty"`
Endpoints []VMEndpoint `json:"endpoints,omitempty"`
GuestOS *GuestOSInfo `json:"guest_os,omitempty"`
}
// OKResult is the result of the methods that only report success.
type OKResult struct {
OK bool `json:"ok"`
}
// NotifyParams is the payload of host/notify.
type NotifyParams struct {
Title string `json:"title"`
Body string `json:"body"`
}
// AuditParams is the payload of host/audit.
type AuditParams struct {
Message string `json:"message"`
}
// SpawnParams is the payload of host/vm.spawn. Ref wins over vm_name when both
// are set.
type SpawnParams struct {
VMName string `json:"vm_name,omitempty"`
Ref *VMRef `json:"ref,omitempty"`
ExePath string `json:"exe_path"`
Args []string `json:"args,omitempty"`
WorkDir string `json:"work_dir,omitempty"`
Env []string `json:"env,omitempty"`
}
// SpawnResult is the result of host/vm.spawn.
type SpawnResult struct {
PID int `json:"pid"`
}
// ProcessParams addresses a process by pid or by the VM ref whose job object
// holds it. It is the payload of host/vm.stop and host/vm.isRunning.
type ProcessParams struct {
PID int `json:"pid,omitempty"`
Ref *VMRef `json:"ref,omitempty"`
}
// IsRunningResult is the result of host/vm.isRunning.
type IsRunningResult struct {
Running bool `json:"running"`
}
// DownloadParams is the payload of host/download.start. SHA256 or SHA256URL
// (with SHA256Name selecting a line) is required; the host verifies the file.
type DownloadParams struct {
URL string `json:"url"`
SHA256 string `json:"sha256,omitempty"`
SHA256URL string `json:"sha256_url,omitempty"`
SHA256Name string `json:"sha256_name,omitempty"`
Dest string `json:"dest"`
Size int64 `json:"size,omitempty"`
Label string `json:"label,omitempty"`
}
// DownloadResult is the result of host/download.start.
type DownloadResult struct {
ID string `json:"id"`
TaskID string `json:"task_id"`
}
// DownloadCancelParams is the payload of host/download.cancel.
type DownloadCancelParams struct {
ID string `json:"id"`
}
// SecretMaterializeParams is the payload of host/secret.materialize. Template
// must hold {{secret}}; Format is "raw" (default), "xml" or "base64-utf16le".
type SecretMaterializeParams struct {
Setting string `json:"setting"`
Ref VMRef `json:"ref"`
Template string `json:"template"`
Dest string `json:"dest"`
Format string `json:"format,omitempty"`
}
// SecretMaterializeResult is the result of host/secret.materialize.
type SecretMaterializeResult struct {
Path string `json:"path"`
}
// SecretDiscardParams is the payload of host/secret.discard. An empty Path
// discards every file the host materialized for Ref.
type SecretDiscardParams struct {
Ref VMRef `json:"ref"`
Path string `json:"path,omitempty"`
}
// SecretDiscardResult is the result of host/secret.discard.
type SecretDiscardResult struct {
Removed int `json:"removed"`
}
// ElevateParams is the payload of host/elevate.request.
type ElevateParams struct {
Action string `json:"action"`
}
// ElevateResult is the result of host/elevate.request, after the user
// confirmed both the host dialog and the Windows UAC prompt.
type ElevateResult struct {
OK bool `json:"ok"`
Action string `json:"action"`
ExitCode int `json:"exit_code,omitempty"`
RebootRequired bool `json:"reboot_required,omitempty"`
LogoffRequired bool `json:"logoff_required,omitempty"`
}
// VMParams addresses one VM by name or by canonical driverID:name reference.
type VMParams struct {
VM string `json:"vm"`
}
// VMShutdownParams is the payload of host/vm.shutdown. Force stops a VM that
// does not shut down on request.
type VMShutdownParams struct {
VM string `json:"vm"`
Force bool `json:"force,omitempty"`
}
// VMView is what host/vm.list and host/vm.get report about one VM. Fields
// that need the user's per-VM consent are present only when it was granted.
type VMView struct {
VM string `json:"vm"`
Name string `json:"name"`
DriverID string `json:"driver_id"`
State string `json:"state"`
Authorized bool `json:"authorized"`
Phase string `json:"phase"`
Owned bool `json:"owned"`
CPUs int `json:"cpus,omitempty"`
Memory string `json:"memory,omitempty"`
DiskSummary string `json:"disk_summary,omitempty"`
SSHPort int `json:"ssh_port,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
SSHUsername string `json:"ssh_username,omitempty"`
}
// VMListResult is the result of host/vm.list.
type VMListResult struct {
VMs []VMView `json:"vms"`
}
// VMCloneParams is the payload of host/vm.clone. The host registers the clone
// as this plugin's temporary VM, so a plugin may name it freely; the name only
// has to be free on the source VM's driver.
type VMCloneParams struct {
VM string `json:"vm"`
CloneName string `json:"clone_name"`
}
// VMCloneResult is the result of host/vm.clone.
type VMCloneResult struct {
VM string `json:"vm"`
Name string `json:"name"`
DriverID string `json:"driver_id"`
State string `json:"state"`
Owned bool `json:"owned"`
}
// SnapshotNameParams is the payload of host/vm.snapshot.create and
// host/vm.snapshot.restore.
type SnapshotNameParams struct {
VM string `json:"vm"`
Name string `json:"name"`
}
// Snapshot describes one restore point.
type Snapshot struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedAt int64 `json:"created_at"`
VMStateBytes int64 `json:"vm_state_bytes"`
}
// SnapshotListResult is the result of host/vm.snapshot.list.
type SnapshotListResult struct {
Snapshots []Snapshot `json:"snapshots"`
}
// SnapshotResult is the result of host/vm.snapshot.create and
// host/vm.snapshot.restore.
type SnapshotResult struct {
OK bool `json:"ok"`
Name string `json:"name"`
}
// Region is a rectangle. In a screenshot request it is expressed in the
// coordinate space of the reference frame the caller sends as Width and
// Height; in a screenshot result it is the source-pixel rectangle that was
// captured.
type Region struct {
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
}
// ScreenshotParams is the payload of host/console.screenshot. MaxWidth caps
// the width of the returned image; a value outside the supported range is
// brought into it rather than refused. Region selects a part of the screen:
// Width and Height name the image the region was measured in, and without them
// the region is in source pixels.
type ScreenshotParams struct {
VM string `json:"vm"`
MaxWidth int `json:"max_width,omitempty"`
Region *Region `json:"region,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
}
// ScreenshotResult is the result of host/console.screenshot. Blank marks a
// frame that is one flat color, which is a normal state during boot, login and
// display switches rather than a failure.
type ScreenshotResult struct {
MIMEType string `json:"mime_type"`
Width int `json:"width"`
Height int `json:"height"`
SourceWidth int `json:"source_width"`
SourceHeight int `json:"source_height"`
Blank bool `json:"blank"`
Data string `json:"data"`
Region *Region `json:"region,omitempty"`
}
// PointerParams is the payload of host/console.pointer. Action is one of
// "move", "button", "click" and "scroll". Move and button down/up leave the
// guest holding what was pressed until a later call releases it.
type PointerParams struct {
VM string `json:"vm"`
Action string `json:"action"`
X int `json:"x,omitempty"`
Y int `json:"y,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Button string `json:"button,omitempty"`
Down *bool `json:"down,omitempty"`
Delta int `json:"delta,omitempty"`
Horizontal bool `json:"horizontal,omitempty"`
}
// KeyParams is the payload of host/console.key. Without Down the host presses
// and releases Key with Modifiers held. With Down set the host sends key
// transitions for Key and every modifier and the guest keeps them held until a
// later call releases them, so the caller must pair it or call
// host/console.release.
type KeyParams struct {
VM string `json:"vm"`
Key string `json:"key"`
Modifiers []string `json:"modifiers,omitempty"`
Down *bool `json:"down,omitempty"`
}
// TypeParams is the payload of host/console.type.
type TypeParams struct {
VM string `json:"vm"`
Text string `json:"text"`
}
// TypeSecretParams is the payload of host/console.typeSecret. Setting names one
// of the calling plugin's own settings; the host never returns its value, so a
// plugin can use a secret it stored without ever reading it.
type TypeSecretParams struct {
VM string `json:"vm"`
Setting string `json:"setting"`
}
// ReleaseParams is the payload of host/console.release. It lifts the keys and
// pointer buttons the caller still holds in the guest.
type ReleaseParams struct {
VM string `json:"vm"`
Keys []string `json:"keys,omitempty"`
Buttons []string `json:"buttons,omitempty"`
}
// CharactersResult is the result of host/console.type and
// host/console.typeSecret.
type CharactersResult struct {
Characters int `json:"characters"`
}
+99
View File
@@ -0,0 +1,99 @@
package pluginsdk
import (
"context"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// The console methods a plugin may call on a VM the user authorized it for.
// A key or a pointer button sent with a press stays held in the guest until a
// release arrives, so a caller that holds input must pair it or call Release;
// the host lifts whatever is still held when the plugin's process goes away.
// Screenshot captures the guest screen. Region is measured in the coordinate
// space of the reference frame of size Width by Height, and MaxWidth caps the
// width of the returned image. A Blank frame is a normal state during boot,
// login and display switches, not a failure.
func (s *Server) Screenshot(ctx context.Context, req pluginproto.ScreenshotParams) (pluginproto.ScreenshotResult, error) {
var res pluginproto.ScreenshotResult
err := s.callFeature(ctx, "host/console.screenshot", req, &res)
return res, err
}
// MovePointer moves the pointer to x, y, given in a frame of size width by
// height.
func (s *Server) MovePointer(ctx context.Context, vm string, x, y, width, height int) error {
return s.callFeature(ctx, "host/console.pointer", pluginproto.PointerParams{
VM: vm, Action: "move", X: x, Y: y, Width: width, Height: height,
}, nil)
}
// PointerButton presses or releases one pointer button.
func (s *Server) PointerButton(ctx context.Context, vm, button string, down bool) error {
return s.callFeature(ctx, "host/console.pointer", pluginproto.PointerParams{
VM: vm, Action: "button", Button: button, Down: &down,
}, nil)
}
// Click presses and releases one pointer button.
func (s *Server) Click(ctx context.Context, vm, button string) error {
return s.callFeature(ctx, "host/console.pointer", pluginproto.PointerParams{
VM: vm, Action: "click", Button: button,
}, nil)
}
// Scroll sends wheel steps. A positive delta scrolls down, or right when
// horizontal is set.
func (s *Server) Scroll(ctx context.Context, vm string, delta int, horizontal bool) error {
return s.callFeature(ctx, "host/console.pointer", pluginproto.PointerParams{
VM: vm, Action: "scroll", Delta: delta, Horizontal: horizontal,
}, nil)
}
// Key presses and releases one key with its modifiers held.
func (s *Server) Key(ctx context.Context, vm, key string, modifiers ...string) error {
return s.callFeature(ctx, "host/console.key", pluginproto.KeyParams{
VM: vm, Key: key, Modifiers: modifiers,
}, nil)
}
// KeyDown presses one key and leaves it held in the guest.
func (s *Server) KeyDown(ctx context.Context, vm, key string) error {
down := true
return s.callFeature(ctx, "host/console.key", pluginproto.KeyParams{VM: vm, Key: key, Down: &down}, nil)
}
// KeyUp releases one key this plugin pressed with KeyDown.
func (s *Server) KeyUp(ctx context.Context, vm, key string) error {
down := false
return s.callFeature(ctx, "host/console.key", pluginproto.KeyParams{VM: vm, Key: key, Down: &down}, nil)
}
// Release lifts the keys and pointer buttons this plugin still holds.
func (s *Server) Release(ctx context.Context, vm string, keys, buttons []string) error {
return s.callFeature(ctx, "host/console.release", pluginproto.ReleaseParams{
VM: vm, Keys: keys, Buttons: buttons,
}, nil)
}
// Type types text as US-layout key strokes and returns how many characters
// reached the guest.
func (s *Server) Type(ctx context.Context, vm, text string) (int, error) {
var res pluginproto.CharactersResult
if err := s.callFeature(ctx, "host/console.type", pluginproto.TypeParams{VM: vm, Text: text}, &res); err != nil {
return 0, err
}
return res.Characters, nil
}
// TypeSecret has the host type one of this plugin's own secret settings. The
// plugin never sees the value, and the user must have enabled the plugin's
// secret-typing consent for that VM.
func (s *Server) TypeSecret(ctx context.Context, vm, setting string) (int, error) {
var res pluginproto.CharactersResult
if err := s.callFeature(ctx, "host/console.typeSecret", pluginproto.TypeSecretParams{VM: vm, Setting: setting}, &res); err != nil {
return 0, err
}
return res.Characters, nil
}
+205
View File
@@ -0,0 +1,205 @@
package pluginsdk
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"io"
"testing"
"time"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// newFeatureServer starts a Server whose handshake advertises features and
// returns it with the pipes a fake host answers on. The pipes are closed on
// cleanup so a blocked write or read never keeps the test binary alive.
func newFeatureServer(t *testing.T, features []string) (*Server, context.Context, *io.PipeReader, *io.PipeWriter) {
t.Helper()
inR, inW := io.Pipe()
outR, outW := io.Pipe()
t.Cleanup(func() {
_ = inW.Close()
_ = outR.Close()
})
srv := NewWithIO(inR, outW)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go func() { _ = srv.Serve(ctx) }()
if err := writeRPCFrame(inW, map[string]any{
"jsonrpc": "2.0",
"id": 1,
"method": "plugin/initialize",
"params": map[string]any{
"pluginId": "acme.tool",
"pluginApi": "1.3.0",
"dataDir": t.TempDir(),
"features": features,
},
}); err != nil {
t.Fatalf("write initialize: %v", err)
}
// The features arrive with the handshake, so wait for it before calling.
deadline := time.Now().Add(2 * time.Second)
for srv.InitInfo().PluginID == "" && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if srv.InitInfo().PluginID == "" {
t.Fatal("the handshake never completed")
}
return srv, ctx, outR, inW
}
// answerHostCalls answers the SDK's Host API calls from a queue and reports
// each request on got. Frames without a method are the SDK's own responses and
// are skipped, and the loop keeps draining so the SDK never blocks on a write.
func answerHostCalls(out *io.PipeReader, in *io.PipeWriter, replies []any, got chan<- envelope) {
br := bufio.NewReader(out)
queue := append([]any(nil), replies...)
for {
frame, err := readFrame(br)
if err != nil {
return
}
var req envelope
if json.Unmarshal(frame, &req) != nil || req.Method == "" || len(req.ID) == 0 {
continue
}
if got != nil {
got <- req
}
if len(queue) == 0 {
continue
}
result := queue[0]
queue = queue[1:]
raw, _ := json.Marshal(result)
if err := writeRPCFrame(in, map[string]any{
"jsonrpc": "2.0", "id": json.RawMessage(req.ID), "result": json.RawMessage(raw),
}); err != nil {
return
}
}
}
func TestVMAndConsoleCallsUseTheContractShapes(t *testing.T) {
srv, ctx, outR, inW := newFeatureServer(t, pluginproto.Features())
got := make(chan envelope, 16)
go answerHostCalls(outR, inW, []any{
map[string]any{"vms": []map[string]any{{"vm": "d:dev", "name": "dev", "driver_id": "d", "state": "running", "authorized": true, "phase": "normal", "owned": false}}},
map[string]any{"ok": true},
map[string]any{"mime_type": "image/jpeg", "width": 640, "height": 360, "source_width": 2560, "source_height": 1440, "blank": false, "data": "AAA", "region": map[string]any{"x": 0, "y": 0, "width": 2560, "height": 1440}},
map[string]any{"ok": true},
map[string]any{"ok": true},
map[string]any{"characters": 5},
}, got)
vms, err := srv.ListVMs(ctx)
if err != nil || len(vms) != 1 || vms[0].Name != "dev" || !vms[0].Authorized {
t.Fatalf("ListVMs = %+v, %v", vms, err)
}
if req := <-got; req.Method != "host/vm.list" {
t.Fatalf("list request = %s", req.Method)
}
if err := srv.StartVM(ctx, "d:dev"); err != nil {
t.Fatalf("StartVM: %v", err)
}
req := <-got
var start pluginproto.VMParams
if req.Method != "host/vm.start" || json.Unmarshal(req.Params, &start) != nil || start.VM != "d:dev" {
t.Fatalf("start request = %s %s", req.Method, req.Params)
}
shot, err := srv.Screenshot(ctx, pluginproto.ScreenshotParams{
VM: "d:dev", MaxWidth: 640, Width: 1280, Height: 720,
Region: &pluginproto.Region{X: 0, Y: 0, Width: 640, Height: 360},
})
if err != nil || shot.Width != 640 || shot.Region == nil || shot.Region.Width != 2560 {
t.Fatalf("Screenshot = %+v, %v", shot, err)
}
req = <-got
if req.Method != "host/console.screenshot" ||
!bytes.Contains(req.Params, []byte(`"max_width":640`)) ||
!bytes.Contains(req.Params, []byte(`"region"`)) {
t.Fatalf("screenshot request = %s %s", req.Method, req.Params)
}
if err := srv.KeyDown(ctx, "d:dev", "cmd"); err != nil {
t.Fatalf("KeyDown: %v", err)
}
req = <-got
var key pluginproto.KeyParams
if req.Method != "host/console.key" || json.Unmarshal(req.Params, &key) != nil || key.Key != "cmd" || key.Down == nil || !*key.Down {
t.Fatalf("key request = %s %s", req.Method, req.Params)
}
if err := srv.Release(ctx, "d:dev", []string{"cmd"}, []string{"left"}); err != nil {
t.Fatalf("Release: %v", err)
}
req = <-got
var release pluginproto.ReleaseParams
if req.Method != "host/console.release" || json.Unmarshal(req.Params, &release) != nil || len(release.Keys) != 1 || len(release.Buttons) != 1 {
t.Fatalf("release request = %s %s", req.Method, req.Params)
}
n, err := srv.Type(ctx, "d:dev", "hello")
if err != nil || n != 5 {
t.Fatalf("Type = %d, %v", n, err)
}
if req := <-got; req.Method != "host/console.type" {
t.Fatalf("type request = %s", req.Method)
}
}
func TestUnadvertisedMethodIsRefusedBeforeItIsSent(t *testing.T) {
srv, ctx, outR, inW := newFeatureServer(t, []string{"host.vm.list"})
got := make(chan envelope, 4)
go answerHostCalls(outR, inW, nil, got)
// The host serves host/console.screenshot, but this handshake does not
// advertise it, so the SDK must not send the call.
_, err := srv.Screenshot(ctx, pluginproto.ScreenshotParams{VM: "d:dev"})
var sdkErr *Error
if !errors.As(err, &sdkErr) || sdkErr.Code != MethodNotFound {
t.Fatalf("err = %v, want a method-not-found SDK error", err)
}
select {
case req := <-got:
t.Fatalf("the SDK sent %s to a host that does not advertise it", req.Method)
default:
}
}
func TestHostErrorCodeReachesTheCaller(t *testing.T) {
srv, ctx, outR, inW := newFeatureServer(t, pluginproto.Features())
go func() {
br := bufio.NewReader(outR)
for {
frame, err := readFrame(br)
if err != nil {
return
}
var req envelope
if json.Unmarshal(frame, &req) != nil || req.Method == "" || len(req.ID) == 0 {
continue
}
_ = writeRPCFrame(inW, map[string]any{
"jsonrpc": "2.0",
"id": json.RawMessage(req.ID),
"error": map[string]any{"code": InvalidParams, "message": `host/console.key: json: unknown field "hold_ms"`},
})
return
}
}()
err := srv.KeyDown(ctx, "d:dev", "cmd")
var sdkErr *Error
if !errors.As(err, &sdkErr) || sdkErr.Code != InvalidParams {
t.Fatalf("err = %v, want code %d", err, InvalidParams)
}
}
+48 -30
View File
@@ -15,10 +15,30 @@ import (
"strings"
"sync"
"sync/atomic"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// PluginAPIVersion is the protocol version spoken by this SDK.
const PluginAPIVersion = "1.2.0"
const PluginAPIVersion = "1.3.0"
// Error is a JSON-RPC error the host answered a Host API call with. Code is
// the JSON-RPC code, so a caller can tell a rejected request (-32602) from a
// method the host does not serve (-32601) or a failed call (-32000).
type Error struct {
Code int
Message string
}
func (e *Error) Error() string { return e.Message }
// InvalidParams is the code the host answers with when a request carries a
// field the contract does not define.
const InvalidParams = -32602
// MethodNotFound is the code the host answers with for a method it does not
// serve.
const MethodNotFound = -32601
// Handler handles one inbound JSON-RPC method from the Reims-Go host.
type Handler func(ctx context.Context, params json.RawMessage) (any, error)
@@ -293,6 +313,28 @@ func (s *Server) Handle(method string, h Handler) {
s.mu.Unlock()
}
// HasFeature reports whether the host advertised feature in the handshake.
func (s *Server) HasFeature(feature string) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.initInfo.HasFeature(feature)
}
// callFeature invokes a Host API method the contract catalogs and the host
// advertised. A method outside the contract, or one this host does not
// advertise, is refused before it is sent, so a plugin never depends on a host
// that cannot serve it.
func (s *Server) callFeature(ctx context.Context, method string, params, out any) error {
if _, ok := pluginproto.Lookup(method); !ok {
return &Error{Code: MethodNotFound, Message: method + " is not part of the Host API contract"}
}
feature := pluginproto.Feature(method)
if !s.HasFeature(feature) {
return &Error{Code: MethodNotFound, Message: "the host does not advertise " + feature}
}
return s.CallHost(ctx, method, params, out)
}
// CallHost invokes a reverse Host API method on Reims-Go (e.g. "host/notify",
// "host/vm.spawn", "host/vm.stop", "host/audit").
func (s *Server) CallHost(ctx context.Context, method string, params any, out any) error {
@@ -326,7 +368,7 @@ func (s *Server) CallHost(ctx context.Context, method string, params any, out an
select {
case resp := <-ch:
if resp.Error != nil {
return errors.New(resp.Error.Message)
return &Error{Code: resp.Error.Code, Message: resp.Error.Message}
}
if out != nil && len(resp.Result) > 0 && string(resp.Result) != "null" {
return json.Unmarshal(resp.Result, out)
@@ -354,42 +396,18 @@ func (s *Server) SpawnVMProcess(ctx context.Context, vmName, exePath string, arg
// VMRef identifies a VM by its owning driver and name. Two drivers may own VMs
// with the same name, so a Sidecar with several drivers always sends the ref.
type VMRef struct {
DriverID string `json:"driver_id"`
Name string `json:"name"`
}
type VMRef = pluginproto.VMRef
// GuestOSInfo describes the guest operating system (family is one of
// "macos", "linux", "windows", "android").
type GuestOSInfo struct {
Family string `json:"family,omitempty"`
Distro string `json:"distro,omitempty"`
Version string `json:"version,omitempty"`
Arch string `json:"arch,omitempty"`
}
type GuestOSInfo = pluginproto.GuestOSInfo
// VMEndpoint is one way to reach a guest. Kind is one of "ssh", "wsl", "rdp",
// "vmconnect" and "adb"; the host runs a fixed command per kind.
type VMEndpoint struct {
Kind string `json:"kind"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
User string `json:"user,omitempty"`
Distro string `json:"distro,omitempty"`
VM string `json:"vm,omitempty"`
Serial string `json:"serial,omitempty"`
Ready bool `json:"ready"`
}
type VMEndpoint = pluginproto.VMEndpoint
// VMStateReport is the payload of `host/vm.reportState`.
type VMStateReport struct {
Ref VMRef `json:"ref"`
State string `json:"state"`
Ready *bool `json:"ready,omitempty"`
Phase string `json:"phase,omitempty"`
Endpoints []VMEndpoint `json:"endpoints,omitempty"`
GuestOS *GuestOSInfo `json:"guest_os,omitempty"`
}
type VMStateReport = pluginproto.ReportedVMState
// SpawnVMProcessWithRef spawns a VM process owned by ref. The host puts the
// process and every child it starts into one per-VM job, so monitoring,
+79
View File
@@ -0,0 +1,79 @@
package pluginsdk
import (
"context"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// The VM methods a plugin may call on VMs the user authorized it for. Every
// call is refused before it is sent unless the host advertised the method in
// the handshake, so a plugin never depends on a host that cannot serve it.
// ListVMs returns the VMs the host shows this plugin.
func (s *Server) ListVMs(ctx context.Context) ([]pluginproto.VMView, error) {
var res pluginproto.VMListResult
if err := s.callFeature(ctx, "host/vm.list", nil, &res); err != nil {
return nil, err
}
return res.VMs, nil
}
// GetVM reads one VM by name or by canonical driverID:name reference.
func (s *Server) GetVM(ctx context.Context, vm string) (pluginproto.VMView, error) {
var view pluginproto.VMView
err := s.callFeature(ctx, "host/vm.get", pluginproto.VMParams{VM: vm}, &view)
return view, err
}
// StartVM starts a VM.
func (s *Server) StartVM(ctx context.Context, vm string) error {
return s.callFeature(ctx, "host/vm.start", pluginproto.VMParams{VM: vm}, nil)
}
// ShutdownVM shuts a VM down, or stops it outright when force is set.
func (s *Server) ShutdownVM(ctx context.Context, vm string, force bool) error {
return s.callFeature(ctx, "host/vm.shutdown", pluginproto.VMShutdownParams{VM: vm, Force: force}, nil)
}
// SuspendVM suspends a VM.
func (s *Server) SuspendVM(ctx context.Context, vm string) error {
return s.callFeature(ctx, "host/vm.suspend", pluginproto.VMParams{VM: vm}, nil)
}
// ResumeVM resumes a VM.
func (s *Server) ResumeVM(ctx context.Context, vm string) error {
return s.callFeature(ctx, "host/vm.resume", pluginproto.VMParams{VM: vm}, nil)
}
// CloneVM clones a VM into a temporary VM this plugin owns. cloneName must
// start with __agent- so the host can recognize and clean up the clone.
func (s *Server) CloneVM(ctx context.Context, vm, cloneName string) (pluginproto.VMCloneResult, error) {
var res pluginproto.VMCloneResult
err := s.callFeature(ctx, "host/vm.clone", pluginproto.VMCloneParams{VM: vm, CloneName: cloneName}, &res)
return res, err
}
// DeleteVM deletes a temporary VM this plugin owns.
func (s *Server) DeleteVM(ctx context.Context, vm string) error {
return s.callFeature(ctx, "host/vm.delete", pluginproto.VMParams{VM: vm}, nil)
}
// ListSnapshots lists a VM's snapshots.
func (s *Server) ListSnapshots(ctx context.Context, vm string) ([]pluginproto.Snapshot, error) {
var res pluginproto.SnapshotListResult
if err := s.callFeature(ctx, "host/vm.snapshot.list", pluginproto.VMParams{VM: vm}, &res); err != nil {
return nil, err
}
return res.Snapshots, nil
}
// CreateSnapshot creates a snapshot.
func (s *Server) CreateSnapshot(ctx context.Context, vm, name string) error {
return s.callFeature(ctx, "host/vm.snapshot.create", pluginproto.SnapshotNameParams{VM: vm, Name: name}, nil)
}
// RestoreSnapshot restores a snapshot of a temporary VM this plugin owns.
func (s *Server) RestoreSnapshot(ctx context.Context, vm, name string) error {
return s.callFeature(ctx, "host/vm.snapshot.restore", pluginproto.SnapshotNameParams{VM: vm, Name: name}, nil)
}