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.4 KB
Raw Blame
import ArgumentParser
import Foundation
import Virtualization

private func parseNetworkModeString(_ value: String) throws -> NetworkMode {
    guard let mode = NetworkMode.parse(value) else {
        throw ValidationError(
            "Invalid network mode '\(value)'. Expected 'nat', 'bridged', 'bridged:<interface>' or 'gateway:<socket path>'."
        )
    }
    return mode
}

struct RunVMRequest: Codable {
    let noDisplay: Bool?
    let sharedDirectories: [SharedDirectoryRequest]?
    let recoveryMode: Bool?
    let storage: String?
    let diskPath: String?
    let nvramPath: String?
    let network: String?
    let clipboard: Bool?
    /// "enabled" (default) or "disabled". Absent keeps the historic behavior of
    /// always starting a VNC server.
    let vnc: String?
    /// Guest ports to publish on host loopback ports over vsock (the VM
    /// gets a virtio socket device; the guest needs Cua's vsock agent).
    /// `get` reports the host ports under `forwards` once the agent answers.
    var forwards: [UInt16]? = nil

    struct SharedDirectoryRequest: Codable {
        let hostPath: String
        let readOnly: Bool?
    }

    func parse() throws -> [SharedDirectory] {
        guard let sharedDirectories = sharedDirectories else { return [] }

        return try sharedDirectories.map { dir -> SharedDirectory in
            // Validate that the host path exists and is a directory
            var isDirectory: ObjCBool = false
            guard FileManager.default.fileExists(atPath: dir.hostPath, isDirectory: &isDirectory),
                isDirectory.boolValue
            else {
                throw ValidationError(
                    "Host path does not exist or is not a directory: \(dir.hostPath)")
            }

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

    func parseNetworkMode() throws -> NetworkMode? {
        guard let network else {
            return nil
        }
        return try parseNetworkModeString(network)
    }

    func parseVNCPolicy() throws -> VNCPolicy {
        guard let vnc else {
            return .enabled
        }
        guard let policy = VNCPolicy(rawValue: vnc) else {
            throw ValidationError(
                "Invalid vnc policy '\(vnc)'. Expected 'enabled' or 'disabled'.")
        }
        return policy
    }

    func validatedVNCPolicy(noDisplayDefault: Bool) throws -> VNCPolicy {
        let policy = try parseVNCPolicy()
        let noDisplay = self.noDisplay ?? noDisplayDefault
        if let option = VNCPolicy.conflictingOption(
            policy: policy,
            displayMode: noDisplay ? .none : .vnc,
            vncPort: 0,
            vncPassword: nil
        ) {
            throw VMError.vncDisabledConflict(option)
        }
        return policy
    }
}

struct PullRequest: Codable {
    let image: String
    let name: String?
    var registry: String
    var organization: String
    let storage: String?

    enum CodingKeys: String, CodingKey {
        case image, name, registry, organization, storage
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        image = try container.decode(String.self, forKey: .image)
        name = try container.decodeIfPresent(String.self, forKey: .name)
        registry = try container.decodeIfPresent(String.self, forKey: .registry) ?? "ghcr.io"
        organization = try container.decodeIfPresent(String.self, forKey: .organization) ?? "trycua"
        storage = try container.decodeIfPresent(String.self, forKey: .storage)
    }
}

struct PullCancelRequest: Codable {
    let name: String
}

struct CreateVMRequest: Codable {
    let name: String
    let os: String
    let cpu: Int
    let memory: String
    let diskSize: String
    let display: String
    let ipsw: String?
    let storage: String?
    /// Preset name or YAML path for offline unattended macOS setup
    let unattended: String?
    /// Network mode: "nat" (default), "bridged", or "bridged:<interface>"
    let network: String?

    func parse() throws -> (memory: UInt64, diskSize: UInt64) {
        return (
            memory: try parseSize(memory),
            diskSize: try parseSize(diskSize)
        )
    }

    func parseNetworkMode() throws -> NetworkMode {
        guard let network else {
            return .nat
        }
        let mode = try parseNetworkModeString(network)
        try mode.checkStorable()
        return mode
    }
}

struct SetVMRequest: Codable {
    let cpu: Int?
    let memory: String?
    let diskSize: String?
    let display: String?
    let storage: String?
    let noBackup: Bool?
    let keepBackup: Bool?
    let dryRun: Bool?

    func parse() throws -> (memory: UInt64?, diskSize: UInt64?, display: VMDisplayResolution?) {
        return (
            memory: try memory.map { try parseSize($0) },
            diskSize: try diskSize.map { try parseSize($0) },
            display: try display.map {
                guard let resolution = VMDisplayResolution(string: $0) else {
                    throw ValidationError(
                        "Invalid display resolution format: \($0). Expected format: WIDTHxHEIGHT")
                }
                return resolution
            }
        )
    }
}

struct CloneRequest: Codable {
    let name: String
    let newName: String
    let sourceLocation: String?
    let destLocation: String?
    /// Clone the source's saved machine state too (`POST /lume/vms/:name/suspend`).
    let withSavedState: Bool?
}

struct RenameVMRequest: Codable {
    let newName: String
    let storage: String?
}

struct SetupVMRequest: Codable {
    let configPath: String?
    let configYaml: String?
    let storage: String?
    let vncPort: Int?
    let noDisplay: Bool?
    let debug: Bool?
    let debugDir: String?
}

struct PushRequest: Codable {
    let name: String // Name of the local VM
    let imageName: String // Base name for the image in the registry
    let tags: [String] // List of tags to push
    var registry: String // Registry URL
    var organization: String // Organization/user in the registry
    let storage: String? // Optional VM storage location or direct path
    var chunkSizeMb: Int // Chunk size
    var singleLayer: Bool // Push as single disk layer (kubelet-compatible)
    // dryRun and reassemble are less common for API, default to false?
    // verbose is usually handled by server logging

    enum CodingKeys: String, CodingKey {
        case name, imageName, tags, registry, organization, storage, chunkSizeMb, singleLayer
    }

    // Provide default values for optional fields during decoding
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        imageName = try container.decode(String.self, forKey: .imageName)
        tags = try container.decode([String].self, forKey: .tags)
        registry = try container.decodeIfPresent(String.self, forKey: .registry) ?? "ghcr.io"
        organization = try container.decodeIfPresent(String.self, forKey: .organization) ?? "trycua"
        storage = try container.decodeIfPresent(String.self, forKey: .storage)
        chunkSizeMb = try container.decodeIfPresent(Int.self, forKey: .chunkSizeMb) ?? 512
        singleLayer = try container.decodeIfPresent(Bool.self, forKey: .singleLayer) ?? false
    }
}