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.

refactor(lume): clean up config subcommand structure (#1214)

Francesco Bonaccif2356059a903
diff --git a/libs/lume/src/Commands/Config.swift b/libs/lume/src/Commands/Config.swift
index 2e49902477..1a26039ee5 100644
--- a/libs/lume/src/Commands/Config.swift
+++ b/libs/lume/src/Commands/Config.swift
@@ -6,7 +6,7 @@ struct Config: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "config",
abstract: "Get or set lume configuration",
- subcommands: [Get.self, Storage.self, Cache.self, Caching.self, Telemetry.self, Network.self],
+ subcommands: [Get.self, Storage.self, Cache.self, Telemetry.self, Registry.self, Network.self],
defaultSubcommand: Get.self
)
@@ -36,6 +36,12 @@ struct Config: ParsableCommand {
// Display telemetry status
print("Telemetry enabled: \(settings.telemetryEnabled)")
+ // Display registry info
+ if let registry = settings.registry {
+ print("Registry type: \(registry.type.rawValue)")
+ print("Registry: \(registry.ghcr.registry)/\(registry.ghcr.organization)")
+ }
+
// Display all locations
if !settings.vmLocations.isEmpty {
print("\nConfigured VM storage locations:")
@@ -63,80 +69,74 @@ struct Config: ParsableCommand {
}
}
- // MARK: - Caching Management Subcommands
+ // MARK: - Cache Management Subcommands
- struct Caching: ParsableCommand {
+ struct Cache: ParsableCommand {
static let configuration = CommandConfiguration(
- commandName: "caching",
- abstract: "Manage image caching settings",
- subcommands: [GetCaching.self, SetCaching.self]
+ commandName: "cache",
+ abstract: "Manage image cache settings",
+ subcommands: [CacheDir.self, CacheEnable.self, CacheDisable.self, CacheStatus.self],
+ defaultSubcommand: CacheStatus.self
)
- struct GetCaching: ParsableCommand {
+ struct CacheStatus: ParsableCommand {
static let configuration = CommandConfiguration(
- commandName: "get",
- abstract: "Show current caching status"
+ commandName: "status",
+ abstract: "Show cache status and directory"
)
func run() throws {
let controller = LumeController()
- let cachingEnabled = controller.isCachingEnabled()
- print("Caching enabled: \(cachingEnabled)")
+ let settings = controller.getSettings()
+ print("Caching enabled: \(settings.cachingEnabled)")
+ print("Cache directory: \(settings.cacheDirectory)")
}
}
- struct SetCaching: ParsableCommand {
+ struct CacheDir: ParsableCommand {
static let configuration = CommandConfiguration(
- commandName: "set",
- abstract: "Enable or disable image caching"
+ commandName: "dir",
+ abstract: "Get or set cache directory"
)
- @Argument(help: "Enable or disable caching (true/false)")
- var enabled: Bool
+ @Argument(help: "Path to cache directory (omit to show current)")
+ var path: String?
func run() throws {
let controller = LumeController()
- try controller.setCachingEnabled(enabled)
- print("Caching \(enabled ? "enabled" : "disabled")")
+ if let path = path {
+ try controller.setCacheDirectory(path: path)
+ print("Cache directory set to: \(path)")
+ } else {
+ let cacheDir = controller.getCacheDirectory()
+ print("Cache directory: \(cacheDir)")
+ }
}
}
- }
- // MARK: - Cache Management Subcommands
-
- struct Cache: ParsableCommand {
- static let configuration = CommandConfiguration(
- commandName: "cache",
- abstract: "Manage cache settings",
- subcommands: [GetCache.self, SetCache.self]
- )
-
- struct GetCache: ParsableCommand {
+ struct CacheEnable: ParsableCommand {
static let configuration = CommandConfiguration(
- commandName: "get",
- abstract: "Get current cache directory"
+ commandName: "enable",
+ abstract: "Enable image caching"
)
func run() throws {
let controller = LumeController()
- let cacheDir = controller.getCacheDirectory()
- print("Cache directory: \(cacheDir)")
+ try controller.setCachingEnabled(true)
+ print("Caching enabled")
}
}
- struct SetCache: ParsableCommand {
+ struct CacheDisable: ParsableCommand {
static let configuration = CommandConfiguration(
- commandName: "set",
- abstract: "Set cache directory"
+ commandName: "disable",
+ abstract: "Disable image caching"
)
- @Argument(help: "Path to cache directory")
- var path: String
-
func run() throws {
let controller = LumeController()
- try controller.setCacheDirectory(path: path)
- print("Cache directory set to: \(path)")
+ try controller.setCachingEnabled(false)
+ print("Caching disabled")
}
}
}
@@ -291,6 +291,172 @@ struct Config: ParsableCommand {
}
}
+ // MARK: - Registry Management Subcommands
+
+ struct Registry: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "registry",
+ abstract: "Manage container registry settings",
+ subcommands: [RegistryStatus.self, RegistryType_.self, GHCR.self, GCS.self],
+ defaultSubcommand: RegistryStatus.self
+ )
+
+ struct RegistryStatus: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "status",
+ abstract: "Show current registry configuration"
+ )
+
+ func run() throws {
+ let controller = LumeController()
+ let settings = controller.getSettings()
+ let registry = settings.registry ?? .defaultConfig
+
+ print("Registry type: \(registry.type.rawValue)")
+ print("")
+ print("GHCR configuration:")
+ print(" Registry: \(registry.ghcr.registry)")
+ print(" Organization: \(registry.ghcr.organization)")
+
+ if let gcs = registry.gcs {
+ print("")
+ print("GCS configuration:")
+ print(" API URL: \(gcs.apiUrl)")
+ print(" API Key: \(gcs.apiKey.prefix(8))...")
+ } else if registry.type == .gcs {
+ print("")
+ print("GCS configuration: not set")
+ print(" Run 'lume config registry gcs --api-url <url> --api-key <key>' to configure")
+ }
+ }
+ }
+
+ struct RegistryType_: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "type",
+ abstract: "Get or set registry type"
+ )
+
+ @Argument(help: "Registry type to use (ghcr, gcs). Omit to show current.")
+ var type: String?
+
+ func run() throws {
+ let settings = SettingsManager.shared.getSettings()
+
+ guard let typeStr = type else {
+ let registry = settings.registry ?? .defaultConfig
+ print("Registry type: \(registry.type.rawValue)")
+ return
+ }
+
+ guard let newType = RegistryType(rawValue: typeStr) else {
+ throw ValidationError("Invalid registry type '\(typeStr)'. Valid types: ghcr, gcs")
+ }
+
+ var updated = settings
+ var registry = updated.registry ?? .defaultConfig
+ registry.type = newType
+ updated.registry = registry
+ try SettingsManager.shared.saveSettings(updated)
+ print("Registry type set to: \(newType.rawValue)")
+ }
+ }
+
+ struct GHCR: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "ghcr",
+ abstract: "Configure GitHub Container Registry settings"
+ )
+
+ @Option(name: .long, help: "Registry URL (default: ghcr.io)")
+ var registry: String?
+
+ @Option(name: .long, help: "Organization/namespace (default: trycua)")
+ var organization: String?
+
+ func run() throws {
+ let settings = SettingsManager.shared.getSettings()
+ let currentRegistry = settings.registry ?? .defaultConfig
+
+ // If no flags, just print current
+ if registry == nil && organization == nil {
+ print("GHCR configuration:")
+ print(" Registry: \(currentRegistry.ghcr.registry)")
+ print(" Organization: \(currentRegistry.ghcr.organization)")
+ return
+ }
+
+ var updated = settings
+ var reg = updated.registry ?? .defaultConfig
+ if let registry = registry {
+ reg.ghcr.registry = registry
+ }
+ if let organization = organization {
+ reg.ghcr.organization = organization
+ }
+ updated.registry = reg
+ try SettingsManager.shared.saveSettings(updated)
+
+ print("GHCR configuration updated:")
+ print(" Registry: \(reg.ghcr.registry)")
+ print(" Organization: \(reg.ghcr.organization)")
+ }
+ }
+
+ struct GCS: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "gcs",
+ abstract: "Configure GCS registry settings"
+ )
+
+ @Option(name: .long, help: "API URL for signed URL generation")
+ var apiUrl: String?
+
+ @Option(name: .long, help: "API key for authentication")
+ var apiKey: String?
+
+ func run() throws {
+ let settings = SettingsManager.shared.getSettings()
+ let currentRegistry = settings.registry ?? .defaultConfig
+
+ // If no flags, just print current
+ if apiUrl == nil && apiKey == nil {
+ if let gcs = currentRegistry.gcs {
+ print("GCS configuration:")
+ print(" API URL: \(gcs.apiUrl)")
+ print(" API Key: \(gcs.apiKey.prefix(8))...")
+ } else {
+ print("GCS configuration: not set")
+ print(" Use --api-url and --api-key to configure")
+ }
+ return
+ }
+
+ var updated = settings
+ var reg = updated.registry ?? .defaultConfig
+ let currentGcs = reg.gcs ?? GCSConfig(apiUrl: "", apiKey: "")
+
+ let newApiUrl = apiUrl ?? currentGcs.apiUrl
+ let newApiKey = apiKey ?? currentGcs.apiKey
+
+ if newApiUrl.isEmpty {
+ throw ValidationError("API URL is required. Use --api-url <url>")
+ }
+ if newApiKey.isEmpty {
+ throw ValidationError("API key is required. Use --api-key <key>")
+ }
+
+ reg.gcs = GCSConfig(apiUrl: newApiUrl, apiKey: newApiKey)
+ updated.registry = reg
+ try SettingsManager.shared.saveSettings(updated)
+
+ print("GCS configuration updated:")
+ print(" API URL: \(newApiUrl)")
+ print(" API Key: \(newApiKey.prefix(8))...")
+ }
+ }
+ }
+
// MARK: - Network Management Subcommands
struct Network: ParsableCommand {
diff --git a/libs/lume/src/Commands/Pull.swift b/libs/lume/src/Commands/Pull.swift
index 497082056c..da728d38d5 100644
--- a/libs/lume/src/Commands/Pull.swift
+++ b/libs/lume/src/Commands/Pull.swift
@@ -22,6 +22,15 @@ struct Pull: AsyncParsableCommand {
@Option(name: .customLong("storage"), help: "VM storage location to use or direct path to VM location")
var storage: String?
+ @Option(name: .long, help: "Registry username for authentication")
+ var username: String?
+
+ @Option(name: .long, help: "Registry password for authentication")
+ var password: String?
+
+ @Flag(name: .long, help: "Force re-download even if image exists")
+ var force: Bool = false
+
@Flag(name: .long, help: "Enable verbose logging")
var verbose: Bool = false
@@ -43,7 +52,10 @@ struct Pull: AsyncParsableCommand {
name: name,
registry: registry,
organization: organization,
- storage: storage
+ storage: storage,
+ username: username,
+ password: password,
+ force: force
)
}
}
diff --git a/libs/lume/src/ContainerRegistry/GCSImageRegistry.swift b/libs/lume/src/ContainerRegistry/GCSImageRegistry.swift
index 19f5b53ef7..f44df41e91 100644
--- a/libs/lume/src/ContainerRegistry/GCSImageRegistry.swift
+++ b/libs/lume/src/ContainerRegistry/GCSImageRegistry.swift
@@ -30,7 +30,8 @@ class GCSImageRegistry: ImageRegistry, @unchecked Sendable {
func pull(
image: String,
name: String?,
- locationName: String?
+ locationName: String?,
+ force: Bool = false
) async throws -> VMDirectory {
// Parse image name and tag
let components = image.split(separator: ":")
diff --git a/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swift b/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swift
index ae5cf6c66a..86b7982595 100644
--- a/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swift
+++ b/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swift
@@ -471,6 +471,8 @@ actor TaskCounter {
class ImageContainerRegistry: ImageRegistry, @unchecked Sendable {
private let registry: String
private let organization: String
+ private let username: String?
+ private let password: String?
private let downloadProgress = ProgressTracker() // Renamed for clarity
private let uploadProgress = UploadProgressTracker() // Added upload tracker
private let cacheDirectory: URL
@@ -493,9 +495,11 @@ class ImageContainerRegistry: ImageRegistry, @unchecked Sendable {
return "[\(completed)\(remaining)]"
}
- init(registry: String, organization: String) {
+ init(registry: String, organization: String, username: String? = nil, password: String? = nil) {
self.registry = registry
self.organization = organization
+ self.username = username
+ self.password = password
// Get cache directory from settings
let cacheDir = SettingsManager.shared.getCacheDirectory()
@@ -761,7 +765,8 @@ class ImageContainerRegistry: ImageRegistry, @unchecked Sendable {
public func pull(
image: String,
name: String?,
- locationName: String? = nil
+ locationName: String? = nil,
+ force: Bool = false
) async throws -> VMDirectory {
guard !image.isEmpty else {
throw ValidationError("Image name cannot be empty")
@@ -784,6 +789,25 @@ class ImageContainerRegistry: ImageRegistry, @unchecked Sendable {
vmDir = try home.getVMDirectory(vmName, storage: locationName)
}
+ // Check if image is already cached with all required files
+ let manifestDigestPath = vmDir.dir.url.appendingPathComponent(".manifest-digest")
+ if !force
+ && vmDir.exists()
+ && vmDir.diskPath.exists()
+ && vmDir.nvramPath.exists()
+ && vmDir.configPath.exists()
+ && FileManager.default.fileExists(atPath: manifestDigestPath.path)
+ {
+ Logger.info("Image already cached, skipping download")
+ return vmDir
+ }
+
+ // If force is set and directory exists, remove it before re-downloading
+ if force && vmDir.exists() {
+ Logger.info("Force flag set, removing existing VM directory")
+ try FileManager.default.removeItem(at: vmDir.dir.url)
+ }
+
// Optimize network early in the process
optimizeNetworkSettings()
@@ -1131,6 +1155,10 @@ class ImageContainerRegistry: ImageRegistry, @unchecked Sendable {
try? cleanupCacheEntry(manifestId: manifestId)
}
+ // Write manifest digest to mark this as a complete cached image
+ let digestFilePath = URL(fileURLWithPath: vmDir.dir.path).appendingPathComponent(".manifest-digest")
+ try manifestDigest.write(to: digestFilePath, atomically: true, encoding: .utf8)
+
Logger.debug("Download complete: Files extracted to \(vmDir.dir.path)")
Logger.debug(
"Note: Actual disk usage is significantly lower than reported size due to macOS sparse file system"
@@ -3799,6 +3827,11 @@ class ImageContainerRegistry: ImageRegistry, @unchecked Sendable {
}
private func getCredentialsFromEnvironment() -> (String?, String?) {
+ // Prefer explicit credentials over environment variables
+ if let username = self.username, let password = self.password,
+ !username.isEmpty, !password.isEmpty {
+ return (username, password)
+ }
let username =
ProcessInfo.processInfo.environment["GITHUB_USERNAME"]
?? ProcessInfo.processInfo.environment["GHCR_USERNAME"]
diff --git a/libs/lume/src/ContainerRegistry/ImageRegistry.swift b/libs/lume/src/ContainerRegistry/ImageRegistry.swift
index 1dd3e2fcf1..32f0afec60 100644
--- a/libs/lume/src/ContainerRegistry/ImageRegistry.swift
+++ b/libs/lume/src/ContainerRegistry/ImageRegistry.swift
@@ -7,11 +7,13 @@ protocol ImageRegistry: Sendable {
/// - image: Image reference (format: name:tag)
/// - name: Optional VM name (defaults to image name without tag)
/// - locationName: Optional storage location name or direct path
+ /// - force: Force re-download even if image exists locally
/// - Returns: The VM directory where the image was pulled
func pull(
image: String,
name: String?,
- locationName: String?
+ locationName: String?,
+ force: Bool
) async throws -> VMDirectory
/// Push a VM to the registry
@@ -42,8 +44,8 @@ protocol ImageRegistry: Sendable {
// Default implementations for optional parameters
extension ImageRegistry {
- func pull(image: String, name: String? = nil, locationName: String? = nil) async throws -> VMDirectory {
- try await pull(image: image, name: name, locationName: locationName)
+ func pull(image: String, name: String? = nil, locationName: String? = nil, force: Bool = false) async throws -> VMDirectory {
+ try await pull(image: image, name: name, locationName: locationName, force: force)
}
func push(
diff --git a/libs/lume/src/ContainerRegistry/RegistryFactory.swift b/libs/lume/src/ContainerRegistry/RegistryFactory.swift
index 0aa874f436..a5bad61197 100644
--- a/libs/lume/src/ContainerRegistry/RegistryFactory.swift
+++ b/libs/lume/src/ContainerRegistry/RegistryFactory.swift
@@ -19,7 +19,9 @@ struct RegistryFactory {
/// - Otherwise, use the registry type from settings (ghcr or gcs)
static func createRegistry(
registry: String? = nil,
- organization: String? = nil
+ organization: String? = nil,
+ username: String? = nil,
+ password: String? = nil
) throws -> any ImageRegistry {
let settings = SettingsManager.shared.getSettings()
let config = settings.registry ?? .defaultConfig
@@ -32,7 +34,7 @@ struct RegistryFactory {
if hasCliOverride {
let registryURL = registry ?? defaultGHCRRegistry
let org = organization ?? defaultGHCROrganization
- return ImageContainerRegistry(registry: registryURL, organization: org)
+ return ImageContainerRegistry(registry: registryURL, organization: org, username: username, password: password)
}
// Otherwise use configured registry type
@@ -40,7 +42,9 @@ struct RegistryFactory {
case .ghcr:
return ImageContainerRegistry(
registry: config.ghcr.registry,
- organization: config.ghcr.organization
+ organization: config.ghcr.organization,
+ username: username,
+ password: password
)
case .gcs:
diff --git a/libs/lume/src/FileSystem/Home.swift b/libs/lume/src/FileSystem/Home.swift
index aa32ef0224..8fd741e752 100644
--- a/libs/lume/src/FileSystem/Home.swift
+++ b/libs/lume/src/FileSystem/Home.swift
@@ -1,3 +1,4 @@
+import Darwin
import Foundation
/// Manages the application's home directory and virtual machine directories.
@@ -221,6 +222,84 @@ final class Home {
}
}
+ /// Clones a VM directory using APFS clonefile for disk.img and regular copy for small files
+ /// - Parameters:
+ /// - sourceName: Name of the source VM
+ /// - destName: Name for the destination VM
+ /// - sourceLocation: Optional name of the source location
+ /// - destLocation: Optional name of the destination location
+ /// - Throws: HomeError if the clone operation fails
+ func cloneVMDirectory(
+ from sourceName: String,
+ to destName: String,
+ sourceLocation: String? = nil,
+ destLocation: String? = nil
+ ) throws {
+ let sourceDir = try getVMDirectory(sourceName, storage: sourceLocation)
+ let destDir = try getVMDirectory(destName, storage: destLocation)
+
+ // Check if destination directory exists at all
+ if destDir.exists() {
+ throw HomeError.directoryAlreadyExists(path: destDir.dir.path)
+ }
+
+ // Create the destination directory
+ do {
+ try fileManager.createDirectory(
+ atPath: destDir.dir.path,
+ withIntermediateDirectories: true
+ )
+ } catch {
+ throw HomeError.directoryCreationFailed(path: destDir.dir.path)
+ }
+
+ // Enumerate files in the source directory and copy/clone each one
+ let sourceURL = sourceDir.dir.url
+ let destURL = destDir.dir.url
+ let contents: [URL]
+ do {
+ contents = try fileManager.contentsOfDirectory(
+ at: sourceURL,
+ includingPropertiesForKeys: nil
+ )
+ } catch {
+ throw HomeError.directoryCreationFailed(path: sourceDir.dir.path)
+ }
+
+ for fileURL in contents {
+ let fileName = fileURL.lastPathComponent
+ let destFileURL = destURL.appendingPathComponent(fileName)
+
+ if fileName == "disk.img" {
+ // Use clonefile(2) for disk.img (instant APFS copy-on-write)
+ let result = Darwin.clonefile(
+ fileURL.path,
+ destFileURL.path,
+ 0
+ )
+ if result != 0 {
+ // Fallback to regular copy if clonefile fails (e.g., cross-volume)
+ Logger.info(
+ "clonefile failed for disk.img, falling back to regular copy",
+ metadata: ["errno": "\(errno)"]
+ )
+ do {
+ try fileManager.copyItem(at: fileURL, to: destFileURL)
+ } catch {
+ throw HomeError.directoryCreationFailed(path: destDir.dir.path)
+ }
+ }
+ } else {
+ // Regular copy for small files (config.json, nvram.bin, etc.)
+ do {
+ try fileManager.copyItem(at: fileURL, to: destFileURL)
+ } catch {
+ throw HomeError.directoryCreationFailed(path: destDir.dir.path)
+ }
+ }
+ }
+ }
+
// MARK: - Location Management
/// Adds a new VM location
diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swift
index b17434c0fe..3af7c8a30c 100644
--- a/libs/lume/src/LumeController.swift
+++ b/libs/lume/src/LumeController.swift
@@ -278,8 +278,8 @@ final class LumeController {
// VM not found is okay, we'll create it
}
- // Copy the VM directory
- try home.copyVMDirectory(
+ // Clone the VM directory (uses APFS clonefile for disk.img)
+ try home.cloneVMDirectory(
from: normalizedName,
to: normalizedNewName,
sourceLocation: sourceLocation,
@@ -1065,7 +1065,10 @@ final class LumeController {
name: String?,
registry: String,
organization: String,
- storage: String? = nil
+ storage: String? = nil,
+ username: String? = nil,
+ password: String? = nil,
+ force: Bool = false
) async throws {
do {
// Split the image to get name and tag
@@ -1095,15 +1098,18 @@ final class LumeController {
name: vmName,
registry: registry,
organization: organization,
- storage: storage
+ storage: storage,
+ force: force
)
let imageRegistry = try RegistryFactory.createRegistry(
- registry: registry, organization: organization)
+ registry: registry, organization: organization,
+ username: username, password: password)
let _ = try await imageRegistry.pull(
image: image,
name: vmName,
- locationName: storage)
+ locationName: storage,
+ force: force)
Logger.debug(
"Setting new VM mac address",
@@ -1524,7 +1530,8 @@ final class LumeController {
name: String,
registry: String,
organization: String,
- storage: String? = nil
+ storage: String? = nil,
+ force: Bool = false
) throws {
guard !image.isEmpty else {
throw ValidationError("Image name cannot be empty")
@@ -1554,15 +1561,15 @@ final class LumeController {
throw HomeError.directoryCreationFailed(path: storage)
}
}
-
+
// Use getVMDirectoryFromPath for direct paths
vmDir = try home.getVMDirectoryFromPath(name, storagePath: storage)
} else {
// Use getVMDirectory for named storage locations
vmDir = try home.getVMDirectory(name, storage: storage)
}
-
- if vmDir.exists() {
+
+ if vmDir.exists() && !force {
throw VMError.alreadyExists(name)
}
}