Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

7.9 KB
Raw Blame
import ArgumentParser
import Foundation
import Virtualization

struct Run: AsyncParsableCommand {
    static let configuration = CommandConfiguration(
        abstract: "Run a virtual machine"
    )

    @Argument(
        help: "Name of the virtual machine or image to pull and run (format: name or name:tag)",
        completion: .custom(completeVMName))
    var name: String

    @Option(
        help: "Local viewer to open: 'vnc', 'native', or 'none'. The VNC server remains available in every mode."
    )
    var display: DisplayMode = .native

    @Flag(
        name: [.customShort("d"), .customLong("no-display")],
        help: "Compatibility alias for --display none"
    )
    var noDisplay: Bool = false

    @Flag(
        name: .customLong("detach"),
        help: "Run the VM in the background and return immediately"
    )
    var detach: Bool = false

    @Option(
        name: .customLong("log-file"),
        help: "Log path for --detach (default: ~/Library/Logs/lume/{vm}.log)"
    )
    var logFile: String?

    @Option(
        name: [.customLong("shared-dir")],
        help:
            "Directory to share with the VM. Can be just a path for read-write access (e.g. ~/src) or path:tag where tag is 'ro' for read-only or 'rw' for read-write (e.g. ~/src:ro)"
    )
    var sharedDirectories: [String] = []

    @Option(
        help:
            "For Linux VMs only, a read-only disk image to attach to the VM (e.g. --mount=\"ubuntu.iso\")",
        completion: .file())
    var mount: String?

    @Option(
        name: [.customLong("usb-storage")],
        help: "Disk image to attach as a USB mass storage device (e.g. --usb-storage=\"disk.img\")",
        completion: .file())
    var usbStorageDevices: [String] = []

    @Option(
        name: [.customLong("disk")],
        help: "Disk image to attach as a read-write virtio-blk device (e.g. --disk=\"scratch.img\")",
        completion: .file())
    var additionalDisks: [String] = []

    @Option(help: "Github Container Registry to pull the images from. Defaults to ghcr.io")
    var registry: String = "ghcr.io"

    @Option(help: "Organization to pull the images from. Defaults to trycua")
    var organization: String = "trycua"

    @Option(
        name: .customLong("vnc"),
        help:
            "VNC server policy: 'enabled' (default) or 'disabled'. 'disabled' starts the VM with no VNC listener and reports a null vncUrl."
    )
    var vnc: VNCPolicy = .enabled

    @Option(
        name: [.customLong("vnc-port")],
        help: "Port to use for the VNC server. Defaults to 0 (auto-assign)")
    var vncPort: Int = 0

    @Option(
        name: [.customLong("vnc-password")],
        help: "Password for the VNC server. Defaults to a random passphrase")
    var vncPassword: String?

    @Option(help: "For MacOS VMs only, boot into the VM in recovery mode")
    var recoveryMode: Bool = false

    @Option(name: .customLong("storage"), help: "VM storage location to use or direct path to VM location")
    var storage: String?

    @Option(
        name: .customLong("disk-path"),
        help: "Override path to disk image file. When set, uses this file instead of the default disk.img in the VM directory.",
        completion: .file())
    var diskPath: String?

    @Option(
        name: .customLong("nvram-path"),
        help: "Override path to NVRAM file. When set, uses this file instead of the default nvram.bin in the VM directory.",
        completion: .file())
    var nvramPath: String?

    @Option(
        name: .customLong("network"),
        help: "Optional network override: 'nat', 'bridged', 'bridged:<interface>' (e.g. 'bridged:en0'), or 'gateway:<socket path>' (a Cua network gateway's datagram socket). Defaults to the VM's configured mode.")
    var network: String?

    @Flag(
        name: .customLong("clipboard"),
        help: "Enable bidirectional clipboard sync via SSH. This is automatic for native macOS display."
    )
    var clipboard: Bool = false

    private var parsedNetworkMode: NetworkMode? {
        get throws {
            guard let network else {
                return nil
            }
            guard let mode = NetworkMode.parse(network) else {
                throw ValidationError(
                    "Invalid network mode '\(network)'. Expected 'nat', 'bridged', 'bridged:<interface>' or 'gateway:<socket path>'."
                )
            }
            return mode
        }
    }

    private var parsedSharedDirectories: [SharedDirectory] {
        get throws {
            try sharedDirectories.map { dirString -> SharedDirectory in
                let components = dirString.split(separator: ":", maxSplits: 1)
                let hostPath = String(components[0])

                // If no tag is provided, default to read-write
                if components.count == 1 {
                    return SharedDirectory(
                        hostPath: hostPath,
                        tag: VZVirtioFileSystemDeviceConfiguration.macOSGuestAutomountTag,
                        readOnly: false
                    )
                }

                // Parse the tag if provided
                let tag = String(components[1])
                let readOnly: Bool
                switch tag.lowercased() {
                case "ro":
                    readOnly = true
                case "rw":
                    readOnly = false
                default:
                    throw ValidationError(
                        "Invalid tag value. Must be either 'ro' for read-only or 'rw' for read-write"
                    )
                }

                return SharedDirectory(
                    hostPath: hostPath,
                    tag: VZVirtioFileSystemDeviceConfiguration.macOSGuestAutomountTag,
                    readOnly: readOnly
                )
            }
        }
    }

    private var parsedUSBStorageDevices: [Path] {
        usbStorageDevices.map { Path($0) }
    }

    private var parsedAdditionalDisks: [Path] {
        additionalDisks.map { Path($0) }
    }

    init() {
    }

    func validate() throws {
        if let option = VNCPolicy.conflictingOption(
            policy: vnc,
            displayMode: DisplayMode.resolve(requested: display, noDisplay: noDisplay),
            vncPort: vncPort,
            vncPassword: vncPassword
        ) {
            throw ValidationError(
                "'--vnc disabled' starts no VNC server, so it cannot be combined with '\(option)'.")
        }
    }

    @MainActor
    func run() async throws {
        if detach {
            let result = try DetachedVMRunner.launch(vmName: name, logPath: logFile)
            print("Started '\(name)' in the background (PID \(result.processIdentifier)).")
            print("Log: \(result.logURL.path)")
            return
        }

        // Record telemetry
        let displayMode = DisplayMode.resolve(requested: display, noDisplay: noDisplay)
        TelemetryClient.shared.record(event: TelemetryEvent.run, properties: [
            "headless": displayMode == .none
        ])

        try await runVM(displayMode: displayMode)
    }

    @MainActor
    private func runVM(displayMode: DisplayMode) async throws {
        try await LumeController().runVM(
            name: name,
            noDisplay: noDisplay,
            displayMode: displayMode,
            sharedDirectories: parsedSharedDirectories,
            mount: mount.map { Path($0) },
            registry: registry,
            organization: organization,
            vncPort: vncPort,
            vncPassword: vncPassword,
            recoveryMode: recoveryMode,
            storage: storage,
            diskPath: diskPath.map { Path($0) },
            nvramPath: nvramPath.map { Path($0) },
            usbMassStoragePaths: parsedUSBStorageDevices.isEmpty ? nil : parsedUSBStorageDevices,
            additionalDiskPaths: parsedAdditionalDisks.isEmpty ? nil : parsedAdditionalDisks,
            networkMode: parsedNetworkMode,
            clipboard: clipboard,
            vncPolicy: vnc
        )
    }
}