- run elevated actions as fixed System32 tools instead of a hidden subcommand - require a SHA-256 for plugin downloads - keep records of secret files that could not be deleted, and never overwrite files the host did not create - stop two concurrent requests from starting the same VM - drop invalid endpoints instead of failing the whole VM list, and reject ssh users and IPv6 zones that could inject command-line text - accept driver screenshots only at the requested path - do not treat an unreadable guest phase as normal Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
815 lines
28 KiB
Go
815 lines
28 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/Nwflower/reims-go/internal/driver"
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
"github.com/Nwflower/reims-go/internal/plugin"
|
|
"github.com/Nwflower/reims-go/internal/thumb"
|
|
)
|
|
|
|
const computerUsePreviewWidth = 1280
|
|
const computerUseMaxTextRunes = 4000
|
|
const computerUseSecretPluginID = "reims.agent"
|
|
|
|
const computerUseOwnershipFile = ".reims-go-computer-use"
|
|
const computerUseCloneRequestPrefix = "__agent-"
|
|
const computerUseCloneNamePrefix = "reims-agent-"
|
|
|
|
func isComputerUseCloneName(name string) bool {
|
|
return strings.HasPrefix(name, computerUseCloneNamePrefix) || strings.HasPrefix(name, computerUseCloneRequestPrefix)
|
|
}
|
|
|
|
type computerUseOwnership struct {
|
|
Version int `json:"version"`
|
|
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.suspend": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.suspend", a.handleComputerUseVMStateChange(a.SuspendVMWithDriver)),
|
|
"host/vm.resume": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.resume", a.handleComputerUseVMStateChange(a.ResumeVMWithDriver)),
|
|
"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, route, 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")
|
|
}
|
|
var count int
|
|
if route.kind == consoleRouteDriver {
|
|
count, err = route.console.ConsoleType(ctx, vm.Name, secret)
|
|
} else {
|
|
service, svcErr := a.computerUseService()
|
|
if svcErr != nil {
|
|
return nil, svcErr
|
|
}
|
|
count, err = service.TypeText(ctx, vm.Directory, secret, nil)
|
|
}
|
|
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) handleComputerUseVMStateChange(change func(driverID, name string) error) computerUseVMHandler {
|
|
return func(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
|
|
var req struct {
|
|
VM string `json:"vm"`
|
|
}
|
|
if err := json.Unmarshal(raw, &req); err != nil {
|
|
return nil, err
|
|
}
|
|
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := change(vm.DriverID, vm.Name); 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")
|
|
}
|
|
suffix, ok := strings.CutPrefix(cloneName, computerUseCloneRequestPrefix)
|
|
if !ok || suffix == "" {
|
|
return nil, errors.New("temporary MCP clone identifiers must begin with __agent- and include a suffix")
|
|
}
|
|
// Preserve the wire prefix used by released sidecars and register a valid VM name.
|
|
cloneName = computerUseCloneNamePrefix + suffix
|
|
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
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 strings.EqualFold(item.Name, cloneName) && driver.CanonicalDriverID(item.DriverID) == driver.CanonicalDriverID(vm.DriverID)
|
|
}) {
|
|
return nil, fmt.Errorf("VM name %q is already taken", cloneName)
|
|
}
|
|
cloned, err := a.cloneVMCoWWithDriverInfo(vm.DriverID, vm.Name, cloneName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
cloneRef := cloned.Ref()
|
|
err = persistComputerUseOwnership(cloned, pluginID, cloneRef.Key())
|
|
if 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, a.computerUseHostError("not_authorized", "err.computer_use.not_owned", i18n.Vars{"name": vm.Name})
|
|
}
|
|
if vm.State == "running" {
|
|
if err := a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, false); err != nil {
|
|
if forceErr := a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, true); forceErr != nil {
|
|
return nil, errors.Join(err, fmt.Errorf("force stop temporary VM %q: %w", vm.Name, forceErr))
|
|
}
|
|
}
|
|
}
|
|
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, a.computerUseHostError("confirmation_required", "err.computer_use.restore_confirmation", i18n.Vars{"name": vm.Name})
|
|
}
|
|
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
|
|
}
|
|
}
|
|
|
|
// resolveComputerUseVM returns the VM and the console route Agent calls use.
|
|
// A VM whose driver serves its own console needs no host process; every other
|
|
// VM must be a running QMP-reachable process.
|
|
func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (driver.VMInfo, consoleRoute, error) {
|
|
ref = strings.TrimSpace(ref)
|
|
if ref == "" {
|
|
return driver.VMInfo{}, consoleRoute{}, errors.New("VM reference is required")
|
|
}
|
|
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, ref)
|
|
if err != nil {
|
|
return driver.VMInfo{}, consoleRoute{}, err
|
|
}
|
|
route, err := a.resolveConsoleRoute(vm)
|
|
if err != nil {
|
|
return driver.VMInfo{}, consoleRoute{}, err
|
|
}
|
|
current, ok := a.polledVMForDriver(vm.DriverID, vm.Name)
|
|
if !ok || current.State != "running" {
|
|
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("vm_not_running", "err.computer_use.vm_not_running", i18n.Vars{"name": vm.Name})
|
|
}
|
|
if route.kind == consoleRouteQMP && (current.PID == nil || *current.PID <= 0) {
|
|
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("vm_not_running", "err.computer_use.vm_not_running", i18n.Vars{"name": vm.Name})
|
|
}
|
|
if vm.Phase == "" {
|
|
if pr, ok := a.driverFor(vm).(driver.PhaseReporter); ok {
|
|
pctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
phase, err := pr.Phase(pctx, vm.Name)
|
|
cancel()
|
|
// Only a driver without `driver/phase` has no protected phases; any
|
|
// other failure must not pass for the normal phase.
|
|
var rpcErr *plugin.RPCError
|
|
if err != nil && !(errors.As(err, &rpcErr) && rpcErr.Code == plugin.RPCMethodNotFound) {
|
|
return driver.VMInfo{}, consoleRoute{}, fmt.Errorf("read the guest phase of %s: %w", vm.Name, err)
|
|
}
|
|
vm.Phase = phase
|
|
}
|
|
}
|
|
if phase := computerUseVMPhase(vm); phase != "normal" {
|
|
phaseLabel := i18n.M(a.computerUseLocale(), "err.computer_use.phase."+phase, nil)
|
|
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("confirmation_required", "err.computer_use.phase_confirmation", i18n.Vars{"name": vm.Name, "phase": phaseLabel})
|
|
}
|
|
if vm.Directory == "" {
|
|
vm.Directory = current.Dir
|
|
}
|
|
if route.kind == consoleRouteQMP && vm.Directory == "" {
|
|
return driver.VMInfo{}, consoleRoute{}, fmt.Errorf("VM %q has no console directory", vm.Name)
|
|
}
|
|
route.vm = vm
|
|
return vm, route, 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{}, a.computerUseHostError("not_authorized", "err.computer_use.access_disabled", i18n.Vars{"name": vm.Name})
|
|
}
|
|
return vm, nil
|
|
}
|
|
|
|
func (a *App) computerUseHostError(code, key string, params i18n.Vars) error {
|
|
return fmt.Errorf("%s: %s", code, i18n.M(a.computerUseLocale(), key, params))
|
|
}
|
|
|
|
func (a *App) computerUseLocale() i18n.Locale {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
loc := i18n.ZhCN
|
|
if a.cfg != nil {
|
|
loc = a.cfg.Locale
|
|
}
|
|
return loc
|
|
}
|
|
|
|
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.CreateTemp(vmDir, computerUseOwnershipFile+".tmp-")
|
|
if err != nil {
|
|
return fmt.Errorf("stage temporary VM ownership marker: %w", err)
|
|
}
|
|
tempPath := file.Name()
|
|
defer os.Remove(tempPath)
|
|
if _, err := file.Write(append(data, '\n')); err != nil {
|
|
_ = file.Close()
|
|
return fmt.Errorf("write temporary VM ownership marker: %w", err)
|
|
}
|
|
if err := file.Sync(); err != nil {
|
|
_ = file.Close()
|
|
return fmt.Errorf("sync temporary VM ownership marker: %w", err)
|
|
}
|
|
if err := file.Close(); err != nil {
|
|
return fmt.Errorf("close temporary VM ownership marker: %w", err)
|
|
}
|
|
if err := os.Link(tempPath, path); err != nil {
|
|
return fmt.Errorf("publish 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 == "" || !isComputerUseCloneName(vm.Name) {
|
|
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)
|
|
if err := a.requireWritableDataRoot(); err != nil {
|
|
return err
|
|
}
|
|
var cleanupErrors []error
|
|
for _, item := range vms {
|
|
vm := driver.VMInfo{Name: item.Name, DriverID: item.DriverID, Directory: item.Dir}
|
|
marker, ok := readComputerUseOwnership(vm)
|
|
if !ok {
|
|
continue
|
|
}
|
|
if item.State == "running" {
|
|
stopCtx, stopCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
|
err := a.stopVMWithDriverCtx(stopCtx, item.DriverID, item.Name, false)
|
|
stopCancel()
|
|
if err != nil {
|
|
forceCtx, forceCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
|
forceErr := a.stopVMWithDriverCtx(forceCtx, item.DriverID, item.Name, true)
|
|
forceCancel()
|
|
if forceErr != nil {
|
|
cleanupErrors = append(cleanupErrors, errors.Join(
|
|
fmt.Errorf("stop orphaned temporary VM %q: %w", item.Name, err),
|
|
fmt.Errorf("force stop orphaned temporary VM %q: %w", item.Name, forceErr),
|
|
))
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
if err := a.DeleteVMWithDriver(item.DriverID, item.Name, false); err != nil {
|
|
cleanupErrors = append(cleanupErrors, fmt.Errorf("delete orphaned temporary VM %q: %w", item.Name, err))
|
|
continue
|
|
}
|
|
a.markComputerUseOwnedVM(marker.PluginID, vm.Ref().Key(), false)
|
|
}
|
|
return errors.Join(cleanupErrors...)
|
|
}
|
|
|
|
func persistComputerUseOwnership(vm driver.VMInfo, pluginID, vmKey string) error {
|
|
if vm.Directory == "" {
|
|
return errors.New("temporary clone directory is unavailable")
|
|
}
|
|
if err := writeComputerUseOwnership(vm.Directory, pluginID, vmKey); err != nil {
|
|
return err
|
|
}
|
|
marker, ok := readComputerUseOwnership(vm)
|
|
if !ok || marker.PluginID != pluginID {
|
|
return errors.New("temporary VM ownership marker could not be verified")
|
|
}
|
|
return 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 == "" || !isComputerUseCloneName(vm.Name) {
|
|
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 {
|
|
switch vm.Phase {
|
|
case driver.PhaseInstaller, driver.PhaseRecovery:
|
|
return vm.Phase
|
|
}
|
|
if vmInfoBool(vm, "has_installer") {
|
|
return "installer"
|
|
}
|
|
if driver.CanonicalDriverID(vm.DriverID) == driver.BuiltinReimsMacOSDriverID {
|
|
if isRecoveryMarkerActive(vm.Directory) {
|
|
return "recovery"
|
|
}
|
|
return "normal"
|
|
}
|
|
if vmInfoBool(vm, "recovery_mode") {
|
|
return "recovery"
|
|
}
|
|
return "normal"
|
|
}
|
|
|
|
// computerUseAccessSetting records the user's per-VM consent. Only the host
|
|
// settings UI may write it; the plugin bridge rejects it.
|
|
const computerUseAccessSetting = "allow_ai_access"
|
|
|
|
func computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) bool {
|
|
if mgr == nil || strings.TrimSpace(pluginID) == "" || strings.TrimSpace(vmKey) == "" {
|
|
return false
|
|
}
|
|
return mgr.SavedBoolSetting(pluginID, vmKey, computerUseAccessSetting)
|
|
}
|
|
|
|
// 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
|
|
}
|
|
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
path, format, cleanup, err := a.consoleCapture(ctx, route, computerUsePreviewWidth)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer cleanup()
|
|
sourceSize, err := thumb.Size(path, format)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// A blank frame is a normal screen state during boot, login and display
|
|
// switches. Return it with a flag so pollers can keep waiting through it.
|
|
preview, blank, err := thumb.LoadPreviewFrame(path, format, computerUsePreviewWidth)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
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,
|
|
"blank": blank,
|
|
"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
|
|
}
|
|
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := a.consolePointer(ctx, route, driver.ConsolePointerRequest{
|
|
Action: req.Action, X: req.X, Y: req.Y, Width: req.Width, Height: req.Height,
|
|
Button: req.Button, Down: req.Down, Delta: req.Delta, Horizontal: req.Horizontal,
|
|
}); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"ok": true}, nil
|
|
}
|
|
|
|
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")
|
|
}
|
|
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := a.consoleKey(ctx, route, 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.injectTextIntoVMForDriver(vm.DriverID, vm.Name, vm.Directory, req.Text, false, true)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"characters": n}, nil
|
|
}
|