diff --git a/changes/computer-use-mcp.json b/changes/computer-use-mcp.json new file mode 100644 index 0000000..03434c1 --- /dev/null +++ b/changes/computer-use-mcp.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 0, + "authors": ["bvzrays"], + "zh": "新增默认启用的「虚拟机交互」扩展,统一处理虚拟机截图、鼠标、键盘与文本输入;新增按虚拟机授权的插件控制通道和 MCP 服务。", + "en": "Add the enabled-by-default Computer Use extension for VM screenshots, pointer, keyboard, and text input, plus per-VM authorization and the MCP service." +} diff --git a/docs/architecture.md b/docs/architecture.md index 5cdebef..b9e9761 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -45,11 +45,13 @@ flowchart TB 客户端编译为 Windows 图形子系统程序。命令行模式下保留调用方传入的管道或文件句柄,缺失时自动挂载父终端控制台;在交互式终端中追加 `| Out-Host` 可等待命令执行完毕。 -### 双通道本地控制套接字 +### 宿主控制台代理与本地控制通道 -便携运行时为每台运行中的虚拟机创建本地 Unix 域控制套接字。由于单个控制端点同一时刻只服务一个连接,客户端对自动键入、屏幕截图与状态迁移按虚拟机串行复用短连接,键入期间自动暂停后台截图。 +便携运行时为每台运行中的虚拟机创建本地 Unix 域 QMP 套接字。内置 `builtin.computer-use` 服务按虚拟机复用 QMP 长连接并串行处理截图、鼠标、键盘和文本输入;缩略图与打字流程共用该服务,键入期间暂停后台截图。 -Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚拟化后端异常退出。在 Windows 10 宿主机上,客户端为虚拟机附加不自动重启标志,并额外挂载一条独立的本地 Unix 域控制套接字监听重启退出事件,进程干净退出后自动重新拉起。两条通道均不使用 TCP 端口,防止虚拟机经用户态网络反向访问宿主机控制面。 +L3 插件经权限核验的 Host API 请求虚拟机状态、截图和输入操作,宿主不接受插件提供的 QMP 套接字或虚拟机目录。MCP 客户端通过 `reims-go plugin connect ` 与桌面进程通信;Windows 命名管道按可执行文件路径和用户 SID 摘要区分,ACL 限制当前用户并拒绝远程客户端。 + +Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚拟化后端异常退出。在 Windows 10 宿主机上,客户端为虚拟机附加不自动重启标志,并额外挂载一条独立的本地 Unix 域控制套接字监听重启退出事件,进程干净退出后自动重新拉起。QMP 和插件控制通道均不使用 TCP 端口,防止虚拟机经用户态网络反向访问宿主机控制面。 ### 宿客协作与目录隔离 diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 45bc4fc..868691b 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -20,7 +20,7 @@ flowchart TB | 层级 | 运行形态 | 隔离与约束边界 | | :--- | :--- | :--- | -| 编译期内置扩展 | 随主程序编译的模块,经同一注册表装载 | 核心默认主题始终启用;macOS 客体支持、宿客传输、剪贴板互通、输入服务与并行下载器可独立启停且停用零残留 | +| 编译期内置扩展 | 随主程序编译的模块,经同一注册表装载 | 核心默认主题始终启用;macOS 客体支持、宿客传输、剪贴板互通、输入服务、虚拟机交互与并行下载器可独立启停且停用零残留 | | L1 声明式插件 | 纯 JSON 配置、词表、字体与静态样式资源 | 不含可执行代码,全部字段经宿主白名单与静态扫描校验 | | 运行时包 | 原生虚拟化与工具二进制归档 | 自身不注册插件代码,仅由客体驱动以受控子进程调用 | | L3 外部进程插件 | 每插件独立子进程,采用 `Content-Length` 分帧的双向 JSON-RPC 2.0 通信(日志走标准错误流) | 崩溃或死循环不拖垮主窗口;操作系统层面拥有当前用户完整账户权限,仅宿主接口受权限表约束 | @@ -30,6 +30,12 @@ flowchart TB 2. Apache-2.0 客户端本体与外部组件仅通过独立子进程和协议交互,插件包、私有数据、缓存与日志全部隔离在数据目录的 `plugins/` 下。 3. 插件无权读取硬件序列号、UUID、ROM 或 MAC 地址,无权静默触发管理员提权或系统重启,也无权直接改写 `vm.toml`;插件贡献的排障数据一律经宿主脱敏后才写入排障包。 +内置 `builtin.computer-use` 默认启用,通过宿主控制台代理串行处理每台虚拟机的截图、鼠标、键盘和文本输入,现有缩略图与打字入口共用该服务。它不实现 MCP 协议。 + +L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。官方 `reims.agent` 插件实现 MCP 工具、VM 状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。 + +Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向插件返回明文。 + ## 生命周期、参数账本与资源预算 每个启用中的插件拥有独立的作用域,注册的服务、事件订阅、界面槽位、后台监听与系统钩子均绑定释放函数;插件停用、卸载或激活失败时按逆序完整拆除。服务依赖变更时先停用失去依赖的插件,再按依赖拓扑激活就绪插件。 @@ -66,7 +72,7 @@ flowchart TB | :--- | :--- | :--- | | 低危 | `vm:read`、`ui:notify`、`task:progress`、`fs:plugin_data`、`log:read` | 启用时展示用途说明,纯声明式语言包无需高危权限 | | 中危 | `vm:intent`、`runtime:source`、`net:`、`ui:slot`、`input:filter`、`fs:pick` | 首次启用时由用户确认 | -| 高危 | `driver:vm`、`runtime:provider`、`process:spawn`、`vm:control`、`qmp:write`、`fs:vm_dir`、`fs:shared`、`host:clipboard`、`ui:script` | 市场端与已安装页统一展示风险说明、入口路径、SHA-256、发布者、许可证与能力明细并要求显式勾选;升级新增高危权限,或 L3 原生程序及 `ui:script` 交互脚本入口哈希变化时自动暂停并重新审批(仅开发链接模式跳过哈希锚定) | +| 高危 | `driver:vm`、`runtime:provider`、`process:spawn`、`vm:control`、`vm:screen`、`qmp:write`、`fs:vm_dir`、`fs:shared`、`host:clipboard`、`ui:script` | 市场端与已安装页统一展示风险说明、入口路径、SHA-256、发布者、许可证与能力明细并要求显式勾选;升级新增高危权限,或 L3 原生程序及 `ui:script` 交互脚本入口哈希变化时自动暂停并重新审批(仅开发链接模式跳过哈希锚定) | 市场预检与本地安装共用同一套平台及版本兼容校验:平台支持 `windows-x64`、`windows/amd64`、`*` 与 `any`(不区分大小写,省略时默认全平台兼容),引擎范围同时核验 `pluginApi`、`uiApi`、`bridgeApi` 与 `reims-go`(开发构建跳过宿主版本门槛)。市场索引与插件包下载统一走直连客户端(不委派外部或并行下载器插件),遵循系统代理,拒绝向非本机明文 HTTP 的降级重定向,并对包体大小与流式读空闲施加硬上限。仅当前会话经官方 HTTPS 市场索引新鲜拉取的条目或带内置可信签名的包可获得 `official` 或 `verified` 信任级;第三方自定义镜像、冷启动未联网的磁盘缓存以及网络异常回退的陈旧缓存均降为 `community`,且卡片展示与实际安装保持一致,网络恢复后下次查询即重新拉取。 diff --git a/go.mod b/go.mod index cf959d6..f2197a8 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/Nwflower/reims-go go 1.26.0 require ( + github.com/Microsoft/go-winio v0.6.2 github.com/klauspost/compress v1.20.5 github.com/pelletier/go-toml/v2 v2.4.3 github.com/ulikunitz/xz v0.5.17 diff --git a/go.sum b/go.sum index deea54e..8f6fc90 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 h1:N3IGoHHp9pb6mj1cbXbuaSXV/UMKwmbKLf53nQmtqMA= git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3/go.mod h1:QtOLZGz8olr4qH2vWK0QH0w0O4T9fEIjMuWpKUsH7nc= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY= github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= diff --git a/internal/app/app.go b/internal/app/app.go index c3edf8d..d4a1863 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -13,6 +13,7 @@ import ( "github.com/Nwflower/reims-go/internal/cli" "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/control" "github.com/Nwflower/reims-go/internal/dataroot" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/guesttools" @@ -112,7 +113,7 @@ type App struct { quitMode string vmStarts sync.WaitGroup lastVMs []driver.VMListItem - lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale + lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale lastVMListErr error pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick diskPaths map[string]cachedDiskPath @@ -125,6 +126,7 @@ type App struct { logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go) pluginMgr *plugin.Manager pluginMarket *plugin.MarketClient + controlServer *control.Server driverRouter *driver.Router lifecycleSvc *vmlifecycle.Service runtimeKinds *rt.KindRegistry @@ -139,6 +141,10 @@ type App struct { keymapPIDs map[string]int fallbackInputSvc *host.InputService inputShuttingDown bool + // computerUseOwnedVMs records temporary CoW VMs created by an MCP session. + // Ownership is process-scoped and disappears when the desktop process exits. + computerUseOwnedVMs map[string]map[string]bool + computerUseCloneMu sync.Mutex } // Lifecycle exposes Wails lifecycle callbacks without exporting them as @@ -254,6 +260,7 @@ func (a *App) shutdown(ctx context.Context) { } tasks.cancelAll() stopAllVMMonitors() + a.stopPluginControlServer() a.mu.Lock() a.inputShuttingDown = true fallback := a.fallbackInputSvc @@ -348,6 +355,7 @@ func (a *App) pollVMs(ctx context.Context) { } continue } + a.syncComputerUseOwnership(vms) watchExits(ctx, vms, exitWatched, a.wakePoll) type pinCandidate struct { name string @@ -452,6 +460,7 @@ func (a *App) pollVMs(ctx context.Context) { } for key := range removedVMs { name := vmNameFromKey(key) + a.forgetComputerUseOwnedVM(key) a.mu.Lock() delete(a.transitions, key) delete(a.pendingChanges, key) diff --git a/internal/app/computer_use_flow.go b/internal/app/computer_use_flow.go new file mode 100644 index 0000000..e4c8b39 --- /dev/null +++ b/internal/app/computer_use_flow.go @@ -0,0 +1,28 @@ +package app + +import ( + "errors" + + "github.com/Nwflower/reims-go/internal/console" + "github.com/Nwflower/reims-go/internal/plugin/builtin" +) + +var fallbackComputerUse = console.NewManager() + +func (a *App) computerUseService() (builtin.ComputerUseService, error) { + a.mu.Lock() + mgr := a.pluginMgr + a.mu.Unlock() + if mgr == nil { + return fallbackComputerUse, nil + } + raw, ok := mgr.Registry().LookupService(builtin.ServiceComputerUse) + if !ok { + return nil, errors.New("virtual machine interaction is disabled") + } + service, ok := raw.(builtin.ComputerUseService) + if !ok || service == nil { + return nil, errors.New("virtual machine interaction service is unavailable") + } + return service, nil +} diff --git a/internal/app/computer_use_host.go b/internal/app/computer_use_host.go new file mode 100644 index 0000000..96812fc --- /dev/null +++ b/internal/app/computer_use_host.go @@ -0,0 +1,738 @@ +package app + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "unicode/utf8" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/internal/plugin/builtin" + "github.com/Nwflower/reims-go/internal/thumb" +) + +const computerUsePreviewWidth = 1280 +const computerUseMaxTextRunes = 4000 +const computerUseSecretPluginID = "reims.agent" + +const computerUseOwnershipFile = ".reims-go-computer-use" + +type computerUseOwnership struct { + Version int `json:"version"` + PluginID string `json:"plugin_id"` + VMKey string `json:"vm_key"` +} + +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.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:control", "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), + } + // 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) + }) +} + +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 { + return nil, err + } + if strings.TrimSpace(req.Setting) == "" { + return nil, errors.New("secret setting name is required") + } + vm, err := a.resolveComputerUseVM(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + if mgr == nil { + return nil, errors.New("plugin manager is unavailable") + } + secret, err := mgr.SecretSetting(pluginID, vm.Ref().Key(), req.Setting) + if err != nil { + return nil, err + } + defer func() { secret = "" }() + if len(secret) == 0 || utf8.RuneCountInString(secret) > computerUseMaxTextRunes { + return nil, errors.New("secret must contain between 1 and 4000 characters") + } + count, err := a.injectTextIntoVMWithLogging(vm.Name, vm.Directory, secret, false, true) + if err != nil { + return nil, err + } + return map[string]any{"characters": count}, nil +} + +func (a *App) handleComputerUseVMList(ctx context.Context, _ json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) { + items, err := a.listVMsInternal(ctx) + if err != nil { + return nil, err + } + vms := make([]map[string]any, 0, len(items)) + for _, item := range items { + info, err := a.resolveVMInfo(item.DriverID, item.Name) + if err != nil { + continue + } + vms = append(vms, a.computerUseVMView(info, mgr, pluginID)) + } + return map[string]any{"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 { + return nil, err + } + info, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + return a.computerUseVMView(info, mgr, pluginID), nil +} + +func (a *App) computerUseVMView(vm driver.VMInfo, mgr *plugin.Manager, pluginID string) map[string]any { + 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()), + } + if vm.CPUs > 0 { + view["cpus"] = vm.CPUs + } + if vm.Memory != "" { + view["memory"] = vm.Memory + } + if vm.DiskSummary != "" { + view["disk_summary"] = vm.DiskSummary + } + if accessEnabled && vm.SSHPort > 0 { + view["ssh_port"] = vm.SSHPort + } + if len(vm.Capabilities) > 0 { + view["capabilities"] = append([]string(nil), vm.Capabilities...) + } + if accessEnabled { + username := a.GetVMSSHUserWithDriver(vm.DriverID, vm.Name) + if mgr != nil { + settings := mgr.GetSettings(pluginID, vm.Ref().Key(), false) + if configured, ok := settings["username"].(string); ok && strings.TrimSpace(configured) != "" { + username = strings.TrimSpace(configured) + } + } + if username != "" { + view["ssh_username"] = 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 { + return nil, err + } + vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + if err := a.StartVMWithDriver(vm.DriverID, vm.Name); err != nil { + return nil, err + } + return map[string]any{"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"` + } + if err := json.Unmarshal(raw, &req); err != nil { + return nil, err + } + vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + if err := a.StopVMWithDriver(vm.DriverID, vm.Name, false); err != nil { + return nil, err + } + return map[string]any{"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 { + return nil, err + } + cloneName := strings.TrimSpace(req.CloneName) + if cloneName == "" { + return nil, errors.New("clone_name is required") + } + if !strings.HasPrefix(cloneName, "__agent-") { + return nil, errors.New("temporary MCP clones must use the __agent- prefix") + } + vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + cloneRef := driver.NewVMRef(vm.DriverID, cloneName) + a.computerUseCloneMu.Lock() + defer a.computerUseCloneMu.Unlock() + if existing, listErr := a.listVMsInternal(ctx); listErr != nil { + return nil, listErr + } else if slices.ContainsFunc(existing, func(item driver.VMListItem) bool { + return item.Name == cloneName && driver.CanonicalDriverID(item.DriverID) == driver.CanonicalDriverID(vm.DriverID) + }) { + return nil, fmt.Errorf("VM name %q is already taken", cloneName) + } + if err := a.CloneVMCoWWithDriver(vm.DriverID, vm.Name, cloneName); err != nil { + // CloneCoW can fail after creating an overlay or VM record. The target + // was absent during the preflight above, so clean up any partial target. + if existing, listErr := a.listVMsInternal(ctx); listErr == nil && slices.ContainsFunc(existing, func(item driver.VMListItem) bool { + return item.Name == cloneName && driver.CanonicalDriverID(item.DriverID) == driver.CanonicalDriverID(vm.DriverID) + }) { + if cleanupErr := a.DeleteVMWithDriver(vm.DriverID, cloneName, false); cleanupErr != nil { + return nil, errors.Join(err, fmt.Errorf("clean up failed clone %q: %w", cloneName, cleanupErr)) + } + } + return nil, err + } + if _, err := a.persistComputerUseOwnership(pluginID, cloneRef.Key()); err != nil { + if cleanupErr := a.DeleteVMWithDriver(vm.DriverID, cloneName, false); cleanupErr != nil { + return nil, errors.Join(err, fmt.Errorf("clean up unregistered clone %q: %w", cloneName, cleanupErr)) + } + return nil, err + } + // The lifecycle service may not expose a newly-created VM until the next + // 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 +} + +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 { + return nil, err + } + vm, err := a.resolveComputerUseVMInfo(req.VM) + if err != nil { + return nil, err + } + if !a.computerUseOwned(pluginID, vm.Ref().Key()) { + return nil, fmt.Errorf("not_authorized: VM %q is not an MCP-owned temporary clone", vm.Name) + } + if vm.State == "running" { + if err := a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, false); err != nil { + return nil, err + } + } + if err := a.DeleteVMWithDriver(vm.DriverID, vm.Name, false); err != nil { + return nil, err + } + removeComputerUseOwnership(vm.Directory) + a.markComputerUseOwnedVM(pluginID, vm.Ref().Key(), false) + return map[string]any{"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 { + return nil, err + } + vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + snapshots, err := a.ListSnapshotsWithDriver(vm.DriverID, vm.Name) + if err != nil { + return nil, err + } + return map[string]any{"snapshots": snapshots}, 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 { + return nil, err + } + vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + if err := a.CreateSnapshotWithDriver(vm.DriverID, vm.Name, req.Name); err != nil { + return nil, err + } + return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil +} + +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 { + 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, errors.New("confirmation_required: restoring a user VM requires confirmation in Reims-Go") + } + if err := a.RestoreSnapshotWithDriver(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 + } +} + +func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (driver.VMInfo, error) { + ref = strings.TrimSpace(ref) + if ref == "" { + return driver.VMInfo{}, errors.New("VM reference is required") + } + vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, ref) + if err != nil { + return driver.VMInfo{}, err + } + if driver.CanonicalDriverID(vm.DriverID) != builtin.IDDriverReimsMacOS { + return driver.VMInfo{}, fmt.Errorf("computer_use_unavailable: driver %q does not support computer use", vm.DriverID) + } + current, ok := a.polledVMForDriver(vm.DriverID, vm.Name) + if !ok || current.State != "running" || current.PID == nil || *current.PID <= 0 { + return driver.VMInfo{}, fmt.Errorf("vm_not_running: VM %q is not running", vm.Name) + } + if phase := computerUseVMPhase(vm); phase != "normal" { + return driver.VMInfo{}, fmt.Errorf("confirmation_required: VM %q is in %s phase", vm.Name, phase) + } + if vm.Directory == "" { + vm.Directory = current.Dir + } + if vm.Directory == "" { + return driver.VMInfo{}, fmt.Errorf("VM %q has no console directory", vm.Name) + } + return vm, nil +} + +func (a *App) resolveAuthorizedComputerUseVMInfo(mgr *plugin.Manager, pluginID, ref string) (driver.VMInfo, error) { + vm, err := a.resolveComputerUseVMInfo(ref) + if err != nil { + return driver.VMInfo{}, err + } + if !a.computerUseVMAccessEnabled(mgr, pluginID, vm.Ref().Key()) { + return driver.VMInfo{}, fmt.Errorf("not_authorized: MCP access is disabled for VM %q in plugin settings", vm.Name) + } + return vm, nil +} + +func (a *App) computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) bool { + return computerUseVMAccessEnabled(mgr, pluginID, vmKey) || a.computerUseOwned(pluginID, vmKey) +} + +func (a *App) computerUseOwned(pluginID, vmKey string) bool { + a.mu.Lock() + defer a.mu.Unlock() + return a.computerUseOwnedVMs != nil && a.computerUseOwnedVMs[pluginID] != nil && a.computerUseOwnedVMs[pluginID][vmKey] +} + +func (a *App) markComputerUseOwnedVM(pluginID, vmKey string, owned bool) { + a.mu.Lock() + defer a.mu.Unlock() + if a.computerUseOwnedVMs == nil { + a.computerUseOwnedVMs = make(map[string]map[string]bool) + } + if a.computerUseOwnedVMs[pluginID] == nil { + a.computerUseOwnedVMs[pluginID] = make(map[string]bool) + } + if owned { + a.computerUseOwnedVMs[pluginID][vmKey] = true + } else { + delete(a.computerUseOwnedVMs[pluginID], vmKey) + } +} + +func (a *App) forgetComputerUseOwnedVM(vmKey string) { + vmKey = strings.TrimSpace(vmKey) + if vmKey == "" { + return + } + a.mu.Lock() + defer a.mu.Unlock() + for pluginID, owned := range a.computerUseOwnedVMs { + delete(owned, vmKey) + if len(owned) == 0 { + delete(a.computerUseOwnedVMs, pluginID) + } + } +} + +func writeComputerUseOwnership(vmDir, pluginID, vmKey string) error { + vmDir = strings.TrimSpace(vmDir) + pluginID = strings.TrimSpace(pluginID) + vmKey = strings.TrimSpace(vmKey) + if vmDir == "" || pluginID == "" || vmKey == "" { + return errors.New("temporary VM ownership metadata is incomplete") + } + data, err := json.Marshal(computerUseOwnership{Version: 1, PluginID: pluginID, VMKey: vmKey}) + if err != nil { + return err + } + path := filepath.Join(vmDir, computerUseOwnershipFile) + file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return fmt.Errorf("create temporary VM ownership marker: %w", err) + } + if _, writeErr := file.Write(append(data, '\n')); writeErr != nil { + _ = file.Close() + _ = os.Remove(path) + return fmt.Errorf("write temporary VM ownership marker: %w", writeErr) + } + if err := file.Close(); err != nil { + _ = os.Remove(path) + return fmt.Errorf("close temporary VM ownership marker: %w", err) + } + return nil +} + +func removeComputerUseOwnership(vmDir string) { + if strings.TrimSpace(vmDir) == "" { + return + } + _ = os.Remove(filepath.Join(vmDir, computerUseOwnershipFile)) +} + +func readComputerUseOwnership(vm driver.VMInfo) (computerUseOwnership, bool) { + if vm.Directory == "" || !strings.HasPrefix(vm.Name, "__agent-") { + return computerUseOwnership{}, false + } + raw, err := os.ReadFile(filepath.Join(vm.Directory, computerUseOwnershipFile)) + if err != nil { + return computerUseOwnership{}, false + } + var marker computerUseOwnership + if json.Unmarshal(raw, &marker) != nil || marker.Version != 1 || marker.PluginID == "" || marker.VMKey != vm.Ref().Key() { + return computerUseOwnership{}, false + } + return marker, true +} + +func (a *App) restoreComputerUseOwnedVMs(ctx context.Context) error { + vms, err := a.listVMsInternal(ctx) + if err != nil { + return err + } + a.syncComputerUseOwnership(vms) + return nil +} + +func (a *App) persistComputerUseOwnership(pluginID, vmKey string) (bool, error) { + vm, err := a.resolveComputerUseVMInfo(vmKey) + if err != nil || vm.Directory == "" { + // Driver inventories can lag behind a successful clone. The next VM + // inventory pass will retry persistence without discarding the clone. + return false, nil + } + if err := writeComputerUseOwnership(vm.Directory, pluginID, vmKey); err != nil { + return false, err + } + return true, nil +} + +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 == "" || !strings.HasPrefix(vm.Name, "__agent-") { + continue + } + marker, ok := readComputerUseOwnership(vm) + if ok { + a.markComputerUseOwnedVM(marker.PluginID, marker.VMKey, true) + continue + } + key := vm.Ref().Key() + a.mu.Lock() + var pluginIDs []string + for pluginID, owned := range a.computerUseOwnedVMs { + if owned[key] { + pluginIDs = append(pluginIDs, pluginID) + } + } + a.mu.Unlock() + for _, pluginID := range pluginIDs { + if err := writeComputerUseOwnership(vm.Directory, pluginID, key); err == nil { + break + } + } + } +} + +func computerUseVMPhase(vm driver.VMInfo) string { + if vmInfoBool(vm, "has_installer") { + return "installer" + } + if vmInfoBool(vm, "recovery_mode") { + return "recovery" + } + return "normal" +} + +func computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) bool { + if mgr == nil || strings.TrimSpace(pluginID) == "" || strings.TrimSpace(vmKey) == "" { + return false + } + value, _ := mgr.GetSettings(pluginID, vmKey, false)["allow_ai_access"].(bool) + return value +} + +// resolveComputerUseVMInfo accepts the bare VM name used by the UI and the +// canonical driverID:name reference returned by the VM list and resource APIs. +func (a *App) resolveComputerUseVMInfo(ref string) (driver.VMInfo, error) { + ref = strings.TrimSpace(ref) + if parsed, ok := driver.ParseVMRef(ref); ok { + return a.resolveVMInfo(parsed.DriverID, parsed.Name) + } + return a.resolveVMInfo("", ref) +} + +func (a *App) handleComputerUseScreenshot(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 { + return nil, err + } + vm, err := a.resolveComputerUseVM(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + service, err := a.computerUseService() + if err != nil { + return nil, err + } + a.mu.Lock() + if a.cfg == nil { + a.mu.Unlock() + return nil, errors.New("application configuration is unavailable") + } + tempDir := a.cfg.TempDir() + a.mu.Unlock() + if err := os.MkdirAll(tempDir, 0o755); err != nil { + return nil, err + } + file, err := os.CreateTemp(tempDir, "computer-use-*.ppm") + if err != nil { + return nil, err + } + path := file.Name() + if err := file.Close(); err != nil { + _ = os.Remove(path) + return nil, err + } + defer os.Remove(path) + format, err := service.Screendump(ctx, vm.Directory, path) + if err != nil { + return nil, err + } + sourceSize, err := thumb.Size(path, format) + if err != nil { + return nil, err + } + preview, err := thumb.LoadPreview(path, format, computerUsePreviewWidth) + if err != nil { + return nil, err + } + if preview == nil { + return nil, errors.New("VM screen is blank") + } + encoded, err := thumb.JPEG(preview, 84) + if err != nil { + return nil, err + } + bounds := preview.Bounds() + return map[string]any{ + "mime_type": "image/jpeg", + "width": bounds.Dx(), + "height": bounds.Dy(), + "source_width": sourceSize.X, + "source_height": sourceSize.Y, + "data": base64.StdEncoding.EncodeToString(encoded), + }, nil +} + +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 + } + vm, err := a.resolveComputerUseVM(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + service, err := a.computerUseService() + if err != nil { + return nil, err + } + switch strings.ToLower(strings.TrimSpace(req.Action)) { + case "move": + available, err := service.PointerAvailable(ctx, vm.Directory) + if err != nil { + return nil, err + } + if !available { + return nil, errors.New("VM has no active absolute pointer") + } + err = service.MouseMove(ctx, vm.Directory, req.X, req.Y, req.Width, req.Height) + case "button": + if req.Down == nil { + return nil, errors.New("button action requires down") + } + err = service.MouseButton(ctx, vm.Directory, req.Button, *req.Down) + case "click": + err = service.MouseClick(ctx, vm.Directory, req.Button) + case "scroll": + err = service.MouseScroll(ctx, vm.Directory, req.Delta, req.Horizontal) + default: + return nil, fmt.Errorf("unsupported pointer action %q", req.Action) + } + if err != nil { + return nil, err + } + return map[string]any{"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"` + } + if err := json.Unmarshal(raw, &req); err != nil { + return nil, err + } + if strings.TrimSpace(req.Key) == "" { + return nil, errors.New("key is required") + } + vm, err := a.resolveComputerUseVM(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + service, err := a.computerUseService() + if err != nil { + return nil, err + } + if err := service.PressKey(ctx, vm.Directory, req.Key, req.Modifiers...); err != nil { + return nil, err + } + return map[string]any{"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 { + return nil, err + } + if len(req.Text) == 0 || !utf8.ValidString(req.Text) { + return nil, errors.New("text must be non-empty valid UTF-8") + } + if utf8.RuneCountInString(req.Text) > computerUseMaxTextRunes { + return nil, fmt.Errorf("text exceeds %d characters", computerUseMaxTextRunes) + } + vm, err := a.resolveComputerUseVM(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + n, err := a.injectTextIntoVMWithLogging(vm.Name, vm.Directory, req.Text, false, true) + if err != nil { + return nil, err + } + return map[string]any{"characters": n}, nil +} diff --git a/internal/app/plugin_connect.go b/internal/app/plugin_connect.go new file mode 100644 index 0000000..786e753 --- /dev/null +++ b/internal/app/plugin_connect.go @@ -0,0 +1,51 @@ +package app + +import ( + "context" + "encoding/json" + "errors" + + "github.com/Nwflower/reims-go/internal/control" +) + +func (a *App) startPluginControlServer() { + a.mu.Lock() + if a.ctx == nil || a.pluginMgr == nil || a.controlServer != nil { + a.mu.Unlock() + return + } + a.mu.Unlock() + + server, err := control.Listen(func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) { + a.mu.Lock() + mgr := a.pluginMgr + a.mu.Unlock() + if mgr == nil { + return nil, errors.New("plugin manager is not ready") + } + return mgr.ChannelMessage(ctx, pluginID, channel, message) + }) + if err != nil { + a.emitLog("plugin", "Could not open local plugin control channel: "+err.Error()) + return + } + + a.mu.Lock() + if a.ctx == nil || a.pluginMgr == nil || a.controlServer != nil { + a.mu.Unlock() + _ = server.Close() + return + } + a.controlServer = server + a.mu.Unlock() +} + +func (a *App) stopPluginControlServer() { + a.mu.Lock() + server := a.controlServer + a.controlServer = nil + a.mu.Unlock() + if server != nil { + _ = server.Close() + } +} diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index 53c34fc..a612cf2 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -69,6 +69,7 @@ func (a *App) initPlugins() { a.emitLog("plugin", "Could not migrate macOS guest state: "+err.Error()) return } + var mgr *plugin.Manager mgr, err := plugin.NewManager(plugin.ManagerOptions{ DataRoot: dataRoot, HostVersion: version.Version, @@ -81,6 +82,12 @@ func (a *App) initPlugins() { SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any { return driver.NewSidecarDriver(contrib, sup) }, + HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler { + a.mu.Lock() + current := a.pluginMgr + a.mu.Unlock() + return a.computerUseHostHandlers(current, pluginID) + }, OnSettingsChanged: func(pluginID, vmName string) { a.onPluginSettingsChanged(pluginID, vmName) }, @@ -219,11 +226,15 @@ func (a *App) initPlugins() { fetch.SetDefaultDownloader(a.activeDownloader) mgr.Registry().Reconcile(context.Background()) + if err := a.restoreComputerUseOwnedVMs(context.Background()); err != nil { + a.emitLog("plugin", "Could not restore temporary computer-use VM ownership: "+err.Error()) + } mgr.MarkBootComplete() a.syncInputFilters() a.syncKeymapRules() a.syncClipboardPolicies() a.syncLocales() + a.startPluginControlServer() } // activeDownloader returns the highest-priority active downloader plugin provider, diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index 08d4d0d..42e01e4 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -1,7 +1,7 @@ package app // VM screen thumbnails for the VM page: while a VM runs, -// grab one frame over its QMP socket (`screendump`), shrink it to a small +// grab one frame through the built-in computer-use console (`screendump`), shrink it to a small // JPEG and keep it under \cache\thumbs, so a stopped VM can still // show its last screen. Nothing here touches vm.toml or the guest. @@ -22,7 +22,6 @@ import ( "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/qmp" "github.com/Nwflower/reims-go/internal/thumb" ) @@ -185,7 +184,11 @@ func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw) + service, err := a.computerUseService() + if err != nil { + return err + } + format, err := service.Screendump(ctx, vm.Dir, raw) if err != nil { return fmt.Errorf("capture screen: %w", err) } @@ -239,7 +242,11 @@ func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail, ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) defer cancel() - format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw) + service, err := a.computerUseService() + if err != nil { + return VMThumbnail{}, false + } + format, err := service.Screendump(ctx, vm.Dir, raw) if err != nil { return VMThumbnail{}, false } diff --git a/internal/app/type_flow.go b/internal/app/type_flow.go index 7a34a1d..90389a3 100644 --- a/internal/app/type_flow.go +++ b/internal/app/type_flow.go @@ -76,6 +76,10 @@ func (a *App) TypeText(name, text string) (int, error) { } func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool) (int, error) { + return a.injectTextIntoVMWithLogging(name, knownDir, text, fromRemoteIME, false) +} + +func (a *App) injectTextIntoVMWithLogging(name, knownDir, text string, fromRemoteIME, suppressLogs bool) (int, error) { text = strings.ReplaceAll(text, "\r\n", "\n") text = strings.ReplaceAll(text, "\r", "\n") if text == "" { @@ -108,6 +112,10 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool) } vmDir = d.Directory } + computerUse, err := a.computerUseService() + if err != nil { + return 0, err + } // Prefer Guest Tools Unicode injection for: // - any non-ASCII (Chinese, CJK punctuation, emoji), OR @@ -127,24 +135,24 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool) if srv != nil { pasteCtx, cancel := context.WithTimeout(ctx, 6*time.Second) mode, err := srv.InjectText(pasteCtx, name, text, func(c context.Context) error { - return qmp.SendPasteShortcut(c, vmDir) + return computerUse.SendPasteShortcut(c, vmDir) }) cancel() if err == nil { n := utf8.RuneCountInString(text) - if !fromRemoteIME { + if !fromRemoteIME && !suppressLogs { a.emitVMLog(name, fmt.Sprintf("Injected %d character(s) into %s via Guest Tools (%s) + Cmd+V.", n, name, mode)) } return n, nil } - if !errors.Is(err, guesttools.ErrGuestToolsNotConnected) { + if !suppressLogs && !errors.Is(err, guesttools.ErrGuestToolsNotConnected) { a.emitVMLog(name, fmt.Sprintf("Guest Tools text injection (%s) failed: %v", mode, err)) } } } // Fallback (or bare Enter/Tab / Recovery / Login screen): QMP US keystrokes. - n, err := qmp.TypeIntoVM(ctx, vmDir, text, nil) + n, err := computerUse.TypeText(ctx, vmDir, text, nil) var ue *qmp.UntypeableError if errors.As(err, &ue) { if fromRemoteIME { @@ -155,19 +163,21 @@ func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool) typing.lastHintAt[key] = time.Now() } typing.mu.Unlock() - if shouldLog { + if shouldLog && !suppressLogs { a.emitVMLog(name, "Remote IME Unicode text received, but Guest Tools is not connected in macOS yet (install Guest Tools to enable Chinese/Unicode remote input).") } - } else { + } else if !suppressLogs { a.emitVMLog(name, "Paste as keystrokes refused: "+ue.Error()) } return 0, fmt.Errorf("%w: %s", ErrNotTypeable, ue.Error()) } if err != nil { - a.emitVMLog(name, fmt.Sprintf("Paste as keystrokes stopped after %d keys: %v", n, err)) + if !suppressLogs { + a.emitVMLog(name, fmt.Sprintf("Paste as keystrokes stopped after %d keys: %v", n, err)) + } return n, err } - if !fromRemoteIME { + if !fromRemoteIME && !suppressLogs { a.emitVMLog(name, fmt.Sprintf("Typed %d keys into %s.", n, name)) } return n, nil diff --git a/internal/cli/macos_native.go b/internal/cli/macos_native.go index 4f7f4a7..b07e04a 100644 --- a/internal/cli/macos_native.go +++ b/internal/cli/macos_native.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/Nwflower/reims-go/internal/config" + "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/macos/guest" @@ -18,7 +19,6 @@ import ( "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/startprep" "github.com/Nwflower/reims-go/internal/plugin" - "github.com/Nwflower/reims-go/internal/qmp" ) func defaultMacOSGuestLang(loc i18n.Locale) string { return opencore.DefaultGuestLang(loc) } @@ -124,7 +124,7 @@ func typeMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, args if err != nil { return err } - n, err := qmp.TypeIntoVM(ctx, detail.Directory, text, nil) + n, err := console.NewManager().TypeText(ctx, detail.Directory, text, nil) if err != nil { return err } diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index 91a5952..c126abc 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -77,10 +77,12 @@ func openCLIMarketClient(cfg *config.Config) *plugin.MarketClient { func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { if len(args) == 0 { - return fmt.Errorf("usage: reims-go plugin ") + return fmt.Errorf("usage: reims-go plugin ") } ctx := context.Background() switch args[0] { + case "connect": + return pluginConnect(args[1:]) case "search": fs := flag.NewFlagSet("plugin search", flag.ContinueOnError) kind := fs.String("kind", "", "Filter by plugin kind (theme, locale, driver, tool, template, runtime)") diff --git a/internal/cli/plugin_connect_other.go b/internal/cli/plugin_connect_other.go new file mode 100644 index 0000000..5904563 --- /dev/null +++ b/internal/cli/plugin_connect_other.go @@ -0,0 +1,9 @@ +//go:build !windows + +package cli + +import "errors" + +func pluginConnect([]string) error { + return errors.New("plugin connect is available on Windows desktop builds") +} diff --git a/internal/cli/plugin_connect_windows.go b/internal/cli/plugin_connect_windows.go new file mode 100644 index 0000000..ac0e17e --- /dev/null +++ b/internal/cli/plugin_connect_windows.go @@ -0,0 +1,131 @@ +//go:build windows + +package cli + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "net" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "github.com/Nwflower/reims-go/internal/control" +) + +func pluginConnect(args []string) error { + if len(args) != 2 || strings.TrimSpace(args[0]) == "" || strings.TrimSpace(args[1]) == "" { + return errors.New("usage: reims-go plugin connect ") + } + pluginID, channel := strings.TrimSpace(args[0]), strings.TrimSpace(args[1]) + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + conn, err := control.Dial(ctx) + if err != nil { + if startErr := spawnWindow([]string{"--background"}); startErr != nil { + return fmt.Errorf("connect to Reims-Go desktop: %w", err) + } + conn, err = waitForPluginControl(ctx) + if err != nil { + return fmt.Errorf("connect to Reims-Go desktop: %w", err) + } + } + defer conn.Close() + go func() { + <-ctx.Done() + _ = conn.Close() + }() + + encoder := json.NewEncoder(conn) + stdinDone := make(chan error, 1) + go func() { + defer conn.Close() + scanner := bufio.NewScanner(os.Stdin) + scanner.Buffer(make([]byte, 64*1024), control.MaxFrameBytes) + for scanner.Scan() { + message := append(json.RawMessage(nil), scanner.Bytes()...) + if !json.Valid(message) { + stdinDone <- errors.New("MCP input line is not valid JSON") + return + } + if err := encoder.Encode(control.Request{PluginID: pluginID, Channel: channel, Message: message}); err != nil { + stdinDone <- err + return + } + } + stdinDone <- scanner.Err() + _ = conn.Close() + }() + + responseScanner := bufio.NewScanner(conn) + responseScanner.Buffer(make([]byte, 64*1024), control.MaxFrameBytes) + for responseScanner.Scan() { + var response control.Response + if err := json.Unmarshal(responseScanner.Bytes(), &response); err != nil { + return fmt.Errorf("decode host control response: %w", err) + } + if response.Error != "" { + return errors.New(response.Error) + } + if len(response.Message) > 0 && string(response.Message) != "null" { + if _, err := os.Stdout.Write(response.Message); err != nil { + return err + } + if _, err := os.Stdout.Write([]byte{'\n'}); err != nil { + return err + } + } + } + if err := responseScanner.Err(); err != nil { + // Closing stdin closes the named pipe from the writer goroutine. The + // response reader can observe that close just before stdinDone is + // scheduled, so give the writer a short chance to report a clean EOF. + stdinTimer := time.NewTimer(250 * time.Millisecond) + defer stdinTimer.Stop() + select { + case stdinErr := <-stdinDone: + if stdinErr != nil && !errors.Is(stdinErr, context.Canceled) { + if ctx.Err() != nil { + return nil + } + return stdinErr + } + return nil + case <-stdinTimer.C: + case <-ctx.Done(): + return nil + } + if ctx.Err() != nil { + return nil + } + return err + } + return nil +} + +func waitForPluginControl(ctx context.Context) (net.Conn, error) { + deadline := time.NewTimer(15 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(150 * time.Millisecond) + defer ticker.Stop() + var lastErr error + for { + conn, err := control.Dial(ctx) + if err == nil { + return conn, nil + } + lastErr = err + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-deadline.C: + return nil, lastErr + case <-ticker.C: + } + } +} diff --git a/internal/console/manager.go b/internal/console/manager.go new file mode 100644 index 0000000..6b3e5c9 --- /dev/null +++ b/internal/console/manager.go @@ -0,0 +1,343 @@ +// Package console serializes host-owned QMP console operations per VM. +package console + +import ( + "context" + "errors" + "fmt" + "path/filepath" + "runtime" + "strings" + "sync" + "time" + + "github.com/Nwflower/reims-go/internal/qmp" +) + +// Manager arbitrates screen and input operations so concurrent host features +// never open competing QMP clients for the same VM. +type Manager struct { + mu sync.Mutex + locks map[string]*vmLock + dial func(context.Context, string) (qmpSession, error) +} + +type vmLock struct { + semaphore chan struct{} + users int + conn qmpSession +} + +type qmpSession interface { + qmp.Executor + qmp.QueryExecutor + Screendump(string) (string, error) + Close() error +} + +func NewManager() *Manager { + return &Manager{ + locks: make(map[string]*vmLock), + dial: func(ctx context.Context, vmDir string) (qmpSession, error) { + return qmp.Dial(ctx, "unix", qmp.SocketPath(vmDir)) + }, + } +} + +// Forget closes the cached QMP session for a VM. Lifecycle code calls this +// before stopping or deleting the VM so QEMU can release its single-client +// console socket. +func (m *Manager) Forget(ctx context.Context, vmDir string) error { + lock, release, err := m.acquire(ctx, vmDir) + if err != nil { + return err + } + defer release() + if lock.conn != nil { + err := lock.conn.Close() + lock.conn = nil + return err + } + return nil +} + +// Close releases every cached QMP session when the owning plugin is disposed. +func (m *Manager) Close() { + if m == nil { + return + } + m.mu.Lock() + dirs := make([]string, 0, len(m.locks)) + for dir := range m.locks { + dirs = append(dirs, dir) + } + m.mu.Unlock() + for _, dir := range dirs { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = m.Forget(ctx, dir) + cancel() + } +} + +// Screendump writes one PPM frame while holding the VM's console lock. +func (m *Manager) Screendump(ctx context.Context, vmDir, path string) (string, error) { + var format string + err := m.withConn(ctx, vmDir, func(conn qmpSession) error { + var err error + format, err = conn.Screendump(path) + return err + }) + return format, err +} + +// TypeText sends US-layout key strokes as one serialized console job. +func (m *Manager) TypeText(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) { + strokes, err := qmp.Strokes(text) + if err != nil { + return 0, err + } + if len(strokes) == 0 { + return 0, errors.New("nothing to type") + } + done := 0 + err = m.withConn(ctx, vmDir, func(conn qmpSession) error { + return qmp.TypeStrokes(ctx, conn, strokes, 20*time.Millisecond, 15*time.Millisecond, func(n int) { + done = n + if progress != nil { + progress(n, len(strokes)) + } + }) + }) + return done, err +} + +// SendPasteShortcut sends Command+V through the same exclusive console path. +func (m *Manager) SendPasteShortcut(ctx context.Context, vmDir string) error { + return m.withConn(ctx, vmDir, func(conn qmpSession) error { + return qmp.PressCombo(ctx, conn, 25*time.Millisecond, "v", "meta_l") + }) +} + +func (m *Manager) PointerAvailable(ctx context.Context, vmDir string) (bool, error) { + var available bool + err := m.withConn(ctx, vmDir, func(conn qmpSession) error { + mice, err := qmp.QueryMice(conn) + if err == nil { + available = qmp.HasCurrentAbsoluteMouse(mice) + } + return err + }) + return available, err +} + +func (m *Manager) MouseMove(ctx context.Context, vmDir string, x, y, width, height int) error { + return m.withConn(ctx, vmDir, func(conn qmpSession) error { + return qmp.MouseMove(conn, x, y, width, height) + }) +} + +func (m *Manager) MouseButton(ctx context.Context, vmDir, button string, down bool) error { + return m.withConn(ctx, vmDir, func(conn qmpSession) error { + return qmp.MouseButton(conn, button, down) + }) +} + +func (m *Manager) MouseClick(ctx context.Context, vmDir, button string) error { + return m.withConn(ctx, vmDir, func(conn qmpSession) error { + if err := qmp.MouseButton(conn, button, true); err != nil { + return err + } + released := false + defer func() { + if !released { + _ = qmp.MouseButton(conn, button, false) + } + }() + timer := time.NewTimer(50 * time.Millisecond) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + } + if err := qmp.MouseButton(conn, button, false); err != nil { + return err + } + released = true + return nil + }) +} + +func (m *Manager) MouseScroll(ctx context.Context, vmDir string, delta int, horizontal bool) error { + return m.withConn(ctx, vmDir, func(conn qmpSession) error { + return qmp.MouseScroll(conn, delta, horizontal) + }) +} + +func (m *Manager) PressKey(ctx context.Context, vmDir, key string, modifiers ...string) error { + key, err := normalizeKeyCode(key) + if err != nil { + return err + } + normalizedModifiers := make([]string, len(modifiers)) + for i, modifier := range modifiers { + normalizedModifiers[i], err = normalizeModifier(modifier) + if err != nil { + return err + } + } + return m.withConn(ctx, vmDir, func(conn qmpSession) error { + return qmp.PressCombo(ctx, conn, 25*time.Millisecond, key, normalizedModifiers...) + }) +} + +func normalizeKeyCode(key string) (string, error) { + if key == " " { + return "spc", nil + } + code := strings.ToLower(strings.TrimSpace(key)) + switch code { + case "space": + code = "spc" + case "escape": + code = "esc" + case "enter", "return": + code = "ret" + case "pageup": + code = "page_up" + case "pagedown": + code = "page_down" + } + if code == "" { + return "", errors.New("key is required") + } + for _, r := range code { + if (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '_' { + return "", fmt.Errorf("unsupported key code %q", key) + } + } + return code, nil +} + +func normalizeModifier(modifier string) (string, error) { + code := strings.ToLower(strings.TrimSpace(modifier)) + switch code { + case "cmd", "command", "meta", "super": + code = "meta_l" + case "ctrl", "control": + code = "ctrl" + case "option": + code = "alt" + } + switch code { + case "shift", "shift_r", "ctrl", "ctrl_r", "alt", "alt_r", "meta_l", "meta_r": + return code, nil + default: + return "", fmt.Errorf("unsupported key modifier %q", modifier) + } +} + +func (m *Manager) withConn(ctx context.Context, vmDir string, operation func(qmpSession) error) error { + if operation == nil { + return errors.New("console operation is unavailable") + } + lock, release, err := m.acquire(ctx, vmDir) + if err != nil { + return err + } + defer release() + if lock.conn == nil { + dial := m.dial + if dial == nil { + dial = func(ctx context.Context, vmDir string) (qmpSession, error) { + return qmp.Dial(ctx, "unix", qmp.SocketPath(vmDir)) + } + } + conn, err := dial(ctx, vmDir) + if err != nil { + return err + } + lock.conn = conn + } + if err := operation(lock.conn); err != nil { + _ = lock.conn.Close() + lock.conn = nil + return err + } + return nil +} + +func (m *Manager) withVM(ctx context.Context, vmDir string, operation func() error) error { + if operation == nil { + return errors.New("console operation is unavailable") + } + _, release, err := m.acquire(ctx, vmDir) + if err != nil { + return err + } + defer release() + return operation() +} + +func (m *Manager) acquire(ctx context.Context, vmDir string) (*vmLock, func(), error) { + if m == nil { + return nil, nil, errors.New("console manager is unavailable") + } + if ctx == nil { + return nil, nil, errors.New("console context is unavailable") + } + key, err := lockKey(vmDir) + if err != nil { + return nil, nil, err + } + + m.mu.Lock() + if m.locks == nil { + m.locks = make(map[string]*vmLock) + } + lock := m.locks[key] + if lock == nil { + lock = &vmLock{semaphore: make(chan struct{}, 1)} + m.locks[key] = lock + } + lock.users++ + m.mu.Unlock() + + select { + case lock.semaphore <- struct{}{}: + var once sync.Once + return lock, func() { + once.Do(func() { + <-lock.semaphore + m.release(key, lock) + }) + }, nil + case <-ctx.Done(): + m.release(key, lock) + return nil, nil, ctx.Err() + } +} + +func (m *Manager) release(key string, lock *vmLock) { + m.mu.Lock() + defer m.mu.Unlock() + lock.users-- + if lock.users == 0 && lock.conn == nil && m.locks[key] == lock { + delete(m.locks, key) + } +} + +func lockKey(vmDir string) (string, error) { + if strings.TrimSpace(vmDir) == "" { + return "", errors.New("VM directory is unavailable") + } + abs, err := filepath.Abs(vmDir) + if err != nil { + return "", fmt.Errorf("resolve VM directory: %w", err) + } + key := filepath.Clean(abs) + if runtime.GOOS == "windows" { + key = strings.ToLower(key) + } + return key, nil +} diff --git a/internal/control/control.go b/internal/control/control.go new file mode 100644 index 0000000..bcd1f7a --- /dev/null +++ b/internal/control/control.go @@ -0,0 +1,38 @@ +package control + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" +) + +const MaxFrameBytes = 8 << 20 + +type Request struct { + PluginID string `json:"plugin_id"` + Channel string `json:"channel"` + Message json.RawMessage `json:"message"` +} + +type Response struct { + Message json.RawMessage `json:"message,omitempty"` + Error string `json:"error,omitempty"` +} + +type Handler func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) + +// PipeName gives the desktop process and its CLI clients a deterministic +// endpoint scoped to this installation path and Windows user. +func PipeName() string { + exe, err := os.Executable() + if err != nil { + exe = "reims-go" + } + identity := filepath.Clean(exe) + sum := sha256.Sum256([]byte(identity)) + userScope := currentUserScope() + return `\\.\pipe\reims-go-control-` + hex.EncodeToString(sum[:8]) + "-" + userScope +} diff --git a/internal/control/control_other.go b/internal/control/control_other.go new file mode 100644 index 0000000..79badc1 --- /dev/null +++ b/internal/control/control_other.go @@ -0,0 +1,27 @@ +//go:build !windows + +package control + +import ( + "context" + "errors" + "net" +) + +type Server struct{} + +func currentUserScope() string { return "unsupported" } + +func Listen(Handler) (*Server, error) { + return nil, errors.ErrUnsupported +} + +func ListenAt(string, Handler) (*Server, error) { + return nil, errors.ErrUnsupported +} + +func Dial(context.Context) (net.Conn, error) { + return nil, errors.ErrUnsupported +} + +func (*Server) Close() error { return nil } diff --git a/internal/control/control_windows.go b/internal/control/control_windows.go new file mode 100644 index 0000000..632d4df --- /dev/null +++ b/internal/control/control_windows.go @@ -0,0 +1,165 @@ +//go:build windows + +package control + +import ( + "bufio" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net" + "sync" + + "github.com/Microsoft/go-winio" + "golang.org/x/sys/windows" +) + +func currentUserScope() string { + token := windows.GetCurrentProcessToken() + user, err := token.GetTokenUser() + if err != nil { + return "unknown" + } + sum := sha256.Sum256([]byte(user.User.Sid.String())) + return hex.EncodeToString(sum[:8]) +} + +type Server struct { + listener net.Listener + handler Handler + cancel context.CancelFunc + + mu sync.Mutex + conns map[net.Conn]struct{} + wg sync.WaitGroup +} + +func Listen(handler Handler) (*Server, error) { + return ListenAt(PipeName(), handler) +} + +func ListenAt(pipeName string, handler Handler) (*Server, error) { + if handler == nil { + return nil, errors.New("control handler is required") + } + token := windows.GetCurrentProcessToken() + user, err := token.GetTokenUser() + if err != nil { + return nil, fmt.Errorf("read current user SID: %w", err) + } + descriptor := "D:P(A;;GA;;;" + user.User.Sid.String() + ")" + listener, err := winio.ListenPipe(pipeName, &winio.PipeConfig{ + SecurityDescriptor: descriptor, + InputBufferSize: 64 * 1024, + OutputBufferSize: 64 * 1024, + }) + if err != nil { + return nil, fmt.Errorf("listen on the Reims-Go control pipe: %w", err) + } + ctx, cancel := context.WithCancel(context.Background()) + s := &Server{listener: listener, handler: handler, cancel: cancel, conns: make(map[net.Conn]struct{})} + s.wg.Add(1) + go s.acceptLoop(ctx) + return s, nil +} + +func Dial(ctx context.Context) (net.Conn, error) { + return winio.DialPipeContext(ctx, PipeName()) +} + +func (s *Server) acceptLoop(ctx context.Context) { + defer s.wg.Done() + for { + conn, err := s.listener.Accept() + if err != nil { + select { + case <-ctx.Done(): + return + default: + } + return + } + s.mu.Lock() + s.conns[conn] = struct{}{} + s.wg.Add(1) + s.mu.Unlock() + go s.serveConn(ctx, conn) + } +} + +func (s *Server) serveConn(serverCtx context.Context, conn net.Conn) { + defer s.wg.Done() + defer func() { + s.mu.Lock() + delete(s.conns, conn) + s.mu.Unlock() + _ = conn.Close() + }() + + scanner := bufio.NewScanner(conn) + scanner.Buffer(make([]byte, 64*1024), MaxFrameBytes) + writer := bufio.NewWriter(conn) + for scanner.Scan() { + var req Request + if err := json.Unmarshal(scanner.Bytes(), &req); err != nil { + if writeErr := writeResponse(writer, Response{Error: "invalid control request"}); writeErr != nil { + return + } + continue + } + if req.PluginID == "" || req.Channel == "" || len(req.Message) == 0 || !json.Valid(req.Message) { + if err := writeResponse(writer, Response{Error: "plugin, channel and valid JSON message are required"}); err != nil { + return + } + continue + } + result, err := s.handler(serverCtx, req.PluginID, req.Channel, req.Message) + response := Response{Message: result} + if err != nil { + response = Response{Error: err.Error()} + } + if err := writeResponse(writer, response); err != nil { + return + } + select { + case <-serverCtx.Done(): + return + default: + } + } +} + +func writeResponse(writer *bufio.Writer, response Response) error { + frame, err := json.Marshal(response) + if err != nil { + return err + } + if len(frame) > MaxFrameBytes { + return errors.New("control response exceeds frame limit") + } + if _, err := writer.Write(frame); err != nil { + return err + } + if err := writer.WriteByte('\n'); err != nil { + return err + } + return writer.Flush() +} + +func (s *Server) Close() error { + if s == nil { + return nil + } + s.cancel() + listenerErr := s.listener.Close() + s.mu.Lock() + for conn := range s.conns { + _ = conn.Close() + } + s.mu.Unlock() + s.wg.Wait() + return listenerErr +} diff --git a/internal/plugin/builtin/builtin.go b/internal/plugin/builtin/builtin.go index a07d203..ec2854e 100644 --- a/internal/plugin/builtin/builtin.go +++ b/internal/plugin/builtin/builtin.go @@ -30,12 +30,14 @@ const ( IDGuestTools = "builtin.bridge.guest-tools" IDClipboard = "builtin.bridge.clipboard" IDInput = "builtin.input" + IDComputerUse = "builtin.computer-use" ) // Service names provided by builtin extensions. const ( ServiceGuestToolsTransport = "guest-tools.transport" ServiceHostInput = "host.input" + ServiceComputerUse = "computer-use.console" ) // HostCallbacks connects builtin extensions to host runtime services without @@ -86,6 +88,7 @@ func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id strin defGuestTools(ver, cb, desiredFn), defClipboard(ver, cb, desiredFn), defInput(ver, cb, desiredFn), + defComputerUse(ver, desiredFn), defDownloaderParallel(ver, cb, desiredFn), } for _, d := range defs { diff --git a/internal/plugin/builtin/computer_use.go b/internal/plugin/builtin/computer_use.go new file mode 100644 index 0000000..779ea95 --- /dev/null +++ b/internal/plugin/builtin/computer_use.go @@ -0,0 +1,66 @@ +package builtin + +import ( + "context" + + "github.com/Nwflower/reims-go/internal/console" + "github.com/Nwflower/reims-go/internal/plugin" +) + +// ComputerUseService is the host-owned console surface exposed to in-process +// features and permission-checked Sidecar Host API handlers. +type ComputerUseService interface { + Screendump(ctx context.Context, vmDir, path string) (string, error) + TypeText(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) + Forget(ctx context.Context, vmDir string) error + Close() + SendPasteShortcut(ctx context.Context, vmDir string) error + PointerAvailable(ctx context.Context, vmDir string) (bool, error) + MouseMove(ctx context.Context, vmDir string, x, y, width, height int) error + MouseButton(ctx context.Context, vmDir, button string, down bool) error + MouseClick(ctx context.Context, vmDir, button string) error + MouseScroll(ctx context.Context, vmDir string, delta int, horizontal bool) error + PressKey(ctx context.Context, vmDir, key string, modifiers ...string) error +} + +func defComputerUse(ver string, desiredFn func(string, bool) bool) plugin.PluginDef { + return plugin.PluginDef{ + Manifest: plugin.Manifest{ + Schema: 1, + ID: IDComputerUse, + Version: ver, + Name: plugin.LocalizedText{ZhCN: "虚拟机交互", EnUS: "Computer Use"}, + Description: plugin.LocalizedText{ + ZhCN: "通过宿主控制台串行访问虚拟机屏幕、鼠标和键盘", + EnUS: "Serializes host console access to VM screens, pointers, and keyboards", + }, + Publisher: "Reims-Go", + License: "Apache-2.0", + Provides: []plugin.ServiceProvision{{Service: ServiceComputerUse, Version: "1.0.0"}}, + Permissions: []string{"vm:screen", "qmp:write"}, + DefaultEnabled: true, + }, + Source: plugin.SourceBuiltin, + Trust: plugin.TrustOfficial, + Desired: desiredFn(IDComputerUse, true), + Activate: func(_ context.Context, sc *plugin.Scope) error { + manager := console.NewManager() + sc.Provide(ServiceComputerUse, "1.0.0", manager) + sc.OnDispose(manager.Close) + for _, event := range []string{plugin.EventVMBeforeStop, plugin.EventVMDeleted} { + sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{ + Event: event, + Builtin: true, + Handler: func(ctx context.Context, raw any) (any, error) { + payload, ok := raw.(plugin.VMEventPayload) + if !ok || payload.VMDir == "" { + return nil, nil + } + return nil, manager.Forget(ctx, payload.VMDir) + }, + }) + } + return nil + }, + } +} diff --git a/internal/plugin/contract.go b/internal/plugin/contract.go index d8dbbf2..e359876 100644 --- a/internal/plugin/contract.go +++ b/internal/plugin/contract.go @@ -32,6 +32,7 @@ const ( // ContributionCatalog lists every `contributes` key (its JSON name). var ContributionCatalog = map[string]ContractStatus{ "themes": ContractStable, + "channels": ContractStable, "uiScripts": ContractExperimental, // theme.uiScript is the implemented path "locales": ContractStable, "inputFilters": ContractStable, @@ -263,6 +264,23 @@ var reContributionID = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`) // catalogs: unknown slots, locations, layout values or icon names are errors; // experimental ones are accepted and reported by ContractFindings. func validateUIContract(m Manifest) error { + channelIDs := make(map[string]bool, len(m.Contributes.Channels)) + for _, channel := range m.Contributes.Channels { + if channel.ID != strings.TrimSpace(channel.ID) || !reContributionID.MatchString(channel.ID) { + return fmt.Errorf("invalid channel id %q", channel.ID) + } + if channelIDs[channel.ID] { + return fmt.Errorf("duplicate channel id %q", channel.ID) + } + channelIDs[channel.ID] = true + if channel.Framing != "jsonl" { + return fmt.Errorf("channel %q uses unsupported framing %q", channel.ID, channel.Framing) + } + } + if len(channelIDs) > 0 && strings.TrimSpace(m.Entry.Sidecar) == "" { + return fmt.Errorf("plugin channels require a Sidecar entry") + } + checkSlot := func(what, id, slot, kind string) error { spec, ok := UISlotCatalog[slot] if !ok { diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index 822a676..87ed7fe 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -20,6 +20,9 @@ import ( // and supervisor without importing internal/driver into internal/plugin. type SidecarDriverFactory func(contrib GuestDriverContribution, sup *SidecarSupervisor) any +// HostHandlerFactory adds host-owned RPC handlers to each Sidecar. +type HostHandlerFactory func(pluginID string) map[string]RPCRequestHandler + // ManagerOptions configures the high-level Plugin Manager. type ManagerOptions struct { DataRoot string @@ -30,6 +33,7 @@ type ManagerOptions struct { Logger func(source, line string) LocaleFn func() i18n.Locale SidecarDriverFactory SidecarDriverFactory + HostHandlers HostHandlerFactory OnSettingsChanged func(pluginID, vmName string) } @@ -49,12 +53,12 @@ type ActiveThemePayload struct { // Manager coordinates Registry, StateStore, package installation, safe mode, // settings, themes, AssetServer, Broker, and L3 Sidecar supervisors. type Manager struct { - opts ManagerOptions - layout PluginsLayout - store *StateStore - registry *Registry - broker *Broker - assets *AssetServer + opts ManagerOptions + layout PluginsLayout + store *StateStore + registry *Registry + broker *Broker + assets *AssetServer mu sync.RWMutex state *StateFile @@ -115,12 +119,61 @@ func NewManager(opts ManagerOptions) (*Manager, error) { return m, nil } -func (m *Manager) Registry() *Registry { return m.registry } -func (m *Manager) Broker() *Broker { return m.broker } -func (m *Manager) Assets() *AssetServer { return m.assets } -func (m *Manager) Layout() PluginsLayout { return m.layout } -func (m *Manager) SafeMode() bool { return m.safeMode } -func (m *Manager) CrashDetected() bool { return m.crashDetected } +func (m *Manager) Registry() *Registry { return m.registry } +func (m *Manager) Broker() *Broker { return m.broker } +func (m *Manager) Assets() *AssetServer { return m.assets } +func (m *Manager) Layout() PluginsLayout { return m.layout } +func (m *Manager) SafeMode() bool { return m.safeMode } +func (m *Manager) CrashDetected() bool { return m.crashDetected } + +// ChannelMessage forwards one JSON line to a declared, active Sidecar channel. +// Channel payloads are never written to the host audit log. +func (m *Manager) ChannelMessage(ctx context.Context, pluginID, channelID string, message json.RawMessage) (json.RawMessage, error) { + if m == nil || m.registry == nil { + return nil, errors.New("plugin manager is unavailable") + } + if len(message) == 0 || len(message) > maxRPCFrameBytes || !json.Valid(message) { + return nil, errors.New("channel message must be valid JSON within the frame limit") + } + manifest, ok := m.registry.ManifestOf(pluginID) + if !ok { + return nil, fmt.Errorf("plugin %q is not installed", pluginID) + } + declared := false + for _, channel := range manifest.Contributes.Channels { + if channel.ID == channelID && channel.Framing == "jsonl" { + declared = true + break + } + } + if !declared { + return nil, fmt.Errorf("plugin %q does not declare JSONL channel %q", pluginID, channelID) + } + if !m.registry.IsActive(pluginID) { + return nil, fmt.Errorf("plugin %q is not enabled", pluginID) + } + if ctx == nil { + ctx = context.Background() + } + m.mu.RLock() + supervisor := m.supervisors[pluginID] + m.mu.RUnlock() + if supervisor == nil { + return nil, fmt.Errorf("plugin %q channel is unavailable", pluginID) + } + var response struct { + Message json.RawMessage `json:"message"` + } + err := supervisor.Call(ctx, "channel/"+channelID+"/message", map[string]json.RawMessage{"message": message}, &response) + if err != nil { + return nil, err + } + if len(response.Message) > maxRPCFrameBytes || (len(response.Message) > 0 && string(response.Message) != "null" && !json.Valid(response.Message)) { + return nil, errors.New("Sidecar returned an invalid channel message") + } + m.broker.Audit(pluginID, "CHANNEL_MESSAGE", channelID) + return response.Message, nil +} // DesiredFor returns whether pluginID should be enabled according to state.json, // falling back to defaultEnabled if no saved record exists. @@ -329,6 +382,17 @@ func (m *Manager) buildSidecarActivator(man Manifest, exePath string, blockingAl "host/downloader.progress": dlHub.handleRPC, } } + if m.opts.HostHandlers != nil { + if extraHandlers == nil { + extraHandlers = make(map[string]RPCRequestHandler) + } + for method, handler := range m.opts.HostHandlers(pid) { + if _, exists := extraHandlers[method]; exists { + return fmt.Errorf("Sidecar Host API method %q is already registered", method) + } + extraHandlers[method] = handler + } + } sup := NewSidecarSupervisor(SidecarOptions{ PluginID: pid, ExePath: exePath, @@ -887,6 +951,27 @@ func (m *Manager) GetSettings(pluginID, vmName string, maskSecrets bool) map[str func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) error { info, hasInfo := m.registry.Info(pluginID) + prepared := make(map[string]any, len(values)) + for key, value := range values { + if hasInfo && info.Settings != nil { + if property, ok := info.Settings.Properties[key]; ok && property.Secret { + if value == "••••••••" { + continue + } + text, ok := value.(string) + if !ok { + return fmt.Errorf("secret setting %q must be a string", key) + } + protected, err := protectSettingSecret(text) + if err != nil { + return fmt.Errorf("protect secret setting %q: %w", key, err) + } + prepared[key] = protected + continue + } + } + prepared[key] = value + } m.mu.Lock() if m.state == nil { m.mu.Unlock() @@ -917,7 +1002,7 @@ func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) er if rec.AppSettings == nil { rec.AppSettings = map[string]any{} } - for k, v := range values { + for k, v := range prepared { if isSecretMask(k, v) { continue } @@ -930,7 +1015,7 @@ func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) er if rec.VMSettings[vmName] == nil { rec.VMSettings[vmName] = map[string]any{} } - for k, v := range values { + for k, v := range prepared { if isSecretMask(k, v) { continue } @@ -947,6 +1032,46 @@ func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) er return err } +// SecretSetting decrypts a DPAPI-protected setting only for host-owned use. +// The caller must never return the plaintext to a plugin or frontend. +func (m *Manager) SecretSetting(pluginID, vmName, key string) (string, error) { + info, ok := m.registry.Info(pluginID) + if !ok || info.Settings == nil { + return "", fmt.Errorf("plugin %q has no settings schema", pluginID) + } + property, ok := info.Settings.Properties[key] + if !ok || !property.Secret { + return "", fmt.Errorf("setting %q is not a secret", key) + } + m.mu.RLock() + if m.state == nil { + m.mu.RUnlock() + return "", m.stateNotLoadedErr() + } + values := map[string]any(nil) + if record := m.state.Plugins[pluginID]; record != nil { + if vmName == "" { + values = record.AppSettings + } else { + values = record.VMSettings[vmName] + } + } + text, _ := values[key].(string) + m.mu.RUnlock() + if text == "" { + return "", errors.New("secret setting is empty") + } + if strings.HasPrefix(text, protectedSecretPrefix) { + return unprotectSettingSecret(text) + } + // Versions before DPAPI protection stored secret settings as plain text. + // Re-save the legacy value through SetSettings so the next read is protected. + if err := m.SetSettings(pluginID, vmName, map[string]any{key: text}); err != nil { + return "", fmt.Errorf("migrate legacy secret setting %q: %w", key, err) + } + return text, nil +} + // SavedVMSettingsForPlugin returns a copy of all saved per-VM setting maps for pluginID. func (m *Manager) SavedVMSettingsForPlugin(pluginID string) map[string]map[string]any { m.mu.RLock() diff --git a/internal/plugin/package.go b/internal/plugin/package.go index c63b3fb..6be8ae3 100644 --- a/internal/plugin/package.go +++ b/internal/plugin/package.go @@ -1116,7 +1116,11 @@ func validateDiskContributions(m Manifest, rootDir string) error { } func safeJoin(root, rel string) (string, error) { - cleanRoot := filepath.Clean(root) + absRoot, err := filepath.Abs(root) + if err != nil { + return "", fmt.Errorf("resolve root path: %w", err) + } + cleanRoot := filepath.Clean(absRoot) joined := filepath.Clean(filepath.Join(cleanRoot, filepath.FromSlash(rel))) if !pathWithinRoot(cleanRoot, joined) { return "", fmt.Errorf("path traversal blocked: %q", rel) diff --git a/internal/plugin/risks.go b/internal/plugin/risks.go index e433693..c4b6af1 100644 --- a/internal/plugin/risks.go +++ b/internal/plugin/risks.go @@ -97,7 +97,7 @@ func addPermissionRisks(set map[string]bool, perm string) { set[RiskNetwork] = true case "fs:vm_dir", "fs:shared": set[RiskFiles] = true - case "vm:control", "qmp:write", "driver:vm", "runtime:provider", "process:spawn", "vm:intent": + case "vm:control", "vm:screen", "qmp:write", "driver:vm", "runtime:provider", "process:spawn", "vm:intent": set[RiskVM] = true case "host:clipboard": set[RiskClipboard] = true diff --git a/internal/plugin/scanner.go b/internal/plugin/scanner.go index 23cda94..be55b18 100644 --- a/internal/plugin/scanner.go +++ b/internal/plugin/scanner.go @@ -123,16 +123,16 @@ var ( reSVGJavascriptURI = regexp.MustCompile(`(?i)javascript\s*:`) reSVGForeignObject = regexp.MustCompile(`(?i)<\s*foreignobject\b`) - reJSWailsGo = regexp.MustCompile(`(?i)\b(?:window|globalThis|self|parent|top)\s*(?:\.\s*go\b|\[\s*['"]go['"]\s*\])`) - reJSWailsRuntime = regexp.MustCompile(`(?i)\b(?:window|globalThis|self|parent|top)\s*(?:\.\s*runtime\b|\[\s*['"]runtime['"]\s*\])`) - reJSEval = regexp.MustCompile(`\beval\s*\(`) - reJSNewFunction = regexp.MustCompile(`\bnew\s+Function\s*\(`) - reJSFunctionCall = regexp.MustCompile(`(?:^|[^.\w$])Function\s*\(`) - reJSDocCookie = regexp.MustCompile(`\bdocument\s*\.\s*cookie\b`) - reJSDocWrite = regexp.MustCompile(`\bdocument\s*\.\s*write(?:ln)?\s*\(`) - reJSScriptTag = regexp.MustCompile(`(?i)<\s*script\b`) - reJSCreateScript = regexp.MustCompile(`(?i)\bcreateElement\s*\(\s*['"]script['"]\s*\)`) - reJSNetworkCall = regexp.MustCompile(`\b(?:fetch\s*\(|XMLHttpRequest\b|WebSocket\b|EventSource\b|navigator\s*\.\s*sendBeacon\s*\()`) + reJSWailsGo = regexp.MustCompile(`(?i)\b(?:window|globalThis|self|parent|top)\s*(?:\.\s*go\b|\[\s*['"]go['"]\s*\])`) + reJSWailsRuntime = regexp.MustCompile(`(?i)\b(?:window|globalThis|self|parent|top)\s*(?:\.\s*runtime\b|\[\s*['"]runtime['"]\s*\])`) + reJSEval = regexp.MustCompile(`\beval\s*\(`) + reJSNewFunction = regexp.MustCompile(`\bnew\s+Function\s*\(`) + reJSFunctionCall = regexp.MustCompile(`(?:^|[^.\w$])Function\s*\(`) + reJSDocCookie = regexp.MustCompile(`\bdocument\s*\.\s*cookie\b`) + reJSDocWrite = regexp.MustCompile(`\bdocument\s*\.\s*write(?:ln)?\s*\(`) + reJSScriptTag = regexp.MustCompile(`(?i)<\s*script\b`) + reJSCreateScript = regexp.MustCompile(`(?i)\bcreateElement\s*\(\s*['"]script['"]\s*\)`) + reJSNetworkCall = regexp.MustCompile(`\b(?:fetch\s*\(|XMLHttpRequest\b|WebSocket\b|EventSource\b|navigator\s*\.\s*sendBeacon\s*\()`) ) // ScanArchive extracts archivePath into a temporary directory under tmpParentDir @@ -869,6 +869,9 @@ func describePermission(perm string) (LocalizedText, LocalizedText) { case "vm:control": return LocalizedText{ZhCN: "控制虚拟机启停", EnUS: "Control VM power state"}, LocalizedText{ZhCN: "可以启动、停止或重启你的虚拟机。", EnUS: "Can start, stop, or reboot your virtual machines."} + case "vm:screen": + return LocalizedText{ZhCN: "读取虚拟机屏幕", EnUS: "Read VM screen"}, + LocalizedText{ZhCN: "可截取运行中虚拟机的屏幕内容。", EnUS: "Can capture the screen of a running virtual machine."} case "qmp:write": return LocalizedText{ZhCN: "向 QEMU 发送写命令", EnUS: "Send QEMU QMP write commands"}, LocalizedText{ZhCN: "可向运行中的 QEMU 虚拟机发送控制指令。", EnUS: "Can send mutating control commands to running QEMU VMs."} diff --git a/internal/plugin/secret.go b/internal/plugin/secret.go new file mode 100644 index 0000000..04013b0 --- /dev/null +++ b/internal/plugin/secret.go @@ -0,0 +1,38 @@ +package plugin + +import ( + "encoding/base64" + "errors" + "strings" +) + +const protectedSecretPrefix = "dpapi:v1:" + +var ErrSecretNotProtected = errors.New("stored secret is not protected") + +func protectSettingSecret(value string) (string, error) { + if value == "" || strings.HasPrefix(value, protectedSecretPrefix) { + return value, nil + } + protected, err := protectSecretBytes([]byte(value)) + if err != nil { + return "", err + } + return protectedSecretPrefix + base64.StdEncoding.EncodeToString(protected), nil +} + +func unprotectSettingSecret(value string) (string, error) { + if !strings.HasPrefix(value, protectedSecretPrefix) { + return "", ErrSecretNotProtected + } + encoded := strings.TrimPrefix(value, protectedSecretPrefix) + protected, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return "", err + } + plain, err := unprotectSecretBytes(protected) + if err != nil { + return "", err + } + return string(plain), nil +} diff --git a/internal/plugin/secret_other.go b/internal/plugin/secret_other.go new file mode 100644 index 0000000..9e66b3b --- /dev/null +++ b/internal/plugin/secret_other.go @@ -0,0 +1,13 @@ +//go:build !windows + +package plugin + +import "errors" + +func protectSecretBytes([]byte) ([]byte, error) { + return nil, errors.New("secret settings require Windows DPAPI") +} + +func unprotectSecretBytes([]byte) ([]byte, error) { + return nil, errors.New("secret settings require Windows DPAPI") +} diff --git a/internal/plugin/secret_windows.go b/internal/plugin/secret_windows.go new file mode 100644 index 0000000..d7653b2 --- /dev/null +++ b/internal/plugin/secret_windows.go @@ -0,0 +1,42 @@ +//go:build windows + +package plugin + +import ( + "errors" + "unsafe" + + "golang.org/x/sys/windows" +) + +func protectSecretBytes(plain []byte) ([]byte, error) { + input := windows.DataBlob{Size: uint32(len(plain))} + if len(plain) > 0 { + input.Data = &plain[0] + } + var output windows.DataBlob + if err := windows.CryptProtectData(&input, nil, nil, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &output); err != nil { + return nil, err + } + defer windows.LocalFree(windows.Handle(unsafe.Pointer(output.Data))) + if output.Size == 0 || output.Data == nil { + return nil, errors.New("DPAPI returned an empty protected value") + } + return append([]byte(nil), unsafe.Slice(output.Data, output.Size)...), nil +} + +func unprotectSecretBytes(ciphertext []byte) ([]byte, error) { + input := windows.DataBlob{Size: uint32(len(ciphertext))} + if len(ciphertext) > 0 { + input.Data = &ciphertext[0] + } + var output windows.DataBlob + if err := windows.CryptUnprotectData(&input, nil, nil, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &output); err != nil { + return nil, err + } + defer windows.LocalFree(windows.Handle(unsafe.Pointer(output.Data))) + if output.Size == 0 || output.Data == nil { + return nil, errors.New("DPAPI returned an empty plaintext value") + } + return append([]byte(nil), unsafe.Slice(output.Data, output.Size)...), nil +} diff --git a/internal/plugin/types.go b/internal/plugin/types.go index b586f93..71ead56 100644 --- a/internal/plugin/types.go +++ b/internal/plugin/types.go @@ -15,7 +15,7 @@ import ( const ( // PluginAPIVersion is the host plugin API contract version (SemVer). - PluginAPIVersion = "1.0.0" + PluginAPIVersion = "1.1.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.0.0" @@ -304,6 +304,7 @@ func (m Manifest) InferTier(isBuiltin bool) Tier { // Contributes enumerates all extension-point declarations in plugin.json (§4.2). type Contributes struct { Themes []ThemeContribution `json:"themes,omitempty"` + Channels []ChannelContribution `json:"channels,omitempty"` UIScripts []UIScriptContribution `json:"uiScripts,omitempty"` Locales []LocaleContribution `json:"locales,omitempty"` InputFilters []InputFilterContribution `json:"inputFilters,omitempty"` @@ -326,6 +327,14 @@ type Contributes struct { Diagnostics []DiagnosticsContribution `json:"diagnostics,omitempty"` } +// ChannelContribution declares a framed message channel exposed through +// `reims-go plugin connect`. The host validates the declaration before it +// forwards any client data to the Sidecar. +type ChannelContribution struct { + ID string `json:"id"` + Framing string `json:"framing"` +} + // DownloaderContribution registers a pluggable file/region downloader (Builtin or L3 Sidecar). type DownloaderContribution struct { ID string `json:"id"` @@ -336,25 +345,25 @@ type DownloaderContribution struct { // ThemeContribution describes a L1 token/style theme or tier-3 interactive theme (§5.1). type ThemeContribution struct { - ID string `json:"id"` - Name LocalizedText `json:"name"` - Description LocalizedText `json:"description,omitempty"` - Appearance string `json:"appearance,omitempty"` // "light" | "dark" | "both" - Seeds map[string]string `json:"seeds,omitempty"` - Schemes []ThemeScheme `json:"schemes,omitempty"` - DeriveRules []TokenDeriveRule `json:"deriveRules,omitempty"` - Tokens map[string]string `json:"tokens,omitempty"` - DarkTokens map[string]string `json:"darkTokens,omitempty"` - Fonts []ThemeFont `json:"fonts,omitempty"` - Icons map[string]string `json:"icons,omitempty"` - BrandMark string `json:"brandMark,omitempty"` - Background string `json:"background,omitempty"` - Sounds map[string]string `json:"sounds,omitempty"` - Stylesheet string `json:"stylesheet,omitempty"` // relative path inside package - Decorations []ThemeDecoration `json:"decorations,omitempty"` - UIScript string `json:"uiScript,omitempty"` // requires ui:script - Layout *ThemeLayout `json:"layout,omitempty"` - PluginID string `json:"pluginId,omitempty"` + ID string `json:"id"` + Name LocalizedText `json:"name"` + Description LocalizedText `json:"description,omitempty"` + Appearance string `json:"appearance,omitempty"` // "light" | "dark" | "both" + Seeds map[string]string `json:"seeds,omitempty"` + Schemes []ThemeScheme `json:"schemes,omitempty"` + DeriveRules []TokenDeriveRule `json:"deriveRules,omitempty"` + Tokens map[string]string `json:"tokens,omitempty"` + DarkTokens map[string]string `json:"darkTokens,omitempty"` + Fonts []ThemeFont `json:"fonts,omitempty"` + Icons map[string]string `json:"icons,omitempty"` + BrandMark string `json:"brandMark,omitempty"` + Background string `json:"background,omitempty"` + Sounds map[string]string `json:"sounds,omitempty"` + Stylesheet string `json:"stylesheet,omitempty"` // relative path inside package + Decorations []ThemeDecoration `json:"decorations,omitempty"` + UIScript string `json:"uiScript,omitempty"` // requires ui:script + Layout *ThemeLayout `json:"layout,omitempty"` + PluginID string `json:"pluginId,omitempty"` } // ThemeScheme is a named seed-color preset inside a theme pack. @@ -387,12 +396,12 @@ type ThemeFont struct { // ThemeDecoration defines a declarative state-driven sprite/frame decoration anchored to a slot. type ThemeDecoration struct { - ID string `json:"id"` - Slot string `json:"slot"` // e.g. "sidebar.footer", "vm.preview.br" - Width int `json:"width,omitempty"` - Height int `json:"height,omitempty"` - Alt LocalizedText `json:"alt,omitempty"` - States []ThemeDecorationState `json:"states"` + ID string `json:"id"` + Slot string `json:"slot"` // e.g. "sidebar.footer", "vm.preview.br" + Width int `json:"width,omitempty"` + Height int `json:"height,omitempty"` + Alt LocalizedText `json:"alt,omitempty"` + States []ThemeDecorationState `json:"states"` } // ThemeDecorationState maps a state expression (e.g. "vmState==running") to a static/animated asset. @@ -469,16 +478,16 @@ type ResolvedLocalePack struct { // InputFilterContribution declares a host-side input filter rule (§5.4). type InputFilterContribution struct { - ID string `json:"id"` - Event string `json:"event"` // "mouse_wheel" - Axis string `json:"axis,omitempty"` // "vertical" | "horizontal" | "both" - Transform string `json:"transform"` // "invert" - Scope string `json:"scope"` // "vm_foreground" - SettingKey string `json:"settingKey,omitempty"` // VM-scoped boolean key - HorizKey string `json:"horizontalKey,omitempty"` - VertKey string `json:"verticalKey,omitempty"` - Name LocalizedText `json:"name,omitempty"` - PluginID string `json:"pluginId,omitempty"` + ID string `json:"id"` + Event string `json:"event"` // "mouse_wheel" + Axis string `json:"axis,omitempty"` // "vertical" | "horizontal" | "both" + Transform string `json:"transform"` // "invert" + Scope string `json:"scope"` // "vm_foreground" + SettingKey string `json:"settingKey,omitempty"` // VM-scoped boolean key + HorizKey string `json:"horizontalKey,omitempty"` + VertKey string `json:"verticalKey,omitempty"` + Name LocalizedText `json:"name,omitempty"` + PluginID string `json:"pluginId,omitempty"` } // VMTemplateContribution contributes a VM creation preset. @@ -493,34 +502,34 @@ type VMTemplateContribution struct { // RuntimeSourceContribution contributes an additional runtime download mirror/source. type RuntimeSourceContribution struct { - ID string `json:"id"` - Kind string `json:"kind"` - Name LocalizedText `json:"name"` - IndexURL string `json:"indexUrl"` - Channel string `json:"channel,omitempty"` - License string `json:"license,omitempty"` - Publisher string `json:"publisher,omitempty"` - PluginID string `json:"pluginId,omitempty"` + ID string `json:"id"` + Kind string `json:"kind"` + Name LocalizedText `json:"name"` + IndexURL string `json:"indexUrl"` + Channel string `json:"channel,omitempty"` + License string `json:"license,omitempty"` + Publisher string `json:"publisher,omitempty"` + PluginID string `json:"pluginId,omitempty"` } // RuntimeKindContribution registers a new runtime kind (e.g. "qemu-ovmf"). type RuntimeKindContribution struct { - Kind string `json:"kind"` - Name LocalizedText `json:"name"` - Description LocalizedText `json:"description,omitempty"` - RequiredFiles []string `json:"requiredFiles,omitempty"` - DefaultAPIVer string `json:"defaultApiVersion,omitempty"` - PluginID string `json:"pluginId,omitempty"` + Kind string `json:"kind"` + Name LocalizedText `json:"name"` + Description LocalizedText `json:"description,omitempty"` + RequiredFiles []string `json:"requiredFiles,omitempty"` + DefaultAPIVer string `json:"defaultApiVersion,omitempty"` + PluginID string `json:"pluginId,omitempty"` } // RuntimePackContribution declares an archive/binary runtime package inside a plugin. type RuntimePackContribution struct { - Kind string `json:"kind"` - Version string `json:"version"` - RuntimeAPI string `json:"runtimeApi"` + Kind string `json:"kind"` + Version string `json:"version"` + RuntimeAPI string `json:"runtimeApi"` Capabilities []string `json:"capabilities,omitempty"` - Dir string `json:"dir,omitempty"` - PluginID string `json:"pluginId,omitempty"` + Dir string `json:"dir,omitempty"` + PluginID string `json:"pluginId,omitempty"` } // GuestDriverContribution declares a guest VM driver provided by an L3 Sidecar or builtin. @@ -649,28 +658,28 @@ type DiagnosticsContribution struct { // SettingsSchema is a JSON Schema subset with Reims-Go extensions (§6.2). type SettingsSchema struct { - Title LocalizedText `json:"title,omitempty"` - Group string `json:"x-group,omitempty"` // e.g. "keyboard", "collaboration" - Scope string `json:"x-scope,omitempty"` // "app" | "vm" - Properties map[string]SettingProperty `json:"properties"` - Order []string `json:"x-order,omitempty"` + Title LocalizedText `json:"title,omitempty"` + Group string `json:"x-group,omitempty"` // e.g. "keyboard", "collaboration" + Scope string `json:"x-scope,omitempty"` // "app" | "vm" + Properties map[string]SettingProperty `json:"properties"` + Order []string `json:"x-order,omitempty"` } // SettingProperty describes one configurable field. type SettingProperty struct { - Type string `json:"type"` // "boolean" | "string" | "number" | "integer" - Title LocalizedText `json:"title"` - Description LocalizedText `json:"description,omitempty"` - Default any `json:"default,omitempty"` - Enum []string `json:"enum,omitempty"` - EnumLabels []LocalizedText `json:"x-enumLabels,omitempty"` - Minimum *float64 `json:"minimum,omitempty"` - Maximum *float64 `json:"maximum,omitempty"` - Secret bool `json:"x-secret,omitempty"` - Effect string `json:"x-effect,omitempty"` // "immediate" | "next_start" - Scope string `json:"x-scope,omitempty"` // "app" | "vm" - Group string `json:"x-group,omitempty"` // VM settings section id - Required bool `json:"required,omitempty"` + Type string `json:"type"` // "boolean" | "string" | "number" | "integer" + Title LocalizedText `json:"title"` + Description LocalizedText `json:"description,omitempty"` + Default any `json:"default,omitempty"` + Enum []string `json:"enum,omitempty"` + EnumLabels []LocalizedText `json:"x-enumLabels,omitempty"` + Minimum *float64 `json:"minimum,omitempty"` + Maximum *float64 `json:"maximum,omitempty"` + Secret bool `json:"x-secret,omitempty"` + Effect string `json:"x-effect,omitempty"` // "immediate" | "next_start" + Scope string `json:"x-scope,omitempty"` // "app" | "vm" + Group string `json:"x-group,omitempty"` // VM settings section id + Required bool `json:"required,omitempty"` } // PermissionLevel categorizes permission risk (§7.1). @@ -697,7 +706,7 @@ func ClassifyPermission(perm string) PermissionLevel { return PermLow case "vm:intent", "runtime:source", "ui:slot", "input:filter", "fs:pick": return PermMedium - case "driver:vm", "runtime:provider", "process:spawn", "vm:control", + case "driver:vm", "runtime:provider", "process:spawn", "vm:control", "vm:screen", "qmp:write", "fs:vm_dir", "fs:shared", "host:clipboard", "ui:script": return PermHigh } diff --git a/internal/qmp/pointer.go b/internal/qmp/pointer.go new file mode 100644 index 0000000..671144a --- /dev/null +++ b/internal/qmp/pointer.go @@ -0,0 +1,162 @@ +package qmp + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "strings" +) + +// QueryExecutor is the read-only part of a QMP session used by mouse probing. +type QueryExecutor interface { + Query(command string, args any) (json.RawMessage, error) +} + +// MouseInfo describes a QEMU input device returned by query-mice. +type MouseInfo struct { + Name string `json:"name"` + Index int `json:"index"` + Current bool `json:"current"` + Absolute bool `json:"absolute"` +} + +// QueryMice returns the guest input devices currently exposed by QEMU. +func QueryMice(q QueryExecutor) ([]MouseInfo, error) { + if q == nil { + return nil, errors.New("QMP session is unavailable") + } + data, err := q.Query("query-mice", nil) + if err != nil { + return nil, err + } + var mice []MouseInfo + if err := json.Unmarshal(data, &mice); err != nil { + return nil, fmt.Errorf("decode QMP query-mice: %w", err) + } + return mice, nil +} + +// HasCurrentAbsoluteMouse reports whether QEMU selected an absolute pointer. +func HasCurrentAbsoluteMouse(mice []MouseInfo) bool { + for _, mouse := range mice { + if mouse.Current && mouse.Absolute { + return true + } + } + return false +} + +// MouseMove converts framebuffer coordinates to QEMU's 0..32767 absolute axes. +func MouseMove(q Executor, x, y, width, height int) error { + if q == nil { + return errors.New("QMP session is unavailable") + } + ax, err := absoluteAxis(x, width) + if err != nil { + return fmt.Errorf("mouse x coordinate: %w", err) + } + ay, err := absoluteAxis(y, height) + if err != nil { + return fmt.Errorf("mouse y coordinate: %w", err) + } + return q.Execute("input-send-event", map[string]any{"events": []any{ + map[string]any{"type": "abs", "data": map[string]any{"axis": "x", "value": ax}}, + map[string]any{"type": "abs", "data": map[string]any{"axis": "y", "value": ay}}, + }}) +} + +// MouseButton sends one supported QEMU mouse button transition. +func MouseButton(q Executor, button string, down bool) error { + if q == nil { + return errors.New("QMP session is unavailable") + } + button = normalizeMouseButton(button) + if !validMouseButton(button) { + return fmt.Errorf("unsupported mouse button %q", button) + } + return sendMouseButton(q, button, down) +} + +// MouseClick presses and releases a mouse button as one serialized QMP job. +func MouseClick(q Executor, button string) error { + if q == nil { + return errors.New("QMP session is unavailable") + } + button = normalizeMouseButton(button) + if !validMouseButton(button) { + return fmt.Errorf("unsupported mouse button %q", button) + } + return q.Execute("input-send-event", map[string]any{"events": []any{ + mouseButtonEvent(button, true), + mouseButtonEvent(button, false), + }}) +} + +// MouseScroll sends vertical or horizontal wheel steps. A positive delta means +// down or right, and a negative delta means up or left. +func MouseScroll(q Executor, delta int, horizontal bool) error { + if q == nil { + return errors.New("QMP session is unavailable") + } + if delta == 0 { + return nil + } + if delta > 120 || delta < -120 { + return errors.New("mouse scroll exceeds 120 steps") + } + steps := delta + if steps < 0 { + steps = -steps + } + button := "wheel-down" + if horizontal { + button = "wheel-right" + } + if delta < 0 { + button = "wheel-up" + if horizontal { + button = "wheel-left" + } + } + events := make([]any, 0, steps*2) + for range steps { + events = append(events, + map[string]any{"type": "btn", "data": map[string]any{"down": true, "button": button}}, + map[string]any{"type": "btn", "data": map[string]any{"down": false, "button": button}}, + ) + } + return q.Execute("input-send-event", map[string]any{"events": events}) +} + +func absoluteAxis(position, size int) (int, error) { + if size <= 0 || position < 0 || position >= size { + return 0, errors.New("coordinate is outside the framebuffer") + } + if size == 1 { + return 0, nil + } + return int(math.Round(float64(position) * 32767 / float64(size-1))), nil +} + +func validMouseButton(button string) bool { + switch button { + case "left", "right", "middle", "wheel-up", "wheel-down", "wheel-left", "wheel-right": + return true + default: + return false + } +} + +func normalizeMouseButton(button string) string { + return strings.ToLower(strings.TrimSpace(button)) +} + +func mouseButtonEvent(button string, down bool) map[string]any { + return map[string]any{"type": "btn", "data": map[string]any{"down": down, "button": button}} +} + +func sendMouseButton(q Executor, button string, down bool) error { + button = normalizeMouseButton(button) + return q.Execute("input-send-event", map[string]any{"events": []any{mouseButtonEvent(button, down)}}) +} diff --git a/internal/thumb/thumb.go b/internal/thumb/thumb.go index 2496a52..4cbaf83 100644 --- a/internal/thumb/thumb.go +++ b/internal/thumb/thumb.go @@ -28,6 +28,26 @@ func Load(path, format string) (image.Image, error) { return decodePPM(bufio.NewReader(f)) } +// Size returns the source-frame dimensions without decoding its pixels. +func Size(path, format string) (image.Point, error) { + f, err := os.Open(path) + if err != nil { + return image.Point{}, err + } + defer f.Close() + if format == "png" { + cfg, err := png.DecodeConfig(bufio.NewReader(f)) + if err != nil { + return image.Point{}, err + } + return image.Pt(cfg.Width, cfg.Height), nil + } + if format != "ppm" { + return image.Point{}, fmt.Errorf("unsupported screendump format %q", format) + } + return ppmSize(bufio.NewReader(f)) +} + // decodePPM reads a binary PPM (P6, maxval ≤ 255), the format QEMU's // screendump writes when no format is given. func decodePPM(r *bufio.Reader) (image.Image, error) { diff --git a/pkg/pluginsdk/sdk.go b/pkg/pluginsdk/sdk.go index 7a053d4..612367d 100644 --- a/pkg/pluginsdk/sdk.go +++ b/pkg/pluginsdk/sdk.go @@ -18,7 +18,7 @@ import ( ) // PluginAPIVersion is the protocol version spoken by this SDK. -const PluginAPIVersion = "1.0.0" +const PluginAPIVersion = "1.1.0" // Handler handles one inbound JSON-RPC method from the Reims-Go host. type Handler func(ctx context.Context, params json.RawMessage) (any, error)