Files
Reims-Go/internal/app/computer_use_host.go
千川白浪 9006e6d9a7
CI / verify (push) Canceled after 0s
CI / rolling-release (push) Canceled after 0s
refactor: 抽离 HostAPIService 并将 internal/plugin 拆分为四层无环子包 (#202)
2026-12-05 06:05:41 -07:00

1027 lines
37 KiB
Go

package app
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"image"
"os"
"path/filepath"
"slices"
"strings"
"time"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/console"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/thumb"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
const computerUsePreviewWidth = 1280
const computerUseMaxImageWidth = 2560
const computerUseMinImageWidth = 64
const computerUseMaxTextRunes = 4000
const computerUseOwnershipFile = ".reims-go-computer-use"
type computerUseOwnership struct {
Version int `json:"version"`
PluginID string `json:"plugin_id"`
VMKey string `json:"vm_key"`
// SourceVM is the driver-qualified key of the VM the clone was taken from.
// A clone has no vm settings of its own (login password, SSH user), so
// secret and username lookups fall back to the source while it is still
// authorized. Older markers omit it and simply have no fallback.
SourceVM string `json:"source_vm,omitempty"`
}
// computerUseHostHandlers serves the VM and console Host API. Every method is
// registered through hostMethod, which authorizes from the contract catalog in
// pkg/pluginproto and audits under the method name.
func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
if mgr == nil || mgr.Broker() == nil {
return nil
}
return map[string]plugin.RPCRequestHandler{
"host/vm.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.list", a.handleComputerUseVMList),
"host/vm.get": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.get", a.handleComputerUseVMGet),
"host/vm.start": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.start", a.handleComputerUseVMStart),
"host/vm.shutdown": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.shutdown", a.handleComputerUseVMShutdown),
"host/vm.suspend": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.suspend", a.handleComputerUseVMStateChange("host/vm.suspend", a.SuspendVM)),
"host/vm.resume": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.resume", a.handleComputerUseVMStateChange("host/vm.resume", a.ResumeVM)),
"host/vm.clone": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.clone", a.handleComputerUseVMClone),
"host/vm.delete": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.delete", a.handleComputerUseVMDelete),
"host/vm.snapshot.list": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
"host/vm.snapshot.create": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
"host/vm.snapshot.restore": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
"host/console.screenshot": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.screenshot", a.handleComputerUseScreenshot),
"host/console.pointer": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.pointer", a.handleComputerUsePointer),
"host/console.key": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.key", a.handleComputerUseKey),
"host/console.type": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.type", a.handleComputerUseType),
"host/console.typeSecret": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.typeSecret", a.handleComputerUseTypeSecret),
"host/console.release": a.hostAPISvc().hostVMMethod(mgr, pluginID, "host/console.release", a.handleComputerUseRelease),
}
}
type computerUseVMHandler func(context.Context, json.RawMessage, *plugin.Manager, string) (any, error)
// handleComputerUseTypeSecret types one of the calling plugin's own settings
// into a VM the user authorized that plugin to access. The host never returns
// the value, so a plugin can use a secret it stored without ever reading it.
// The method is open to every plugin that holds qmp:write; the user's per-VM
// access consent is the only gate, and the audit log records the setting name
// and its length.
func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.TypeSecretParams](mgr, pluginID, "host/console.typeSecret", raw)
if 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 := a.computerUseSecretSetting(mgr, pluginID, vm, req.Setting)
if err != nil {
if errors.Is(err, plugin.ErrSecretEmpty) {
return nil, a.computerUseHostError("secret_missing", "err.computer_use.secret_missing", i18n.Vars{"name": vm.Name})
}
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 pluginproto.CharactersResult{Characters: count}, nil
}
func (a *App) handleComputerUseVMList(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
if _, err := decodeHostParams[struct{}](mgr, pluginID, "host/vm.list", raw); err != nil {
return nil, err
}
items, err := a.listVMsInternal(ctx)
if err != nil {
return nil, err
}
vms := make([]pluginproto.VMView, 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 pluginproto.VMListResult{VMs: vms}, nil
}
func (a *App) handleComputerUseVMGet(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.get", raw)
if err != nil {
return nil, err
}
info, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
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) pluginproto.VMView {
accessEnabled := a.computerUseVMAccessEnabled(mgr, pluginID, vm.Ref().Key())
view := pluginproto.VMView{
VM: vm.Ref().Key(),
Name: vm.Name,
DriverID: vm.DriverID,
State: vm.State,
Authorized: accessEnabled,
Phase: computerUseVMPhase(vm),
Owned: a.computerUseOwned(pluginID, vm.Ref().Key()),
}
if vm.CPUs > 0 {
view.CPUs = vm.CPUs
}
if vm.Memory != "" {
view.Memory = vm.Memory
}
if vm.DiskSummary != "" {
view.DiskSummary = vm.DiskSummary
}
if accessEnabled && vm.SSHPort > 0 {
view.SSHPort = vm.SSHPort
}
if len(vm.Capabilities) > 0 {
view.Capabilities = append([]string(nil), vm.Capabilities...)
}
if accessEnabled {
if username := a.computerUseSSHUser(mgr, pluginID, vm); username != "" {
view.SSHUsername = username
}
}
return view
}
func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.start", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.StartVM(vm.DriverID, vm.Name); err != nil {
return nil, err
}
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.VMShutdownParams](mgr, pluginID, "host/vm.shutdown", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.StopVM(vm.DriverID, vm.Name, req.Force); err != nil {
return nil, err
}
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseVMStateChange(method string, change func(driverID, name string) error) computerUseVMHandler {
return func(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, method, raw)
if 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 pluginproto.OKResult{OK: true}, nil
}
}
func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.VMCloneParams](mgr, pluginID, "host/vm.clone", raw)
if err != nil {
return nil, err
}
cloneName := strings.TrimSpace(req.CloneName)
if cloneName == "" {
return nil, errors.New("clone_name is required")
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
a.hostAPI.computerUseCloneMu.Lock()
defer a.hostAPI.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.cloneVM(vm.DriverID, vm.Name, cloneName)
if err != nil {
return nil, err
}
cloneRef := cloned.Ref()
err = persistComputerUseOwnership(cloned, pluginID, cloneRef.Key(), vm.Ref().Key())
if err != nil {
if cleanupErr := a.DeleteVM(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 pluginproto.VMCloneResult{
VM: cloneRef.Key(), Name: cloneName, DriverID: vm.DriverID, State: "stopped", Owned: true,
}, nil
}
func (a *App) handleComputerUseVMDelete(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.delete", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveComputerUseVMInfo(req.VM)
if err != nil {
return nil, err
}
// Deleting a VM is irreversible, so it stays limited to the temporary VMs
// this plugin created. Every other VM keeps its own lifecycle.
if !a.computerUseOwned(pluginID, vm.Ref().Key()) {
return nil, a.computerUseHostError("not_authorized", "err.computer_use.not_owned", i18n.Vars{"name": vm.Name})
}
if vm.State == "running" {
if err := a.stopVM(ctx, vm.DriverID, vm.Name, false); err != nil {
if forceErr := a.stopVM(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.DeleteVM(vm.DriverID, vm.Name, false); err != nil {
return nil, err
}
removeComputerUseOwnership(vm.Directory)
a.markComputerUseOwnedVM(pluginID, vm.Ref().Key(), false)
// The guest is gone, so nothing it held can still be held.
a.forgetHeld(pluginID, vm.Ref().Key())
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseVMSnapshotList(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.VMParams](mgr, pluginID, "host/vm.snapshot.list", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
snapshots, err := a.ListSnapshots(vm.DriverID, vm.Name)
if err != nil {
return nil, err
}
out := make([]pluginproto.Snapshot, 0, len(snapshots))
for _, snap := range snapshots {
out = append(out, pluginproto.Snapshot{
ID: snap.ID, Name: snap.Name, CreatedAt: snap.CreatedAt, VMStateBytes: snap.VMStateBytes,
})
}
return pluginproto.SnapshotListResult{Snapshots: out}, nil
}
func (a *App) handleComputerUseVMSnapshotCreate(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.SnapshotNameParams](mgr, pluginID, "host/vm.snapshot.create", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.CreateSnapshot(vm.DriverID, vm.Name, req.Name); err != nil {
return nil, err
}
return pluginproto.SnapshotResult{OK: true, Name: strings.TrimSpace(req.Name)}, nil
}
// handleComputerUseVMSnapshotRestore restores a snapshot of any VM the user
// authorized this plugin to access. Restoring replaces the guest's state, which
// the plugin can already stop, start and clone, so it needs no separate
// consent; the call is audited like every other VM control.
func (a *App) handleComputerUseVMSnapshotRestore(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.SnapshotNameParams](mgr, pluginID, "host/vm.snapshot.restore", raw)
if err != nil {
return nil, err
}
vm, err := a.resolveAuthorizedComputerUseVMInfo(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.RestoreSnapshot(vm.DriverID, vm.Name, req.Name); err != nil {
return nil, err
}
return pluginproto.SnapshotResult{OK: true, Name: strings.TrimSpace(req.Name)}, 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
}
// A plugin that stopped calling mid-hold must not leave a key down.
route, err := a.resolveConsoleRoute(vm)
if err != nil {
return driver.VMInfo{}, consoleRoute{}, err
}
current, ok := a.polledVMForDriver(vm.DriverID, vm.Name)
if !ok || current.State != "running" {
// A powered-off guest holds nothing, so the record is dropped rather
// than retried: a later release could lift a key the user is pressing.
a.forgetHeld(pluginID, vm.Ref().Key())
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("vm_not_running", "err.computer_use.vm_not_running", i18n.Vars{"name": vm.Name})
}
if route.kind == consoleRouteQMP && (current.PID == nil || *current.PID <= 0) {
a.forgetHeld(pluginID, vm.Ref().Key())
return driver.VMInfo{}, consoleRoute{}, a.computerUseHostError("vm_not_running", "err.computer_use.vm_not_running", i18n.Vars{"name": vm.Name})
}
if vm.Phase == "" {
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 {
h := a.hostAPISvc()
h.ownedMu.Lock()
defer h.ownedMu.Unlock()
return h.computerUseOwnedVMs != nil && h.computerUseOwnedVMs[pluginID] != nil && h.computerUseOwnedVMs[pluginID][vmKey]
}
func (a *App) markComputerUseOwnedVM(pluginID, vmKey string, owned bool) {
h := a.hostAPISvc()
h.ownedMu.Lock()
defer h.ownedMu.Unlock()
if h.computerUseOwnedVMs == nil {
h.computerUseOwnedVMs = make(map[string]map[string]bool)
}
if h.computerUseOwnedVMs[pluginID] == nil {
h.computerUseOwnedVMs[pluginID] = make(map[string]bool)
}
if owned {
h.computerUseOwnedVMs[pluginID][vmKey] = true
} else {
delete(h.computerUseOwnedVMs[pluginID], vmKey)
}
}
func (a *App) forgetComputerUseOwnedVM(vmKey string) {
vmKey = strings.TrimSpace(vmKey)
if vmKey == "" {
return
}
h := a.hostAPISvc()
h.ownedMu.Lock()
defer h.ownedMu.Unlock()
for pluginID, owned := range h.computerUseOwnedVMs {
delete(owned, vmKey)
if len(owned) == 0 {
delete(h.computerUseOwnedVMs, pluginID)
}
}
}
func writeComputerUseOwnership(vmDir, pluginID, vmKey, sourceVM string) error {
vmDir = strings.TrimSpace(vmDir)
pluginID = strings.TrimSpace(pluginID)
vmKey = strings.TrimSpace(vmKey)
sourceVM = strings.TrimSpace(sourceVM)
if vmDir == "" || pluginID == "" || vmKey == "" {
return errors.New("temporary VM ownership metadata is incomplete")
}
data, err := json.Marshal(computerUseOwnership{Version: 1, PluginID: pluginID, VMKey: vmKey, SourceVM: sourceVM})
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))
}
// readComputerUseOwnership reads the marker the host wrote when it cloned a VM
// for a plugin. The marker, not the VM name, is what makes a VM a plugin's
// temporary clone, so a plugin may name its clones freely.
func readComputerUseOwnership(vm driver.VMInfo) (computerUseOwnership, bool) {
if vm.Directory == "" {
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.stopVM(stopCtx, item.DriverID, item.Name, false)
stopCancel()
if err != nil {
forceCtx, forceCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
forceErr := a.stopVM(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.DeleteVM(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, sourceVM string) error {
if vm.Directory == "" {
return errors.New("temporary clone directory is unavailable")
}
if err := writeComputerUseOwnership(vm.Directory, pluginID, vmKey, sourceVM); err != nil {
return err
}
marker, ok := readComputerUseOwnership(vm)
if !ok || marker.PluginID != pluginID || marker.SourceVM != strings.TrimSpace(sourceVM) {
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 == "" {
continue
}
marker, ok := readComputerUseOwnership(vm)
if ok {
a.markComputerUseOwnedVM(marker.PluginID, marker.VMKey, true)
continue
}
key := vm.Ref().Key()
h := a.hostAPISvc()
h.ownedMu.Lock()
var pluginIDs []string
for pluginID, owned := range h.computerUseOwnedVMs {
if owned[key] {
pluginIDs = append(pluginIDs, pluginID)
}
}
h.ownedMu.Unlock()
for _, pluginID := range pluginIDs {
// The source VM is no longer known on this repair path (the marker
// was lost), so write an empty source: no fallback, same as before.
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)
}
// computerUseSourceVM returns the driver-qualified key of the VM a temporary
// clone was taken from, or "" when the clone records no usable source. Only
// MCP-owned clones carry an ownership marker, so any other VM has no fallback.
func (a *App) computerUseSourceVM(vm driver.VMInfo) string {
marker, ok := readComputerUseOwnership(vm)
if !ok {
return ""
}
source := strings.TrimSpace(marker.SourceVM)
if source == "" || source == vm.Ref().Key() {
return ""
}
normalized, ok := driver.ParseVMRef(source)
if !ok {
return ""
}
return normalized.Key()
}
// computerUseSecretSetting reads one secret for a VM. A temporary clone owns no
// vm settings, so a value it does not have falls back to the source VM's copy
// while that source still allows MCP access. The fallback reads the single
// stored secret instead of copying it, so revoking access to the source also
// revokes it for its clones and no secret is left behind when a clone is
// disposed. A source that no longer exists resolves to nothing.
func (a *App) computerUseSecretSetting(mgr *plugin.Manager, pluginID string, vm driver.VMInfo, key string) (string, error) {
value, err := mgr.SecretSetting(pluginID, vm.Ref().Key(), key)
if err == nil {
return value, nil
}
if !errors.Is(err, plugin.ErrSecretEmpty) {
return "", err
}
sourceVM, ok := a.computerUseAuthorizedSource(mgr, pluginID, vm)
if !ok {
return "", err
}
return mgr.SecretSetting(pluginID, sourceVM.Ref().Key(), key)
}
// computerUseAuthorizedSource resolves a clone's source VM and confirms the
// source still grants MCP access. It reports false when the clone has no
// recorded source, the source is gone, or access to the source was revoked.
func (a *App) computerUseAuthorizedSource(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) (driver.VMInfo, bool) {
source := a.computerUseSourceVM(vm)
if source == "" || !computerUseVMAccessEnabled(mgr, pluginID, source) {
return driver.VMInfo{}, false
}
ref, ok := driver.ParseVMRef(source)
if !ok {
return driver.VMInfo{}, false
}
sourceVM, err := a.resolveVMInfo(ref.DriverID, ref.Name)
if err != nil {
return driver.VMInfo{}, false
}
return sourceVM, true
}
// computerUseSSHUser resolves the SSH login name for a VM. A temporary clone
// has neither its own settings nor a copied .reims-go-ssh-user file, so it
// borrows the source's user while the source still allows MCP access.
func (a *App) computerUseSSHUser(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) string {
if username := a.sshUserForVM(mgr, pluginID, vm); username != "" {
return username
}
sourceVM, ok := a.computerUseAuthorizedSource(mgr, pluginID, vm)
if !ok {
return ""
}
return a.sshUserForVM(mgr, pluginID, sourceVM)
}
func (a *App) sshUserForVM(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) string {
username := a.GetVMSSHUser(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)
}
}
return strings.TrimSpace(username)
}
// 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)
}
// computerUseRegion is a rectangle in source-frame pixels.
type computerUseRegion struct {
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
}
// computerUseRegionFrame cuts region from a full-resolution frame, clipped to
// the screen, and shrinks the cut to at most maxWidth pixels wide. It returns
// the region that was actually used.
func computerUseRegionFrame(full image.Image, region computerUseRegion, maxWidth int) (image.Image, computerUseRegion, error) {
area := image.Rect(region.X, region.Y, region.X+region.Width, region.Y+region.Height).Intersect(full.Bounds())
if area.Empty() {
return nil, computerUseRegion{}, errors.New("region does not intersect the screen")
}
sub, ok := full.(interface {
SubImage(image.Rectangle) image.Image
})
if !ok {
return nil, computerUseRegion{}, errors.New("screen frame cannot be cropped")
}
applied := computerUseRegion{X: area.Min.X, Y: area.Min.Y, Width: area.Dx(), Height: area.Dy()}
return thumb.Scale(sub.SubImage(area), maxWidth), applied, nil
}
// computerUseRegionToSource maps a region given in a refW x refH image of the
// screen onto the source frame, widening it outward so no selected pixel is
// lost to rounding.
func computerUseRegionToSource(region computerUseRegion, refW, refH int, source image.Point) computerUseRegion {
if refW <= 0 || refH <= 0 {
return region
}
x0 := region.X * source.X / refW
y0 := region.Y * source.Y / refH
x1 := ((region.X+region.Width)*source.X + refW - 1) / refW
y1 := ((region.Y+region.Height)*source.Y + refH - 1) / refH
return computerUseRegion{X: x0, Y: y0, Width: x1 - x0, Height: y1 - y0}
}
// computerUseScreenshotWidth returns the width the returned image is scaled
// to. A request outside the supported range is brought into it rather than
// refused, so a caller that asks for more than the host encodes still gets a
// usable frame.
func computerUseScreenshotWidth(requested int) int {
if requested == 0 {
return computerUsePreviewWidth
}
return min(max(requested, computerUseMinImageWidth), computerUseMaxImageWidth)
}
func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.ScreenshotParams](mgr, pluginID, "host/console.screenshot", raw)
if err != nil {
return nil, err
}
maxWidth := computerUseScreenshotWidth(req.MaxWidth)
if req.Region != nil && (req.Region.Width <= 0 || req.Region.Height <= 0) {
return nil, errors.New("region width and height must be positive")
}
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
// A region is cut from the full-resolution frame, so the driver must not
// shrink it first.
captureEdge := maxWidth
if req.Region != nil {
captureEdge = 0
}
path, format, cleanup, err := a.consoleCapture(ctx, route, captureEdge)
if err != nil {
return nil, err
}
defer cleanup()
sourceSize, err := thumb.Size(path, format)
if err != nil {
return nil, err
}
var (
frame image.Image
blank bool
)
result := pluginproto.ScreenshotResult{
MIMEType: "image/jpeg", SourceWidth: sourceSize.X, SourceHeight: sourceSize.Y,
}
if req.Region == nil {
// A blank frame is a normal screen state during boot, login and display
// switches. Return it with a flag so pollers can keep waiting through it.
frame, blank, err = thumb.LoadPreviewFrame(path, format, maxWidth)
if err != nil {
return nil, err
}
} else {
full, err := thumb.Load(path, format)
if err != nil {
return nil, err
}
var applied computerUseRegion
region := computerUseRegionToSource(computerUseRegion{
X: req.Region.X, Y: req.Region.Y, Width: req.Region.Width, Height: req.Region.Height,
}, req.Width, req.Height, full.Bounds().Size())
result.SourceWidth, result.SourceHeight = full.Bounds().Dx(), full.Bounds().Dy()
frame, applied, err = computerUseRegionFrame(full, region, maxWidth)
if err != nil {
return nil, err
}
blank = thumb.Blank(full)
result.Region = &pluginproto.Region{X: applied.X, Y: applied.Y, Width: applied.Width, Height: applied.Height}
}
encoded, err := thumb.JPEG(frame, 84)
if err != nil {
return nil, err
}
bounds := frame.Bounds()
result.Width = bounds.Dx()
result.Height = bounds.Dy()
result.Blank = blank
result.Data = base64.StdEncoding.EncodeToString(encoded)
return result, nil
}
// computerUseHeldButtons normalizes the pointer buttons of a held gesture the
// way consoleRelease does, so the ledger records what will be lifted later.
func computerUseHeldButtons(buttons []string) ([]string, error) {
return normalizeReleaseButtons(buttons)
}
func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.PointerParams](mgr, pluginID, "host/console.pointer", raw)
if err != nil {
return nil, err
}
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
// A button left down stays down in the guest until a release arrives, so
// the host records it on both console kinds and can lift it if the plugin
// goes away.
held := req.Action == "button" && req.Down != nil
button := ""
if held {
names, err := computerUseHeldButtons([]string{req.Button})
if err != nil {
return nil, err
}
button = names[0]
if *req.Down {
a.noteHeldButton(pluginID, vm.Ref().Key(), button, true)
}
}
if err := a.consolePointer(ctx, route, driver.ConsolePointerRequest{
Action: req.Action, X: req.X, Y: req.Y, Width: req.Width, Height: req.Height,
Button: req.Button, Down: req.Down, Delta: req.Delta, Horizontal: req.Horizontal,
}); err != nil {
return nil, err
}
if held && !*req.Down {
a.noteHeldButton(pluginID, vm.Ref().Key(), button, false)
}
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.KeyParams](mgr, pluginID, "host/console.key", raw)
if err != nil {
return nil, err
}
if strings.TrimSpace(req.Key) == "" {
return nil, errors.New("key is required")
}
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if req.Down == nil {
if err := a.consoleKey(ctx, route, req.Key, req.Modifiers); err != nil {
return nil, err
}
return pluginproto.OKResult{OK: true}, nil
}
// A held key may carry modifiers: each one is held or released with it, so
// a caller can hold Command and click without a second round trip.
names := append([]string{req.Key}, req.Modifiers...)
codes := make([]string, 0, len(names))
for _, name := range names {
code, err := console.NormalizeHeldKey(name)
if err != nil {
return nil, err
}
codes = append(codes, code)
}
// Record a press before sending it: a call that never returns still left
// the key down, and the fallback release has to know about it.
if *req.Down {
for _, code := range codes {
a.noteHeldKey(pluginID, vm.Ref().Key(), code, true)
}
}
for _, code := range codes {
if err := a.consoleKeyState(ctx, route, code, *req.Down); err != nil {
return nil, err
}
}
if !*req.Down {
for _, code := range codes {
a.noteHeldKey(pluginID, vm.Ref().Key(), code, false)
}
}
return pluginproto.OKResult{OK: true}, nil
}
// handleComputerUseRelease lifts the given keys and pointer buttons in one
// report, so a client that stops mid-gesture never leaves input held.
func (a *App) handleComputerUseRelease(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.ReleaseParams](mgr, pluginID, "host/console.release", raw)
if err != nil {
return nil, err
}
vm, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if err := a.consoleRelease(ctx, route, req.Keys, req.Buttons); err != nil {
return nil, err
}
// Whatever the caller lifted is no longer held on the host's books either.
codes := make([]string, 0, len(req.Keys))
for _, key := range req.Keys {
if code, err := console.NormalizeHeldKey(key); err == nil {
codes = append(codes, code)
}
}
buttons, _ := computerUseHeldButtons(req.Buttons)
a.dropHeld(pluginID, vm.Ref().Key(), codes, buttons)
return pluginproto.OKResult{OK: true}, nil
}
func (a *App) handleComputerUseType(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
req, err := decodeHostParams[pluginproto.TypeParams](mgr, pluginID, "host/console.type", raw)
if err != nil {
return nil, err
}
if len(req.Text) == 0 || !utf8.ValidString(req.Text) {
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, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
if err != nil {
return nil, err
}
if route.kind == consoleRouteQMP {
// Typing below uses the host's own console; agents need the plugin on.
if _, err := a.computerUseService(); 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 pluginproto.CharactersResult{Characters: n}, nil
}