- Each plugin connect connection gets a session id that is forwarded with channel/<id>/message; when the connection ends the host notifies the sidecar with channel/<id>/closed so it can cancel calls and release input. - host/console.screenshot crops a region from the full-resolution frame, optionally measured in a reference image size, and full frames now honor max_width up to 2560. - host/console.key can hold or release one key, and host/console.release lifts keys and pointer buttons in one call. Driver consoles stay press-only. - host/vm.shutdown accepts force, and host/vm.snapshot.list needs only vm:read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1023 lines
36 KiB
Go
1023 lines
36 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/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 computerUseMaxImageWidth = 2560
|
|
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"`
|
|
// 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"`
|
|
}
|
|
|
|
func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
|
if mgr == nil || mgr.Broker() == nil {
|
|
return nil
|
|
}
|
|
handlers := map[string]plugin.RPCRequestHandler{
|
|
"host/vm.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.list", a.handleComputerUseVMList),
|
|
"host/vm.get": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.get", a.handleComputerUseVMGet),
|
|
"host/vm.start": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.start", a.handleComputerUseVMStart),
|
|
"host/vm.shutdown": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.shutdown", a.handleComputerUseVMShutdown),
|
|
"host/vm.suspend": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.suspend", a.handleComputerUseVMStateChange(a.SuspendVM)),
|
|
"host/vm.resume": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.resume", a.handleComputerUseVMStateChange(a.ResumeVM)),
|
|
"host/vm.clone": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.clone", a.handleComputerUseVMClone),
|
|
"host/vm.delete": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.delete", a.handleComputerUseVMDelete),
|
|
"host/vm.snapshot.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
|
|
"host/vm.snapshot.create": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
|
|
"host/vm.snapshot.restore": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
|
|
"host/console.screenshot": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:screen", "host/console.screenshot", a.handleComputerUseScreenshot),
|
|
"host/console.pointer": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.pointer", a.handleComputerUsePointer),
|
|
"host/console.key": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.key", a.handleComputerUseKey),
|
|
"host/console.type": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.type", a.handleComputerUseType),
|
|
"host/console.release": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.release", a.handleComputerUseRelease),
|
|
}
|
|
// 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 := 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 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 {
|
|
if username := a.computerUseSSHUser(mgr, pluginID, vm); 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.StartVM(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"`
|
|
Force bool `json:"force"`
|
|
}
|
|
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.StopVM(vm.DriverID, vm.Name, req.Force); 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.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 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.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)
|
|
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.ListSnapshots(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.CreateSnapshot(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.RestoreSnapshot(vm.DriverID, vm.Name, req.Name); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"ok": true, "name": strings.TrimSpace(req.Name)}, nil
|
|
}
|
|
|
|
type computerUseHandler func(context.Context, json.RawMessage) (any, error)
|
|
|
|
func (a *App) authorizedComputerUseHandler(mgr *plugin.Manager, pluginID, permission, method string, run computerUseHandler) plugin.RPCRequestHandler {
|
|
return func(ctx context.Context, raw json.RawMessage) (any, error) {
|
|
broker := mgr.Broker()
|
|
if err := broker.Authorize(pluginID, permission); err != nil {
|
|
return nil, err
|
|
}
|
|
result, err := run(ctx, raw)
|
|
if err != nil {
|
|
broker.Audit(pluginID, "HOST_API_ERROR", method)
|
|
return nil, err
|
|
}
|
|
broker.Audit(pluginID, "HOST_API", method)
|
|
return result, nil
|
|
}
|
|
}
|
|
|
|
// 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, 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))
|
|
}
|
|
|
|
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.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 == "" || !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 {
|
|
// 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}
|
|
}
|
|
|
|
func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
|
|
var req struct {
|
|
VM string `json:"vm"`
|
|
Region *computerUseRegion `json:"region"`
|
|
MaxWidth int `json:"max_width"`
|
|
// Width and Height name the image the region was measured in; without
|
|
// them the region is in source pixels.
|
|
Width int `json:"width"`
|
|
Height int `json:"height"`
|
|
}
|
|
if err := json.Unmarshal(raw, &req); err != nil {
|
|
return nil, err
|
|
}
|
|
maxWidth := req.MaxWidth
|
|
if maxWidth == 0 {
|
|
maxWidth = computerUsePreviewWidth
|
|
}
|
|
if maxWidth < 64 || maxWidth > computerUseMaxImageWidth {
|
|
return nil, fmt.Errorf("max_width must be between 64 and %d", computerUseMaxImageWidth)
|
|
}
|
|
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 := map[string]any{"mime_type": "image/jpeg", "source_width": sourceSize.X, "source_height": 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(*req.Region, req.Width, req.Height, full.Bounds().Size())
|
|
result["source_width"], result["source_height"] = full.Bounds().Dx(), full.Bounds().Dy()
|
|
frame, applied, err = computerUseRegionFrame(full, region, maxWidth)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
blank = thumb.Blank(full)
|
|
result["region"] = applied
|
|
}
|
|
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
|
|
}
|
|
|
|
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"`
|
|
// Down holds (true) or releases (false) one key instead of pressing it.
|
|
Down *bool `json:"down"`
|
|
}
|
|
if err := json.Unmarshal(raw, &req); err != nil {
|
|
return nil, err
|
|
}
|
|
if strings.TrimSpace(req.Key) == "" {
|
|
return nil, errors.New("key is required")
|
|
}
|
|
if req.Down != nil && len(req.Modifiers) > 0 {
|
|
return nil, errors.New("a held key takes no modifiers; hold each key separately")
|
|
}
|
|
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if req.Down != nil {
|
|
err = a.consoleKeyState(ctx, route, req.Key, *req.Down)
|
|
} else {
|
|
err = a.consoleKey(ctx, route, req.Key, req.Modifiers)
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"ok": true}, nil
|
|
}
|
|
|
|
// handleComputerUseRelease lifts the given keys and pointer buttons in one
|
|
// report, so a client that stops mid-gesture never leaves input held.
|
|
func (a *App) handleComputerUseRelease(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
|
|
var req struct {
|
|
VM string `json:"vm"`
|
|
Keys []string `json:"keys"`
|
|
Buttons []string `json:"buttons"`
|
|
}
|
|
if err := json.Unmarshal(raw, &req); err != nil {
|
|
return nil, err
|
|
}
|
|
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := a.consoleRelease(ctx, route, req.Keys, req.Buttons); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"ok": true}, nil
|
|
}
|
|
|
|
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, 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 map[string]any{"characters": n}, nil
|
|
}
|