Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
Add flexible location commands
f-trycuaae7441d3b5a6
diff --git a/libs/lume/src/Commands/Config.swift b/libs/lume/src/Commands/Config.swiftnew file mode 100644index 0000000000..a3de1aac50--- /dev/null+++ b/libs/lume/src/Commands/Config.swift@@ -0,0 +1,167 @@+import ArgumentParser+import Foundation++struct Config: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "config",+ abstract: "Get or set lume configuration",+ subcommands: [Get.self, Location.self, Cache.self],+ defaultSubcommand: Get.self+ )++ // MARK: - Basic Configuration Subcommands++ struct Get: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "get",+ abstract: "Get current configuration"+ )++ func run() throws {+ let controller = LumeController()+ let settings = controller.getSettings()++ // Display default location+ print(+ "Default VM location: \(settings.defaultLocationName) (\(settings.defaultLocation?.path ?? "not set"))"+ )++ // Display cache directory+ print("Cache directory: \(settings.cacheDirectory)")++ // Display all locations+ if !settings.vmLocations.isEmpty {+ print("\nConfigured VM locations:")+ for location in settings.sortedLocations {+ let isDefault = location.name == settings.defaultLocationName+ let defaultMark = isDefault ? " (default)" : ""+ print(" - \(location.name): \(location.path)\(defaultMark)")+ }+ }+ }+ }++ // 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 {+ static let configuration = CommandConfiguration(+ commandName: "get",+ abstract: "Get current cache directory"+ )++ func run() throws {+ let controller = LumeController()+ let cacheDir = controller.getCacheDirectory()+ print("Cache directory: \(cacheDir)")+ }+ }++ struct SetCache: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "set",+ abstract: "Set cache directory"+ )++ @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)")+ }+ }+ }++ // MARK: - Location Management Subcommands++ struct Location: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "location",+ abstract: "Manage VM locations",+ subcommands: [Add.self, Remove.self, List.self, Default.self]+ )++ struct Add: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "add",+ abstract: "Add a new VM location"+ )++ @Argument(help: "Location name (alphanumeric with dashes/underscores)")+ var name: String++ @Argument(help: "Path to VM location directory")+ var path: String++ func run() throws {+ let controller = LumeController()+ try controller.addLocation(name: name, path: path)+ print("Added VM location: \(name) at \(path)")+ }+ }++ struct Remove: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "remove",+ abstract: "Remove a VM location"+ )++ @Argument(help: "Location name to remove")+ var name: String++ func run() throws {+ let controller = LumeController()+ try controller.removeLocation(name: name)+ print("Removed VM location: \(name)")+ }+ }++ struct List: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "list",+ abstract: "List all VM locations"+ )++ func run() throws {+ let controller = LumeController()+ let settings = controller.getSettings()++ if settings.vmLocations.isEmpty {+ print("No VM locations configured")+ return+ }++ print("VM Locations:")+ for location in settings.sortedLocations {+ let isDefault = location.name == settings.defaultLocationName+ let defaultMark = isDefault ? " (default)" : ""+ print(" - \(location.name): \(location.path)\(defaultMark)")+ }+ }+ }++ struct Default: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "default",+ abstract: "Set the default VM location"+ )++ @Argument(help: "Location name to set as default")+ var name: String++ func run() throws {+ let controller = LumeController()+ try controller.setDefaultLocation(name: name)+ print("Set default VM location to: \(name)")+ }+ }+ }+}diff --git a/libs/lume/src/Commands/Create.swift b/libs/lume/src/Commands/Create.swiftindex 2e0f0150e0..8ca51b9911 100644--- a/libs/lume/src/Commands/Create.swift+++ b/libs/lume/src/Commands/Create.swift@@ -8,45 +8,56 @@ struct Create: AsyncParsableCommand {static let configuration = CommandConfiguration(abstract: "Create a new virtual machine")-+@Argument(help: "Name for the virtual machine")var name: String- @Option(help: "Operating system to install. Defaults to macOS.", completion: .list(["macOS", "linux"]))+ @Option(+ help: "Operating system to install. Defaults to macOS.",+ completion: .list(["macOS", "linux"]))var os: String = "macOS"-+@Option(help: "Number of CPU cores", transform: { Int($0) ?? 4 })var cpu: Int = 4-- @Option(help: "Memory size, e.g., 8192MB or 8GB. Defaults to 8GB.", transform: { try parseSize($0) })++ @Option(+ help: "Memory size, e.g., 8192MB or 8GB. Defaults to 8GB.", transform: { try parseSize($0) }+ )var memory: UInt64 = 8 * 1024 * 1024 * 1024-- @Option(help: "Disk size, e.g., 20480MB or 20GB. Defaults to 50GB.", transform: { try parseSize($0) })++ @Option(+ help: "Disk size, e.g., 20480MB or 20GB. Defaults to 50GB.",+ transform: { try parseSize($0) })var diskSize: UInt64 = 50 * 1024 * 1024 * 1024@Option(help: "Display resolution in format WIDTHxHEIGHT. Defaults to 1024x768.")var display: VMDisplayResolution = VMDisplayResolution(string: "1024x768")!@Option(- help: "Path to macOS restore image (IPSW), or 'latest' to download the latest supported version. Required for macOS VMs.",+ help:+ "Path to macOS restore image (IPSW), or 'latest' to download the latest supported version. Required for macOS VMs.",completion: .file(extensions: ["ipsw"]))var ipsw: String?-++ @Option(name: .customLong("location"), help: "VM location to use")+ var location: String?+init() {}-+@MainActorfunc run() async throws {- let vmController = LumeController()- try await vmController.create(+ let controller = LumeController()+ try await controller.create(name: name,os: os,diskSize: diskSize,cpuCount: cpu,memorySize: memory,display: display.string,- ipsw: ipsw+ ipsw: ipsw,+ locationName: location)}-}\ No newline at end of file+}diff --git a/libs/lume/src/Commands/Pull.swift b/libs/lume/src/Commands/Pull.swiftindex 98d74eeddf..d56f16536f 100644--- a/libs/lume/src/Commands/Pull.swift+++ b/libs/lume/src/Commands/Pull.swift@@ -5,11 +5,12 @@ struct Pull: AsyncParsableCommand {static let configuration = CommandConfiguration(abstract: "Pull a macOS image from GitHub Container Registry")-+@Argument(help: "Image to pull (format: name:tag)")var image: String-- @Argument(help: "Name for the VM (defaults to image name without tag)", transform: { Optional($0) })++ @Argument(+ help: "Name for the VM (defaults to image name without tag)", transform: { Optional($0) })var name: String?@Option(help: "Github Container Registry to pull from. Defaults to ghcr.io")@@ -18,14 +19,20 @@ struct Pull: AsyncParsableCommand {@Option(help: "Organization to pull from. Defaults to trycua")var organization: String = "trycua"- @Flag(help: "Pull image without creating .cache. Defaults to false")- var noCache: Bool = false+ @Option(name: .customLong("location"), help: "VM location to use")+ var location: String?init() {}-+@MainActorfunc run() async throws {- let vmController = LumeController()- try await vmController.pullImage(image: image, name: name, registry: registry, organization: organization, noCache: noCache)+ let controller = LumeController()+ try await controller.pullImage(+ image: image,+ name: name,+ registry: registry,+ organization: organization,+ locationName: location+ )}}diff --git a/libs/lume/src/Commands/Run.swift b/libs/lume/src/Commands/Run.swiftindex e94ae7d305..c2f026ff4a 100644--- a/libs/lume/src/Commands/Run.swift+++ b/libs/lume/src/Commands/Run.swift@@ -6,37 +6,51 @@ 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))++ @Argument(+ help: "Name of the virtual machine or image to pull and run (format: name or name:tag)",+ completion: .custom(completeVMName))var name: String-+@Flag(name: [.short, .long], help: "Do not start the VNC client")var noDisplay: Bool = false-- @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)")++ @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: Path?-+ @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(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-port")], help: "Port to use for the VNC server. Defaults to 0 (auto-assign)")++ @Option(+ name: [.customLong("vnc-port")],+ help: "Port to use for the VNC server. Defaults to 0 (auto-assign)")var vncPort: Int = 0@Option(help: "For MacOS VMs only, boot into the VM in recovery mode")var recoveryMode: Bool = false+ @Option(name: .customLong("location"), help: "VM location to use")+ var location: String?+private var parsedSharedDirectories: [SharedDirectory] {get throws {try sharedDirectories.map { dirString -> SharedDirectory inlet components = dirString.split(separator: ":", maxSplits: 1)let hostPath = String(components[0])-+// If no tag is provided, default to read-writeif components.count == 1 {return SharedDirectory(@@ -45,7 +59,7 @@ struct Run: AsyncParsableCommand {readOnly: false)}-+// Parse the tag if providedlet tag = String(components[1])let readOnly: Bool@@ -55,9 +69,11 @@ struct Run: AsyncParsableCommand {case "rw":readOnly = falsedefault:- throw ValidationError("Invalid tag value. Must be either 'ro' for read-only or 'rw' for read-write")+ throw ValidationError(+ "Invalid tag value. Must be either 'ro' for read-only or 'rw' for read-write"+ )}-+return SharedDirectory(hostPath: hostPath,tag: VZVirtioFileSystemDeviceConfiguration.macOSGuestAutomountTag,@@ -66,24 +82,22 @@ struct Run: AsyncParsableCommand {}}}-+init() {}@MainActorfunc run() async throws {- let vmController = LumeController()- let dirs = try parsedSharedDirectories-- try await vmController.runVM(+ try await LumeController().runVM(name: name,noDisplay: noDisplay,- sharedDirectories: dirs,- mount: mount,+ sharedDirectories: parsedSharedDirectories,+ mount: mount.map { Path($0) },registry: registry,organization: organization,vncPort: vncPort,- recoveryMode: recoveryMode+ recoveryMode: recoveryMode,+ locationName: location)}}diff --git a/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swift b/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swiftindex 83d1d99695..95e72cec6a 100644--- a/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swift+++ b/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swift@@ -81,9 +81,12 @@ class ImageContainerRegistry: @unchecked Sendable {self.registry = registryself.organization = organization- // Setup cache directory in user's home- let home = FileManager.default.homeDirectoryForCurrentUser- self.cacheDirectory = home.appendingPathComponent(".lume/cache/ghcr")+ // Get cache directory from settings+ let cacheDir = SettingsManager.shared.getCacheDirectory()+ let expandedCacheDir = (cacheDir as NSString).expandingTildeInPath+ self.cacheDirectory = URL(fileURLWithPath: expandedCacheDir)+ .appendingPathComponent("ghcr")+try? FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)@@ -241,22 +244,39 @@ class ImageContainerRegistry: @unchecked Sendable {}}- func pull(image: String, name: String?, noCache: Bool = false) async throws {- // Validate home directory+ public func pull(+ image: String,+ name: String?,+ locationName: String? = nil+ ) async throws {+ guard !image.isEmpty else {+ throw ValidationError("Image name cannot be empty")+ }+let home = Home()- try home.validateHomeDirectory()// Use provided name or derive from imagelet vmName = name ?? image.split(separator: ":").first.map(String.init) ?? ""- let vmDir = home.getVMDirectory(vmName)+ let vmDir = try home.getVMDirectory(vmName, locationName: locationName)// Parse image name and taglet components = image.split(separator: ":")- guard components.count == 2 else {- throw PullError.invalidImageFormat+ guard components.count == 2, let tag = components.last else {+ throw ValidationError("Invalid image format. Expected format: name:tag")}- let imageName = String(components[0])- let tag = String(components[1])++ let imageName = String(components.first!)+ let imageTag = String(tag)++ Logger.info(+ "Pulling image",+ metadata: [+ "image": image,+ "name": vmName,+ "location": locationName ?? "default",+ "registry": registry,+ "organization": organization,+ ])// Get anonymous tokenLogger.info("Getting registry authentication token")@@ -266,7 +286,7 @@ class ImageContainerRegistry: @unchecked Sendable {Logger.info("Fetching Image manifest")let (manifest, manifestDigest): (Manifest, String) = try await fetchManifest(repository: "\(self.organization)/\(imageName)",- tag: tag,+ tag: imageTag,token: token)@@ -290,30 +310,24 @@ class ImageContainerRegistry: @unchecked Sendable {// Check if we have a valid cached version and noCache is falseLogger.info("Checking cache for manifest ID: \(manifestId)")- if !noCache && validateCache(manifest: manifest, manifestId: manifestId) {+ if validateCache(manifest: manifest, manifestId: manifestId) {Logger.info("Using cached version of image")try await copyFromCache(manifest: manifest, manifestId: manifestId, to: tempVMDir)} else {// Clean up old versions of this repository before setting up new cache- if !noCache {- try cleanupOldVersions(currentManifestId: manifestId, image: imageName)- }-- if noCache {- Logger.info("Skipping cache setup due to noCache option")- } else {- Logger.info("Cache miss or invalid cache, setting up new cache")- // Setup new cache directory- try setupImageCache(manifestId: manifestId)- // Save new manifest- try saveManifest(manifest, manifestId: manifestId)-- // Save image metadata- try saveImageMetadata(- image: imageName,- manifestId: manifestId- )- }+ try cleanupOldVersions(currentManifestId: manifestId, image: imageName)++ Logger.info("Cache miss or invalid cache, setting up new cache")+ // Setup new cache directory+ try setupImageCache(manifestId: manifestId)+ // Save new manifest+ try saveManifest(manifest, manifestId: manifestId)++ // Save image metadata+ try saveImageMetadata(+ image: imageName,+ manifestId: manifestId+ )// Create temporary directory for new downloadslet tempDownloadDir = FileManager.default.temporaryDirectory.appendingPathComponent(@@ -372,7 +386,7 @@ class ImageContainerRegistry: @unchecked Sendable {let size = layer.size// For memory-optimized mode - point directly to cache when possible- if !noCache && memoryConstrained+ if memoryConstrained&& FileManager.default.fileExists(atPath: cachedLayer.path){// Use the cached file directly@@ -394,14 +408,12 @@ class ImageContainerRegistry: @unchecked Sendable {group.addTask { @Sendable [self] inawait counter.increment()- if !noCache- && FileManager.default.fileExists(atPath: cachedLayer.path)- {+ if FileManager.default.fileExists(atPath: cachedLayer.path) {try FileManager.default.copyItem(at: cachedLayer, to: partURL)await progress.addProgress(Int64(size))} else {// Check if this layer is already being downloaded and we're not skipping cache- if !noCache && isDownloading(digest) {+ if isDownloading(digest) {try await waitForExistingDownload(digest, cachedLayer: cachedLayer)if FileManager.default.fileExists(atPath: cachedLayer.path)@@ -414,9 +426,7 @@ class ImageContainerRegistry: @unchecked Sendable {}// Start new download- if !noCache {- markDownloadStarted(digest)- }+ markDownloadStarted(digest)try await self.downloadLayer(repository: "\(self.organization)/\(imageName)",@@ -429,15 +439,12 @@ class ImageContainerRegistry: @unchecked Sendable {)// Cache the downloaded layer if not in noCache mode- if !noCache {- if FileManager.default.fileExists(atPath: cachedLayer.path)- {- try FileManager.default.removeItem(at: cachedLayer)- }- try FileManager.default.copyItem(- at: partURL, to: cachedLayer)- markDownloadComplete(digest)+ if FileManager.default.fileExists(atPath: cachedLayer.path) {+ try FileManager.default.removeItem(at: cachedLayer)}+ try FileManager.default.copyItem(+ at: partURL, to: cachedLayer)+ markDownloadComplete(digest)}await counter.decrement()@@ -468,13 +475,12 @@ class ImageContainerRegistry: @unchecked Sendable {let cachedLayer = getCachedLayerPath(manifestId: manifestId, digest: digest)- if !noCache && FileManager.default.fileExists(atPath: cachedLayer.path)- {+ if FileManager.default.fileExists(atPath: cachedLayer.path) {try FileManager.default.copyItem(at: cachedLayer, to: outputURL)await progress.addProgress(Int64(size))} else {// Check if this layer is already being downloaded and we're not skipping cache- if !noCache && isDownloading(digest) {+ if isDownloading(digest) {try await waitForExistingDownload(digest, cachedLayer: cachedLayer)if FileManager.default.fileExists(atPath: cachedLayer.path) {@@ -486,9 +492,7 @@ class ImageContainerRegistry: @unchecked Sendable {}// Start new download- if !noCache {- markDownloadStarted(digest)- }+ markDownloadStarted(digest)try await self.downloadLayer(repository: "\(self.organization)/\(imageName)",@@ -501,13 +505,11 @@ class ImageContainerRegistry: @unchecked Sendable {)// Cache the downloaded layer if not in noCache mode- if !noCache {- if FileManager.default.fileExists(atPath: cachedLayer.path) {- try FileManager.default.removeItem(at: cachedLayer)- }- try FileManager.default.copyItem(at: outputURL, to: cachedLayer)- markDownloadComplete(digest)+ if FileManager.default.fileExists(atPath: cachedLayer.path) {+ try FileManager.default.removeItem(at: cachedLayer)}+ try FileManager.default.copyItem(at: outputURL, to: cachedLayer)+ markDownloadComplete(digest)}await counter.decrement()@@ -548,7 +550,7 @@ class ImageContainerRegistry: @unchecked Sendable {defer {try? inputHandle.close()// Don't delete the part file if we're in cache mode and the part is from cache- if noCache || !partURL.path.contains(cacheDirectory.path) {+ if !partURL.path.contains(cacheDirectory.path) {try? FileManager.default.removeItem(at: partURL)}}@@ -632,9 +634,21 @@ class ImageContainerRegistry: @unchecked Sendable {if FileManager.default.fileExists(atPath: vmDir.dir.path) {try FileManager.default.removeItem(at: URL(fileURLWithPath: vmDir.dir.path))}++ // Ensure parent directory existstry FileManager.default.createDirectory(at: URL(fileURLWithPath: vmDir.dir.path).deletingLastPathComponent(),withIntermediateDirectories: true)++ // Log the final destination+ Logger.info(+ "Moving files to VM directory",+ metadata: [+ "destination": vmDir.dir.path,+ "location": locationName ?? "default",+ ])++ // Move files to final locationtry FileManager.default.moveItem(at: tempVMDir, to: URL(fileURLWithPath: vmDir.dir.path))Logger.info("Download complete: Files extracted to \(vmDir.dir.path)")diff --git a/libs/lume/src/FileSystem/Home.swift b/libs/lume/src/FileSystem/Home.swiftindex 571a7f923c..79476407f8 100644--- a/libs/lume/src/FileSystem/Home.swift+++ b/libs/lume/src/FileSystem/Home.swift@@ -4,35 +4,58 @@ import Foundation/// Responsible for creating, accessing, and validating the application's directory structure.final class Home {// MARK: - Constants-+private enum Constants {static let defaultDirectoryName = ".lume"static let homeDirPath = "~/\(defaultDirectoryName)"}-+// MARK: - Properties-- let homeDir: Path++ private var _homeDir: Path+ private let settingsManager: SettingsManagerprivate let fileManager: FileManager-+ private var locations: [String: VMLocation] = [:]++ // Current home directory based on default location+ var homeDir: Path {+ return _homeDir+ }+// MARK: - Initialization-- init(fileManager: FileManager = .default) {++ init(+ settingsManager: SettingsManager = SettingsManager.shared,+ fileManager: FileManager = .default+ ) {+ self.settingsManager = settingsManagerself.fileManager = fileManager- self.homeDir = Path(Constants.homeDirPath)++ // Get home directory path from settings or use default+ let settings = settingsManager.getSettings()+ guard let defaultLocation = settings.defaultLocation else {+ fatalError("No default VM location found")+ }++ self._homeDir = Path(defaultLocation.path)++ // Cache all locations+ for location in settings.vmLocations {+ locations[location.name] = location+ }}-+// MARK: - VM Directory Management-+/// Creates a temporary VM directory with a unique identifier/// - Returns: A VMDirectory instance representing the created directory/// - Throws: HomeError if directory creation failsfunc createTempVMDirectory() throws -> VMDirectory {let uuid = UUID().uuidStringlet tempDir = homeDir.directory(uuid)-+Logger.info("Creating temporary directory", metadata: ["path": tempDir.path])-+do {try createDirectory(at: tempDir.url)return VMDirectory(tempDir)@@ -40,107 +63,233 @@ final class Home {throw HomeError.directoryCreationFailed(path: tempDir.path)}}-- /// Returns a VMDirectory instance for the given name- /// - Parameter name: Name of the VM directory++ /// Returns a VMDirectory instance for the given name and location+ /// - Parameters:+ /// - name: Name of the VM directory+ /// - locationName: Optional name of the VM location (default: default location)/// - Returns: A VMDirectory instance- func getVMDirectory(_ name: String) -> VMDirectory {- VMDirectory(homeDir.directory(name))+ /// - Throws: HomeError if location not found+ func getVMDirectory(_ name: String, locationName: String? = nil) throws -> VMDirectory {+ let location: VMLocation++ if let locationName = locationName {+ // Get a specific location+ guard let loc = locations[locationName] else {+ throw VMLocationError.locationNotFound(name: locationName)+ }+ location = loc+ } else {+ // Use default location+ let settings = settingsManager.getSettings()+ guard let defaultLocation = settings.defaultLocation else {+ throw HomeError.invalidHomeDirectory+ }+ location = defaultLocation+ }++ let baseDir = Path(location.expandedPath)+ return VMDirectory(baseDir.directory(name))}-- /// Returns all initialized VM directories- /// - Returns: An array of VMDirectory instances++ /// Returns all initialized VM directories across all locations+ /// - Returns: An array of VMDirectory instances with location info/// - Throws: HomeError if directory access is denied- func getAllVMDirectories() throws -> [VMDirectory] {- guard homeDir.exists() else { return [] }-- do {- let allFolders = try fileManager.contentsOfDirectory(- at: homeDir.url,- includingPropertiesForKeys: nil- )- let folders = allFolders- .compactMap { url in- let sanitizedName = sanitizeFileName(url.lastPathComponent)- let dir = getVMDirectory(sanitizedName)- let dir1 = dir.initialized() ? dir : nil- return dir1- }- return folders- } catch {- throw HomeError.directoryAccessDenied(path: homeDir.path)+ func getAllVMDirectories() throws -> [VMDirectoryWithLocation] {+ var results: [VMDirectoryWithLocation] = []++ // Loop through all locations+ let settings = settingsManager.getSettings()+ for location in settings.vmLocations {+ let locationPath = Path(location.expandedPath)++ // Skip non-existent locations+ if !locationPath.exists() {+ continue+ }++ do {+ let allFolders = try fileManager.contentsOfDirectory(+ at: locationPath.url,+ includingPropertiesForKeys: nil+ )++ let folders =+ allFolders+ .compactMap { url in+ let sanitizedName = sanitizeFileName(url.lastPathComponent)+ let dir = VMDirectory(locationPath.directory(sanitizedName))+ let dirWithLoc =+ dir.initialized()+ ? VMDirectoryWithLocation(directory: dir, locationName: location.name)+ : nil+ return dirWithLoc+ }++ results.append(contentsOf: folders)+ } catch {+ Logger.error(+ "Failed to access VM location",+ metadata: [+ "location": location.name,+ "error": error.localizedDescription,+ ])+ // Continue to next location rather than failing completely+ }}++ return results}-+/// Copies a VM directory to a new location with a new name/// - 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 copy operation fails- func copyVMDirectory(from sourceName: String, to destName: String) throws {- let sourceDir = getVMDirectory(sourceName)- let destDir = getVMDirectory(destName)-+ func copyVMDirectory(+ from sourceName: String,+ to destName: String,+ sourceLocation: String? = nil,+ destLocation: String? = nil+ ) throws {+ let sourceDir = try getVMDirectory(sourceName, locationName: sourceLocation)+ let destDir = try getVMDirectory(destName, locationName: destLocation)+if destDir.initialized() {throw HomeError.directoryAlreadyExists(path: destDir.dir.path)}-+do {try fileManager.copyItem(atPath: sourceDir.dir.path, toPath: destDir.dir.path)} catch {throw HomeError.directoryCreationFailed(path: destDir.dir.path)}}-++ // MARK: - Location Management++ /// Adds a new VM location+ /// - Parameters:+ /// - name: Location name+ /// - path: Location path+ /// - Throws: Error if location cannot be added+ func addLocation(name: String, path: String) throws {+ let location = VMLocation(name: name, path: path)+ try settingsManager.addLocation(location)++ // Update cache+ locations[name] = location+ }++ /// Removes a VM location+ /// - Parameter name: Location name+ /// - Throws: Error if location cannot be removed+ func removeLocation(name: String) throws {+ try settingsManager.removeLocation(name: name)++ // Update cache+ locations.removeValue(forKey: name)+ }++ /// Sets the default VM location+ /// - Parameter name: Location name+ /// - Throws: Error if location cannot be set as default+ func setDefaultLocation(name: String) throws {+ try settingsManager.setDefaultLocation(name: name)++ // Update home directory+ guard let location = locations[name] else {+ throw VMLocationError.locationNotFound(name: name)+ }++ // Update homeDir to reflect the new default+ self._homeDir = Path(location.path)+ }++ /// Gets all available VM locations+ /// - Returns: Array of VM locations+ func getLocations() -> [VMLocation] {+ return settingsManager.getSettings().sortedLocations+ }++ /// Gets the default VM location+ /// - Returns: Default VM location+ /// - Throws: HomeError if no default location+ func getDefaultLocation() throws -> VMLocation {+ guard let location = settingsManager.getSettings().defaultLocation else {+ throw HomeError.invalidHomeDirectory+ }+ return location+ }+// MARK: - Directory Validation-- /// Validates and ensures the existence of the home directory++ /// Validates and ensures the existence of all VM locations/// - Throws: HomeError if validation fails or directory creation failsfunc validateHomeDirectory() throws {- if !homeDir.exists() {- try createHomeDirectory()- return- }-- guard isValidDirectory(at: homeDir.path) else {- throw HomeError.invalidHomeDirectory+ let settings = settingsManager.getSettings()++ for location in settings.vmLocations {+ let path = location.expandedPath+ if !fileExists(at: path) {+ try createVMLocation(at: path)+ } else if !isValidDirectory(at: path) {+ throw HomeError.invalidHomeDirectory+ }}}-+// MARK: - Private Helpers-- private func createHomeDirectory() throws {++ private func createVMLocation(at path: String) throws {do {- try createDirectory(at: homeDir.url)+ try fileManager.createDirectory(+ atPath: path,+ withIntermediateDirectories: true+ )} catch {- throw HomeError.directoryCreationFailed(path: homeDir.path)+ throw HomeError.directoryCreationFailed(path: path)}}-+private func createDirectory(at url: URL) throws {try fileManager.createDirectory(at: url,withIntermediateDirectories: true)}-+private func isValidDirectory(at path: String) -> Bool {var isDirectory: ObjCBool = false- return fileManager.fileExists(atPath: path, isDirectory: &isDirectory)- && isDirectory.boolValue+ return fileManager.fileExists(atPath: path, isDirectory: &isDirectory)+ && isDirectory.boolValue&& Path(path).writable()}-++ private func fileExists(at path: String) -> Bool {+ return fileManager.fileExists(atPath: path)+ }+private func sanitizeFileName(_ name: String) -> String {// Only decode percent encoding (e.g., %20 for spaces)return name.removingPercentEncoding ?? name}}+// MARK: - VM Directory with Location++/// Represents a VM directory with its location information+struct VMDirectoryWithLocation {+ let directory: VMDirectory+ let locationName: String+}+// MARK: - Home + CustomStringConvertibleextension Home: CustomStringConvertible {var description: String {"Home(path: \(homeDir.path))"}-}\ No newline at end of file+}diff --git a/libs/lume/src/FileSystem/Settings.swift b/libs/lume/src/FileSystem/Settings.swiftnew file mode 100644index 0000000000..96a5dedc24--- /dev/null+++ b/libs/lume/src/FileSystem/Settings.swift@@ -0,0 +1,249 @@+import Foundation++/// Manages the application settings using a config file+struct LumeSettings: Codable, Sendable {+ var vmLocations: [VMLocation]+ var defaultLocationName: String+ var cacheDirectory: String++ var defaultLocation: VMLocation? {+ vmLocations.first { $0.name == defaultLocationName }+ }++ // For backward compatibility+ var homeDirectory: String {+ defaultLocation?.path ?? "~/.lume"+ }++ static let defaultSettings = LumeSettings(+ vmLocations: [+ VMLocation(name: "default", path: "~/.lume")+ ],+ defaultLocationName: "default",+ cacheDirectory: "~/.lume/cache"+ )++ /// Gets all locations sorted by name+ var sortedLocations: [VMLocation] {+ vmLocations.sorted { $0.name < $1.name }+ }+}++final class SettingsManager: @unchecked Sendable {+ // MARK: - Constants++ private enum Constants {+ static let xdgConfigDir = "~/.config/lume"+ static let configFileName = "config.json"+ }++ // MARK: - Properties++ static let shared = SettingsManager()+ private let fileManager: FileManager++ // Path to XDG config file+ private var configFilePath: String {+ let configDir = (Constants.xdgConfigDir as NSString).expandingTildeInPath+ return "\(configDir)/\(Constants.configFileName)"+ }++ // MARK: - Initialization++ init(fileManager: FileManager = .default) {+ self.fileManager = fileManager+ ensureConfigDirectoryExists()+ }++ // MARK: - Settings Access++ func getSettings() -> LumeSettings {+ if let settings = readSettingsFromFile() {+ return settings+ }++ // No settings file found, use defaults+ let defaultSettings = LumeSettings.defaultSettings++ // Try to save default settings+ try? saveSettings(defaultSettings)++ return defaultSettings+ }++ func saveSettings(_ settings: LumeSettings) throws {+ let configDir = (Constants.xdgConfigDir as NSString).expandingTildeInPath+ try fileManager.createDirectory(atPath: configDir, withIntermediateDirectories: true)++ let data = try JSONEncoder().encode(settings)+ try data.write(to: URL(fileURLWithPath: configFilePath))+ }++ // MARK: - VM Location Management++ func addLocation(_ location: VMLocation) throws {+ var settings = getSettings()++ // Validate location name (alphanumeric, dash, underscore)+ let nameRegex = try NSRegularExpression(pattern: "^[a-zA-Z0-9_-]+$")+ let nameRange = NSRange(location.name.startIndex..., in: location.name)+ if nameRegex.firstMatch(in: location.name, range: nameRange) == nil {+ throw VMLocationError.invalidLocationName(name: location.name)+ }++ // Check for duplicate name+ if settings.vmLocations.contains(where: { $0.name == location.name }) {+ throw VMLocationError.duplicateLocationName(name: location.name)+ }++ // Validate location path+ try location.validate()++ // Add location+ settings.vmLocations.append(location)+ try saveSettings(settings)+ }++ func removeLocation(name: String) throws {+ var settings = getSettings()++ // Check location exists+ guard settings.vmLocations.contains(where: { $0.name == name }) else {+ throw VMLocationError.locationNotFound(name: name)+ }++ // Prevent removing default location+ if name == settings.defaultLocationName {+ throw VMLocationError.defaultLocationCannotBeRemoved(name: name)+ }++ // Remove location+ settings.vmLocations.removeAll(where: { $0.name == name })+ try saveSettings(settings)+ }++ func setDefaultLocation(name: String) throws {+ var settings = getSettings()++ // Check location exists+ guard settings.vmLocations.contains(where: { $0.name == name }) else {+ throw VMLocationError.locationNotFound(name: name)+ }++ // Set default+ settings.defaultLocationName = name+ try saveSettings(settings)+ }++ func getLocation(name: String) throws -> VMLocation {+ let settings = getSettings()++ if let location = settings.vmLocations.first(where: { $0.name == name }) {+ return location+ }++ throw VMLocationError.locationNotFound(name: name)+ }++ // MARK: - Legacy Home Directory Compatibility++ func setHomeDirectory(path: String) throws {+ var settings = getSettings()++ let defaultLocation = VMLocation(name: "default", path: path)+ try defaultLocation.validate()++ // Replace default location+ if let index = settings.vmLocations.firstIndex(where: { $0.name == "default" }) {+ settings.vmLocations[index] = defaultLocation+ } else {+ settings.vmLocations.append(defaultLocation)+ settings.defaultLocationName = "default"+ }++ try saveSettings(settings)+ }++ // MARK: - Cache Directory Management++ func setCacheDirectory(path: String) throws {+ var settings = getSettings()++ // Validate path+ let expandedPath = (path as NSString).expandingTildeInPath+ var isDir: ObjCBool = false++ // If directory exists, check if it's writable+ if fileManager.fileExists(atPath: expandedPath, isDirectory: &isDir) {+ if !isDir.boolValue {+ throw SettingsError.notADirectory(path: expandedPath)+ }++ if !fileManager.isWritableFile(atPath: expandedPath) {+ throw SettingsError.directoryNotWritable(path: expandedPath)+ }+ } else {+ // Try to create the directory+ do {+ try fileManager.createDirectory(+ atPath: expandedPath,+ withIntermediateDirectories: true+ )+ } catch {+ throw SettingsError.directoryCreationFailed(path: expandedPath, error: error)+ }+ }++ // Update settings+ settings.cacheDirectory = path+ try saveSettings(settings)+ }++ func getCacheDirectory() -> String {+ return getSettings().cacheDirectory+ }++ // MARK: - Private Helpers++ private func ensureConfigDirectoryExists() {+ let configDir = (Constants.xdgConfigDir as NSString).expandingTildeInPath+ try? fileManager.createDirectory(atPath: configDir, withIntermediateDirectories: true)+ }++ private func readSettingsFromFile() -> LumeSettings? {+ guard fileExists(at: configFilePath) else { return nil }++ do {+ let data = try Data(contentsOf: URL(fileURLWithPath: configFilePath))+ return try JSONDecoder().decode(LumeSettings.self, from: data)+ } catch {+ Logger.error(+ "Failed to read settings from file", metadata: ["error": error.localizedDescription]+ )+ return nil+ }+ }++ private func fileExists(at path: String) -> Bool {+ fileManager.fileExists(atPath: path)+ }+}++// MARK: - Errors++enum SettingsError: Error, LocalizedError {+ case notADirectory(path: String)+ case directoryNotWritable(path: String)+ case directoryCreationFailed(path: String, error: Error)++ var errorDescription: String? {+ switch self {+ case .notADirectory(let path):+ return "Path is not a directory: \(path)"+ case .directoryNotWritable(let path):+ return "Directory is not writable: \(path)"+ case .directoryCreationFailed(let path, let error):+ return "Failed to create directory at \(path): \(error.localizedDescription)"+ }+ }+}diff --git a/libs/lume/src/FileSystem/VMLocation.swift b/libs/lume/src/FileSystem/VMLocation.swiftnew file mode 100644index 0000000000..f635f7b576--- /dev/null+++ b/libs/lume/src/FileSystem/VMLocation.swift@@ -0,0 +1,69 @@+import Foundation++/// Represents a location where VMs can be stored+struct VMLocation: Codable, Equatable, Sendable {+ let name: String+ let path: String++ var expandedPath: String {+ (path as NSString).expandingTildeInPath+ }++ /// Validates the location path exists and is writable+ func validate() throws {+ let fullPath = expandedPath+ var isDir: ObjCBool = false++ if FileManager.default.fileExists(atPath: fullPath, isDirectory: &isDir) {+ if !isDir.boolValue {+ throw VMLocationError.notADirectory(path: fullPath)+ }++ if !FileManager.default.isWritableFile(atPath: fullPath) {+ throw VMLocationError.directoryNotWritable(path: fullPath)+ }+ } else {+ // Try to create the directory+ do {+ try FileManager.default.createDirectory(+ atPath: fullPath,+ withIntermediateDirectories: true+ )+ } catch {+ throw VMLocationError.directoryCreationFailed(path: fullPath, error: error)+ }+ }+ }+}++// MARK: - Errors++enum VMLocationError: Error, LocalizedError {+ case notADirectory(path: String)+ case directoryNotWritable(path: String)+ case directoryCreationFailed(path: String, error: Error)+ case locationNotFound(name: String)+ case duplicateLocationName(name: String)+ case invalidLocationName(name: String)+ case defaultLocationCannotBeRemoved(name: String)++ var errorDescription: String? {+ switch self {+ case .notADirectory(let path):+ return "Path is not a directory: \(path)"+ case .directoryNotWritable(let path):+ return "Directory is not writable: \(path)"+ case .directoryCreationFailed(let path, let error):+ return "Failed to create directory at \(path): \(error.localizedDescription)"+ case .locationNotFound(let name):+ return "VM location not found: \(name)"+ case .duplicateLocationName(let name):+ return "VM location with name '\(name)' already exists"+ case .invalidLocationName(let name):+ return+ "Invalid location name: \(name). Names should be alphanumeric with underscores or dashes."+ case .defaultLocationCannotBeRemoved(let name):+ return "Cannot remove the default location '\(name)'. Set a new default location first."+ }+ }+}diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swiftindex 9350d0073a..12859ba474 100644--- a/libs/lume/src/LumeController.swift+++ b/libs/lume/src/LumeController.swift@@ -8,17 +8,17 @@ import Virtualizationfinal class SharedVM {static let shared: SharedVM = SharedVM()private var runningVMs: [String: VM] = [:]-+private init() {}-+func getVM(name: String) -> VM? {return runningVMs[name]}-+func setVM(name: String, vm: VM) {runningVMs[name] = vm}-+func removeVM(name: String) {runningVMs.removeValue(forKey: name)}@@ -50,8 +50,10 @@ final class LumeController {@MainActorpublic func list() throws -> [VMDetails] {do {- let statuses = try home.getAllVMDirectories().map { directory in- let vm = try self.get(name: directory.name)+ let vmLocations = try home.getAllVMDirectories()+ let statuses = try vmLocations.map { vmWithLoc in+ let vm = try self.get(+ name: vmWithLoc.directory.name, locationName: vmWithLoc.locationName)return vm.details}return statuses@@ -62,22 +64,38 @@ final class LumeController {}@MainActor- public func clone(name: String, newName: String) throws {+ public func clone(+ name: String, newName: String, sourceLocation: String? = nil, destLocation: String? = nil+ ) throws {let normalizedName = normalizeVMName(name: name)let normalizedNewName = normalizeVMName(name: newName)- Logger.info("Cloning VM", metadata: ["source": normalizedName, "destination": normalizedNewName])+ Logger.info(+ "Cloning VM",+ metadata: [+ "source": normalizedName,+ "destination": normalizedNewName,+ "sourceLocation": sourceLocation ?? "default",+ "destLocation": destLocation ?? "default",+ ])do {- try self.validateVMExists(normalizedName)-+ try self.validateVMExists(normalizedName, locationName: sourceLocation)+// Copy the VM directory- try home.copyVMDirectory(from: normalizedName, to: normalizedNewName)-+ try home.copyVMDirectory(+ from: normalizedName,+ to: normalizedNewName,+ sourceLocation: sourceLocation,+ destLocation: destLocation+ )+// Update MAC address in the cloned VM to ensure uniqueness- let clonedVM = try get(name: normalizedNewName)+ let clonedVM = try get(name: normalizedNewName, locationName: destLocation)try clonedVM.setMacAddress(VZMACAddress.randomLocallyAdministered().string)-- Logger.info("VM cloned successfully", metadata: ["source": normalizedName, "destination": normalizedNewName])++ Logger.info(+ "VM cloned successfully",+ metadata: ["source": normalizedName, "destination": normalizedNewName])} catch {Logger.error("Failed to clone VM", metadata: ["error": error.localizedDescription])throw error@@ -85,12 +103,12 @@ final class LumeController {}@MainActor- public func get(name: String) throws -> VM {+ public func get(name: String, locationName: String? = nil) throws -> VM {let normalizedName = normalizeVMName(name: name)do {- try self.validateVMExists(normalizedName)+ try self.validateVMExists(normalizedName, locationName: locationName)- let vm = try self.loadVM(name: normalizedName)+ let vm = try self.loadVM(name: normalizedName, locationName: locationName)return vm} catch {Logger.error("Failed to get VM", metadata: ["error": error.localizedDescription])@@ -107,13 +125,15 @@ final class LumeController {cpuCount: Int,memorySize: UInt64,display: String,- ipsw: String?+ ipsw: String?,+ locationName: String? = nil) async throws {Logger.info("Creating VM",metadata: ["name": name,"os": os,+ "location": locationName ?? "default","disk_size": "\(diskSize / 1024 / 1024)MB","cpu_count": "\(cpuCount)","memory_size": "\(memorySize / 1024 / 1024)MB",@@ -122,7 +142,7 @@ final class LumeController {])do {- try validateCreateParameters(name: name, os: os, ipsw: ipsw)+ try validateCreateParameters(name: name, os: os, ipsw: ipsw, locationName: locationName)let vm = try await createTempVMConfig(os: os,@@ -140,7 +160,7 @@ final class LumeController {display: display)- try vm.finalize(to: name, home: home)+ try vm.finalize(to: name, home: home, locationName: locationName)Logger.info("VM created successfully", metadata: ["name": name])} catch {@@ -150,19 +170,24 @@ final class LumeController {}@MainActor- public func delete(name: String) async throws {+ public func delete(name: String, locationName: String? = nil) async throws {let normalizedName = normalizeVMName(name: name)- Logger.info("Deleting VM", metadata: ["name": normalizedName])+ Logger.info(+ "Deleting VM",+ metadata: [+ "name": normalizedName,+ "location": locationName ?? "default",+ ])do {- try self.validateVMExists(normalizedName)+ try self.validateVMExists(normalizedName, locationName: locationName)// Stop VM if it's runningif SharedVM.shared.getVM(name: normalizedName) != nil {try await stopVM(name: normalizedName)}- let vmDir = home.getVMDirectory(normalizedName)+ let vmDir = try home.getVMDirectory(normalizedName, locationName: locationName)try vmDir.delete()Logger.info("VM deleted successfully", metadata: ["name": normalizedName])@@ -181,22 +206,24 @@ final class LumeController {cpu: Int? = nil,memory: UInt64? = nil,diskSize: UInt64? = nil,- display: String? = nil+ display: String? = nil,+ locationName: String? = nil) throws {let normalizedName = normalizeVMName(name: name)Logger.info("Updating VM settings",metadata: ["name": normalizedName,+ "location": locationName ?? "default","cpu": cpu.map { "\($0)" } ?? "unchanged","memory": memory.map { "\($0 / 1024 / 1024)MB" } ?? "unchanged","disk_size": diskSize.map { "\($0 / 1024 / 1024)MB" } ?? "unchanged","display": display ?? "unchanged",])do {- try self.validateVMExists(normalizedName)+ try self.validateVMExists(normalizedName, locationName: locationName)- let vm = try get(name: normalizedName)+ let vm = try get(name: normalizedName, locationName: locationName)// Apply settings in orderif let cpu = cpu {@@ -257,15 +284,18 @@ final class LumeController {registry: String = "ghcr.io",organization: String = "trycua",vncPort: Int = 0,- recoveryMode: Bool = false+ recoveryMode: Bool = false,+ locationName: String? = nil) async throws {let normalizedName = normalizeVMName(name: name)Logger.info("Running VM",metadata: ["name": normalizedName,+ "location": locationName ?? "default","no_display": "\(noDisplay)",- "shared_directories": "\(sharedDirectories.map( { $0.string } ).joined(separator: ", "))",+ "shared_directories":+ "\(sharedDirectories.map( { $0.string } ).joined(separator: ", "))","mount": mount?.path ?? "none","vnc_port": "\(vncPort)","recovery_mode": "\(recoveryMode)",@@ -276,19 +306,31 @@ final class LumeController {let components = name.split(separator: ":")if components.count == 2 {do {- try self.validateVMExists(normalizedName)+ try self.validateVMExists(normalizedName, locationName: locationName)} catch {// If the VM doesn't exist, try to pull the image- try await pullImage(image: name, name: nil, registry: registry, organization: organization)+ try await pullImage(+ image: name,+ name: nil,+ registry: registry,+ organization: organization,+ locationName: locationName+ )}}try validateRunParameters(- name: normalizedName, sharedDirectories: sharedDirectories, mount: mount)+ name: normalizedName,+ sharedDirectories: sharedDirectories,+ mount: mount,+ locationName: locationName+ )- let vm = try get(name: normalizedName)+ let vm = try get(name: normalizedName, locationName: locationName)SharedVM.shared.setVM(name: normalizedName, vm: vm)- try await vm.run(noDisplay: noDisplay, sharedDirectories: sharedDirectories, mount: mount, vncPort: vncPort, recoveryMode: recoveryMode)+ try await vm.run(+ noDisplay: noDisplay, sharedDirectories: sharedDirectories, mount: mount,+ vncPort: vncPort, recoveryMode: recoveryMode)Logger.info("VM started successfully", metadata: ["name": normalizedName])} catch {SharedVM.shared.removeVM(name: normalizedName)@@ -316,9 +358,13 @@ final class LumeController {}@MainActor- public func pullImage(image: String, name: String?, registry: String, organization: String, noCache: Bool = false)- async throws- {+ public func pullImage(+ image: String,+ name: String?,+ registry: String,+ organization: String,+ locationName: String? = nil+ ) async throws {do {let vmName: String = name ?? normalizeVMName(name: image)@@ -329,19 +375,31 @@ final class LumeController {"name": name ?? "default","registry": registry,"organization": organization,+ "location": locationName ?? "default",])try self.validatePullParameters(- image: image, name: vmName, registry: registry, organization: organization)+ image: image,+ name: vmName,+ registry: registry,+ organization: organization,+ locationName: locationName+ )let imageContainerRegistry = ImageContainerRegistry(registry: registry, organization: organization)- try await imageContainerRegistry.pull(image: image, name: vmName, noCache: noCache)+ try await imageContainerRegistry.pull(+ image: image, name: vmName, locationName: locationName)- Logger.info("Setting new VM mac address")+ Logger.info(+ "Setting new VM mac address",+ metadata: [+ "vm_name": vmName,+ "location": locationName ?? "default",+ ])// Update MAC address in the cloned VM to ensure uniqueness- let vm = try get(name: vmName)+ let vm = try get(name: vmName, locationName: locationName)try vm.setMacAddress(VZMACAddress.randomLocallyAdministered().string)Logger.info(@@ -351,6 +409,7 @@ final class LumeController {"name": vmName,"registry": registry,"organization": organization,+ "location": locationName ?? "default",])} catch {Logger.error("Failed to pull image", metadata: ["error": error.localizedDescription])@@ -361,14 +420,17 @@ final class LumeController {@MainActorpublic func pruneImages() async throws {Logger.info("Pruning cached images")-+do {- let home = FileManager.default.homeDirectoryForCurrentUser- let cacheDir = home.appendingPathComponent(".lume/cache/ghcr")-- if FileManager.default.fileExists(atPath: cacheDir.path) {- try FileManager.default.removeItem(at: cacheDir)- try FileManager.default.createDirectory(at: cacheDir, withIntermediateDirectories: true)+ // Use configured cache directory+ let cacheDir = (SettingsManager.shared.getCacheDirectory() as NSString)+ .expandingTildeInPath+ let ghcrDir = URL(fileURLWithPath: cacheDir).appendingPathComponent("ghcr")++ if FileManager.default.fileExists(atPath: ghcrDir.path) {+ try FileManager.default.removeItem(at: ghcrDir)+ try FileManager.default.createDirectory(+ at: ghcrDir, withIntermediateDirectories: true)Logger.info("Successfully removed cached images")} else {Logger.info("No cached images found")@@ -392,21 +454,82 @@ final class LumeController {@MainActorpublic func getImages(organization: String = "trycua") async throws -> ImageList {Logger.info("Listing local images", metadata: ["organization": organization])-- let imageContainerRegistry = ImageContainerRegistry(registry: "ghcr.io", organization: organization)++ let imageContainerRegistry = ImageContainerRegistry(+ registry: "ghcr.io", organization: organization)let cachedImages = try await imageContainerRegistry.getImages()-+let imageInfos = cachedImages.map { image inImageInfo(repository: image.repository,imageId: String(image.manifestId.prefix(12)))}-+ImagesPrinter.print(images: imageInfos.map { "\($0.repository):\($0.imageId)" })return ImageList(local: imageInfos, remote: [])}+ // MARK: - Settings Management++ public func getSettings() -> LumeSettings {+ return SettingsManager.shared.getSettings()+ }++ public func setHomeDirectory(_ path: String) throws {+ // Try to set the home directory in settings+ try SettingsManager.shared.setHomeDirectory(path: path)++ // Force recreate home instance to use the new path+ try home.validateHomeDirectory()++ Logger.info("Home directory updated", metadata: ["path": path])+ }++ // MARK: - VM Location Management++ public func addLocation(name: String, path: String) throws {+ Logger.info("Adding VM location", metadata: ["name": name, "path": path])++ try home.addLocation(name: name, path: path)++ Logger.info("VM location added successfully", metadata: ["name": name])+ }++ public func removeLocation(name: String) throws {+ Logger.info("Removing VM location", metadata: ["name": name])++ try home.removeLocation(name: name)++ Logger.info("VM location removed successfully", metadata: ["name": name])+ }++ public func setDefaultLocation(name: String) throws {+ Logger.info("Setting default VM location", metadata: ["name": name])++ try home.setDefaultLocation(name: name)++ Logger.info("Default VM location set successfully", metadata: ["name": name])+ }++ public func getLocations() -> [VMLocation] {+ return home.getLocations()+ }++ // MARK: - Cache Directory Management++ public func setCacheDirectory(path: String) throws {+ Logger.info("Setting cache directory", metadata: ["path": path])++ try SettingsManager.shared.setCacheDirectory(path: path)++ Logger.info("Cache directory updated", metadata: ["path": path])+ }++ public func getCacheDirectory() -> String {+ return SettingsManager.shared.getCacheDirectory()+ }+// MARK: - Private Helper Methods/// Normalizes a VM name by replacing colons with underscores@@ -443,8 +566,8 @@ final class LumeController {}@MainActor- private func loadVM(name: String) throws -> VM {- let vmDir = home.getVMDirectory(name)+ private func loadVM(name: String, locationName: String? = nil) throws -> VM {+ let vmDir = try home.getVMDirectory(name, locationName: locationName)guard vmDir.initialized() else {throw VMError.notInitialized(name)}@@ -459,7 +582,9 @@ final class LumeController {// MARK: - Validation Methods- private func validateCreateParameters(name: String, os: String, ipsw: String?) throws {+ private func validateCreateParameters(+ name: String, os: String, ipsw: String?, locationName: String?+ ) throws {if os.lowercased() == "macos" {guard let ipsw = ipsw else {throw ValidationError("IPSW path required for macOS VM")@@ -475,7 +600,7 @@ final class LumeController {throw ValidationError("Unsupported OS type: \(os)")}- let vmDir = home.getVMDirectory(name)+ let vmDir = try home.getVMDirectory(name, locationName: locationName)if vmDir.exists() {throw VMError.alreadyExists(name)}@@ -493,15 +618,19 @@ final class LumeController {}}- public func validateVMExists(_ name: String) throws {- let vmDir = home.getVMDirectory(name)+ public func validateVMExists(_ name: String, locationName: String? = nil) throws {+ let vmDir = try home.getVMDirectory(name, locationName: locationName)guard vmDir.initialized() else {throw VMError.notFound(name)}}private func validatePullParameters(- image: String, name: String, registry: String, organization: String+ image: String,+ name: String,+ registry: String,+ organization: String,+ locationName: String? = nil) throws {guard !image.isEmpty else {throw ValidationError("Image name cannot be empty")@@ -516,20 +645,21 @@ final class LumeController {throw ValidationError("Organization cannot be empty")}- let vmDir = home.getVMDirectory(name)+ let vmDir = try home.getVMDirectory(name, locationName: locationName)if vmDir.exists() {throw VMError.alreadyExists(name)}}private func validateRunParameters(- name: String, sharedDirectories: [SharedDirectory]?, mount: Path?+ name: String, sharedDirectories: [SharedDirectory]?, mount: Path?,+ locationName: String? = nil) throws {- try self.validateVMExists(name)- if let dirs: [SharedDirectory] = sharedDirectories {+ try self.validateVMExists(name, locationName: locationName)+ if let dirs = sharedDirectories {try self.validateSharedDirectories(dirs)}- let vmConfig = try home.getVMDirectory(name).loadConfig()+ let vmConfig = try home.getVMDirectory(name, locationName: locationName).loadConfig()switch vmConfig.os.lowercased() {case "macos":if mount != nil {diff --git a/libs/lume/src/Server/Handlers.swift b/libs/lume/src/Server/Handlers.swiftindex 3fe0356550..9c00038e00 100644--- a/libs/lume/src/Server/Handlers.swift+++ b/libs/lume/src/Server/Handlers.swift@@ -1,11 +1,11 @@+import ArgumentParserimport Foundationimport Virtualization-import ArgumentParser@MainActorextension Server {// MARK: - VM Management Handlers-+func handleListVMs() async throws -> HTTPResponse {do {let vmController = LumeController()@@ -15,7 +15,7 @@ extension Server {return .badRequest(message: error.localizedDescription)}}-+func handleGetVM(name: String) async throws -> HTTPResponse {do {let vmController = LumeController()@@ -25,17 +25,18 @@ extension Server {return .badRequest(message: error.localizedDescription)}}-+func handleCreateVM(_ body: Data?) async throws -> HTTPResponse {guard let body = body,- let request = try? JSONDecoder().decode(CreateVMRequest.self, from: body) else {+ let request = try? JSONDecoder().decode(CreateVMRequest.self, from: body)+ else {return HTTPResponse(statusCode: .badRequest,headers: ["Content-Type": "application/json"],body: try JSONEncoder().encode(APIError(message: "Invalid request body")))}-+do {let sizes = try request.parse()let vmController = LumeController()@@ -48,11 +49,13 @@ extension Server {display: request.display,ipsw: request.ipsw)-+return HTTPResponse(statusCode: .ok,headers: ["Content-Type": "application/json"],- body: try JSONEncoder().encode(["message": "VM created successfully", "name": request.name])+ body: try JSONEncoder().encode([+ "message": "VM created successfully", "name": request.name,+ ]))} catch {return HTTPResponse(@@ -67,33 +70,37 @@ extension Server {do {let vmController = LumeController()try await vmController.delete(name: name)- return HTTPResponse(statusCode: .ok, headers: ["Content-Type": "application/json"], body: Data())+ return HTTPResponse(+ statusCode: .ok, headers: ["Content-Type": "application/json"], body: Data())} catch {- return HTTPResponse(statusCode: .badRequest, headers: ["Content-Type": "application/json"], body: try JSONEncoder().encode(APIError(message: error.localizedDescription)))+ return HTTPResponse(+ statusCode: .badRequest, headers: ["Content-Type": "application/json"],+ body: try JSONEncoder().encode(APIError(message: error.localizedDescription)))}}-+func handleCloneVM(_ body: Data?) async throws -> HTTPResponse {guard let body = body,- let request = try? JSONDecoder().decode(CloneRequest.self, from: body) else {+ let request = try? JSONDecoder().decode(CloneRequest.self, from: body)+ else {return HTTPResponse(statusCode: .badRequest,headers: ["Content-Type": "application/json"],body: try JSONEncoder().encode(APIError(message: "Invalid request body")))}-+do {let vmController = LumeController()try vmController.clone(name: request.name, newName: request.newName)-+return HTTPResponse(statusCode: .ok,headers: ["Content-Type": "application/json"],body: try JSONEncoder().encode(["message": "VM cloned successfully","source": request.name,- "destination": request.newName+ "destination": request.newName,]))} catch {@@ -104,19 +111,20 @@ extension Server {)}}-+// MARK: - VM Operation Handlers-+func handleSetVM(name: String, body: Data?) async throws -> HTTPResponse {guard let body = body,- let request = try? JSONDecoder().decode(SetVMRequest.self, from: body) else {+ let request = try? JSONDecoder().decode(SetVMRequest.self, from: body)+ else {return HTTPResponse(statusCode: .badRequest,headers: ["Content-Type": "application/json"],body: try JSONEncoder().encode(APIError(message: "Invalid request body")))}-+do {let vmController = LumeController()let sizes = try request.parse()@@ -127,7 +135,7 @@ extension Server {diskSize: sizes.diskSize,display: sizes.display?.string)-+return HTTPResponse(statusCode: .ok,headers: ["Content-Type": "application/json"],@@ -141,7 +149,7 @@ extension Server {)}}-+func handleStopVM(name: String) async throws -> HTTPResponse {do {let vmController = LumeController()@@ -161,11 +169,13 @@ extension Server {}func handleRunVM(name: String, body: Data?) async throws -> HTTPResponse {- let request = body.flatMap { try? JSONDecoder().decode(RunVMRequest.self, from: $0) } ?? RunVMRequest(noDisplay: nil, sharedDirectories: nil, recoveryMode: nil)-+ let request =+ body.flatMap { try? JSONDecoder().decode(RunVMRequest.self, from: $0) }+ ?? RunVMRequest(noDisplay: nil, sharedDirectories: nil, recoveryMode: nil)+do {let dirs = try request.parse()-+// Start VM in backgroundstartVM(name: name,@@ -173,7 +183,7 @@ extension Server {sharedDirectories: dirs,recoveryMode: request.recoveryMode ?? false)-+// Return response immediatelyreturn HTTPResponse(statusCode: .accepted,@@ -181,7 +191,7 @@ extension Server {body: try JSONEncoder().encode(["message": "VM start initiated","name": name,- "status": "pending"+ "status": "pending",]))} catch {@@ -192,9 +202,9 @@ extension Server {)}}-+// MARK: - Image Management Handlers-+func handleIPSW() async throws -> HTTPResponse {do {let vmController = LumeController()@@ -215,7 +225,8 @@ extension Server {func handlePull(_ body: Data?) async throws -> HTTPResponse {guard let body = body,- let request = try? JSONDecoder().decode(PullRequest.self, from: body) else {+ let request = try? JSONDecoder().decode(PullRequest.self, from: body)+ else {return HTTPResponse(statusCode: .badRequest,headers: ["Content-Type": "application/json"],@@ -225,7 +236,12 @@ extension Server {do {let vmController = LumeController()- try await vmController.pullImage(image: request.image, name: request.name, registry: request.registry, organization: request.organization, noCache: request.noCache)+ try await vmController.pullImage(+ image: request.image,+ name: request.name,+ registry: request.registry,+ organization: request.organization+ )return HTTPResponse(statusCode: .ok,headers: ["Content-Type": "application/json"],@@ -257,30 +273,34 @@ extension Server {)}}-+func handleGetImages(_ request: HTTPRequest) async throws -> HTTPResponse {let pathAndQuery = request.path.split(separator: "?", maxSplits: 1)- let queryParams = pathAndQuery.count > 1 ? pathAndQuery[1]- .split(separator: "&")- .reduce(into: [String: String]()) { dict, param in- let parts = param.split(separator: "=", maxSplits: 1)- if parts.count == 2 {- dict[String(parts[0])] = String(parts[1])- }- } : [:]-+ let queryParams =+ pathAndQuery.count > 1+ ? pathAndQuery[1]+ .split(separator: "&")+ .reduce(into: [String: String]()) { dict, param in+ let parts = param.split(separator: "=", maxSplits: 1)+ if parts.count == 2 {+ dict[String(parts[0])] = String(parts[1])+ }+ } : [:]+let organization = queryParams["organization"] ?? "trycua"-+do {let vmController = LumeController()let imageList = try await vmController.getImages(organization: organization)-+// Create a response format that matches the CLI output- let response = imageList.local.map { [- "repository": $0.repository,- "imageId": $0.imageId- ] }-+ let response = imageList.local.map {+ [+ "repository": $0.repository,+ "imageId": $0.imageId,+ ]+ }+return HTTPResponse(statusCode: .ok,headers: ["Content-Type": "application/json"],@@ -294,9 +314,9 @@ extension Server {)}}-+// MARK: - Private Helper Methods-+nonisolated private func startVM(name: String,noDisplay: Bool,@@ -315,10 +335,12 @@ extension Server {)Logger.info("VM started successfully in background", metadata: ["name": name])} catch {- Logger.error("Failed to start VM in background", metadata: [- "name": name,- "error": error.localizedDescription- ])+ Logger.error(+ "Failed to start VM in background",+ metadata: [+ "name": name,+ "error": error.localizedDescription,+ ])}}}diff --git a/libs/lume/src/Server/Requests.swift b/libs/lume/src/Server/Requests.swiftindex 3db114e609..429ad752e2 100644--- a/libs/lume/src/Server/Requests.swift+++ b/libs/lume/src/Server/Requests.swift@@ -1,28 +1,30 @@-import Foundationimport ArgumentParser+import Foundationimport Virtualizationstruct RunVMRequest: Codable {let noDisplay: Bool?let sharedDirectories: [SharedDirectoryRequest]?let recoveryMode: Bool?-+struct SharedDirectoryRequest: Codable {let hostPath: Stringlet 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 directoryvar isDirectory: ObjCBool = falseguard 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)")+ 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,@@ -37,19 +39,17 @@ struct PullRequest: Codable {let name: String?var registry: Stringvar organization: String- var noCache: Bool-+enum CodingKeys: String, CodingKey {- case image, name, registry, organization, noCache+ case image, name, registry, organization}-+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"- noCache = try container.decodeIfPresent(Bool.self, forKey: .noCache) ?? false}}@@ -61,7 +61,7 @@ struct CreateVMRequest: Codable {let diskSize: Stringlet display: Stringlet ipsw: String?-+func parse() throws -> (memory: UInt64, diskSize: UInt64) {return (memory: try parseSize(memory),@@ -75,14 +75,15 @@ struct SetVMRequest: Codable {let memory: String?let diskSize: String?let display: String?-+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 {+ display: try display.map {guard let resolution = VMDisplayResolution(string: $0) else {- throw ValidationError("Invalid display resolution format: \($0). Expected format: WIDTHxHEIGHT")+ throw ValidationError(+ "Invalid display resolution format: \($0). Expected format: WIDTHxHEIGHT")}return resolution}diff --git a/libs/lume/src/Utils/CommandRegistry.swift b/libs/lume/src/Utils/CommandRegistry.swiftindex f7ec317be3..a7e2a7bc98 100644--- a/libs/lume/src/Utils/CommandRegistry.swift+++ b/libs/lume/src/Utils/CommandRegistry.swift@@ -15,7 +15,8 @@ enum CommandRegistry {IPSW.self,Serve.self,Delete.self,- Prune.self+ Prune.self,+ Config.self,]}}diff --git a/libs/lume/src/Utils/CommandUtils.swift b/libs/lume/src/Utils/CommandUtils.swiftindex f400f38335..7061a9b618 100644--- a/libs/lume/src/Utils/CommandUtils.swift+++ b/libs/lume/src/Utils/CommandUtils.swift@@ -2,5 +2,5 @@ import ArgumentParserimport Foundationfunc completeVMName(_ arguments: [String]) -> [String] {- (try? Home().getAllVMDirectories().map(\.name)) ?? []-}\ No newline at end of file+ (try? Home().getAllVMDirectories().map { $0.directory.name }) ?? []+}diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swiftindex 8d736c62bd..abf74de83b 100644--- a/libs/lume/src/VM/VM.swift+++ b/libs/lume/src/VM/VM.swift@@ -7,22 +7,22 @@ struct VMDirContext {let dir: VMDirectoryvar config: VMConfiglet home: Home-+func saveConfig() throws {try dir.saveConfig(config)}-+var name: String { dir.name }var initialized: Bool { dir.initialized() }var diskPath: Path { dir.diskPath }var nvramPath: Path { dir.nvramPath }-+func setDisk(_ size: UInt64) throws {try dir.setDisk(size)}-+func finalize(to name: String) throws {- let vmDir = home.getVMDirectory(name)+ let vmDir = try home.getVMDirectory(name)try FileManager.default.moveItem(at: dir.dir.url, to: vmDir.dir.url)}}@@ -33,21 +33,25 @@ struct VMDirContext {@MainActorclass VM {// MARK: - Properties-+var vmDirContext: VMDirContext@MainActorprivate var virtualizationService: VMVirtualizationService?private let vncService: VNCService- internal let virtualizationServiceFactory: (VMVirtualizationServiceContext) throws -> VMVirtualizationService+ internal let virtualizationServiceFactory:+ (VMVirtualizationServiceContext) throws -> VMVirtualizationServiceprivate let vncServiceFactory: (VMDirectory) -> VNCService// MARK: - Initialization-+init(vmDirContext: VMDirContext,- virtualizationServiceFactory: @escaping (VMVirtualizationServiceContext) throws -> VMVirtualizationService = { try DarwinVirtualizationService(configuration: $0) },- vncServiceFactory: @escaping (VMDirectory) -> VNCService = { DefaultVNCService(vmDirectory: $0) }+ virtualizationServiceFactory: @escaping (VMVirtualizationServiceContext) throws ->+ VMVirtualizationService = { try DarwinVirtualizationService(configuration: $0) },+ vncServiceFactory: @escaping (VMDirectory) -> VNCService = {+ DefaultVNCService(vmDirectory: $0)+ }) {self.vmDirContext = vmDirContextself.virtualizationServiceFactory = virtualizationServiceFactory@@ -58,13 +62,14 @@ class VM {}// MARK: - VM State Management-+private var isRunning: Bool {// First check if we have an IP address- guard let ipAddress = DHCPLeaseParser.getIPAddress(forMAC: vmDirContext.config.macAddress!) else {+ guard let ipAddress = DHCPLeaseParser.getIPAddress(forMAC: vmDirContext.config.macAddress!)+ else {return false}-+// Then check if it's reachablereturn NetworkUtils.isReachable(ipAddress: ipAddress)}@@ -72,7 +77,7 @@ class VM {var details: VMDetails {let isRunning: Bool = self.isRunninglet vncUrl = isRunning ? getVNCUrl() : nil-+return VMDetails(name: vmDirContext.name,os: getOSType(),@@ -82,19 +87,24 @@ class VM {display: vmDirContext.config.display.string,status: isRunning ? "running" : "stopped",vncUrl: vncUrl,- ipAddress: isRunning ? DHCPLeaseParser.getIPAddress(forMAC: vmDirContext.config.macAddress!) : nil+ ipAddress: isRunning+ ? DHCPLeaseParser.getIPAddress(forMAC: vmDirContext.config.macAddress!) : nil)}// MARK: - VM Lifecycle Management-- func run(noDisplay: Bool, sharedDirectories: [SharedDirectory], mount: Path?, vncPort: Int = 0, recoveryMode: Bool = false) async throws {++ func run(+ noDisplay: Bool, sharedDirectories: [SharedDirectory], mount: Path?, vncPort: Int = 0,+ recoveryMode: Bool = false+ ) async throws {guard vmDirContext.initialized else {throw VMError.notInitialized(vmDirContext.name)}-+guard let cpuCount = vmDirContext.config.cpuCount,- let memorySize = vmDirContext.config.memorySize else {+ let memorySize = vmDirContext.config.memorySize+ else {throw VMError.notInitialized(vmDirContext.name)}@@ -105,16 +115,18 @@ class VM {throw VMError.alreadyRunning(vmDirContext.name)}- Logger.info("Running VM with configuration", metadata: [- "cpuCount": "\(cpuCount)",- "memorySize": "\(memorySize)",- "diskSize": "\(vmDirContext.config.diskSize ?? 0)",- "sharedDirectories": sharedDirectories.map(- { $0.string }- ).joined(separator: ", "),- "vncPort": "\(vncPort)",- "recoveryMode": "\(recoveryMode)"- ])+ Logger.info(+ "Running VM with configuration",+ metadata: [+ "cpuCount": "\(cpuCount)",+ "memorySize": "\(memorySize)",+ "diskSize": "\(vmDirContext.config.diskSize ?? 0)",+ "sharedDirectories": sharedDirectories.map(+ { $0.string }+ ).joined(separator: ", "),+ "vncPort": "\(vncPort)",+ "recoveryMode": "\(recoveryMode)",+ ])// Create and configure the VMdo {@@ -127,16 +139,16 @@ class VM {recoveryMode: recoveryMode)virtualizationService = try virtualizationServiceFactory(config)-+let vncInfo = try await setupVNC(noDisplay: noDisplay, port: vncPort)Logger.info("VNC info", metadata: ["vncInfo": vncInfo])-+// Start the VMguard let service = virtualizationService else {throw VMError.internalError("Virtualization service not initialized")}try await service.start()-+while true {try await Task.sleep(nanoseconds: UInt64(1e9))}@@ -164,13 +176,17 @@ class VM {try await service.stop()virtualizationService = nilvncService.stop()- Logger.info("VM stopped successfully via virtualization service", metadata: ["name": vmDirContext.name])+ Logger.info(+ "VM stopped successfully via virtualization service",+ metadata: ["name": vmDirContext.name])return- } catch let error {- Logger.error("Failed to stop VM via virtualization service, falling back to process termination", metadata: [- "name": vmDirContext.name,- "error": "\(error)"- ])+ } catch let error {+ Logger.error(+ "Failed to stop VM via virtualization service, falling back to process termination",+ metadata: [+ "name": vmDirContext.name,+ "error": "\(error)",+ ])// Fall through to process termination}}@@ -178,68 +194,76 @@ class VM {// Try to open config file to get file descriptor - note that this matches with the serve process - so this is only for the command linelet fileHandle = try? FileHandle(forReadingFrom: vmDirContext.dir.configPath.url)guard let fileHandle = fileHandle else {- Logger.error("Failed to open config file - VM not running", metadata: ["name": vmDirContext.name])+ Logger.error(+ "Failed to open config file - VM not running", metadata: ["name": vmDirContext.name]+ )throw VMError.notRunning(vmDirContext.name)}-+// Get the PID of the process holding the lock using lsof commandlet task = Process()task.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof")task.arguments = ["-F", "p", vmDirContext.dir.configPath.path]-+let outputPipe = Pipe()task.standardOutput = outputPipe-+try task.run()task.waitUntilExit()-+let outputData = try outputPipe.fileHandleForReading.readToEnd() ?? Data()guard let outputString = String(data: outputData, encoding: .utf8),- let pidString = outputString.split(separator: "\n").first?.dropFirst(), // Drop the 'p' prefix- let pid = pid_t(pidString) else {+ let pidString = outputString.split(separator: "\n").first?.dropFirst(), // Drop the 'p' prefix+ let pid = pid_t(pidString)+ else {try? fileHandle.close()- Logger.error("Failed to find VM process - VM not running", metadata: ["name": vmDirContext.name])+ Logger.error(+ "Failed to find VM process - VM not running", metadata: ["name": vmDirContext.name])throw VMError.notRunning(vmDirContext.name)}// First try graceful shutdown with SIGINTif kill(pid, SIGINT) == 0 {- Logger.info("Sent SIGINT to VM process", metadata: ["name": vmDirContext.name, "pid": "\(pid)"])+ Logger.info(+ "Sent SIGINT to VM process", metadata: ["name": vmDirContext.name, "pid": "\(pid)"])}// Wait for process to stop with timeoutvar attempts = 0while attempts < 10 {try await Task.sleep(nanoseconds: 1_000_000_000)-+// Check if process still existsif kill(pid, 0) != 0 {// Process is gone, do final cleanupvirtualizationService = nilvncService.stop()try? fileHandle.close()-- Logger.info("VM stopped successfully via process termination", metadata: ["name": vmDirContext.name])++ Logger.info(+ "VM stopped successfully via process termination",+ metadata: ["name": vmDirContext.name])return}attempts += 1}-+// If graceful shutdown failed, force kill the process- Logger.info("Graceful shutdown failed, forcing termination", metadata: ["name": vmDirContext.name])+ Logger.info(+ "Graceful shutdown failed, forcing termination", metadata: ["name": vmDirContext.name])if kill(pid, SIGKILL) == 0 {// Wait a moment for the process to be fully killedtry await Task.sleep(nanoseconds: 2_000_000_000)-+// Do final cleanupvirtualizationService = nilvncService.stop()try? fileHandle.close()-+Logger.info("VM forcefully stopped", metadata: ["name": vmDirContext.name])return}-+// If we get here, something went very wrongtry? fileHandle.close()Logger.error("Failed to stop VM", metadata: ["name": vmDirContext.name, "pid": "\(pid)"])@@ -252,24 +276,25 @@ class VM {vmDirContext.config = vmConfigtry vmDirContext.saveConfig()}-+private func getDiskSize() throws -> DiskSize {let resourceValues = try vmDirContext.diskPath.url.resourceValues(forKeys: [.totalFileAllocatedSizeKey,- .totalFileSizeKey+ .totalFileSizeKey,])-+guard let allocated = resourceValues.totalFileAllocatedSize,- let total = resourceValues.totalFileSize else {+ let total = resourceValues.totalFileSize+ else {throw VMConfigError.invalidDiskSize}-+return DiskSize(allocated: UInt64(allocated), total: UInt64(total))}func resizeDisk(_ newSize: UInt64) throws {let currentSize = try getDiskSize()-+guard newSize >= currentSize.total else {throw VMError.resizeTooSmall(current: currentSize.total, requested: newSize)}@@ -335,18 +360,18 @@ class VM {}// MARK: - VNC Management-+func getVNCUrl() -> String? {return vncService.url}-+private func setupVNC(noDisplay: Bool, port: Int = 0) async throws -> String {guard let service = virtualizationService else {throw VMError.internalError("Virtualization service not initialized")}-+try await vncService.start(port: port, virtualMachine: service.getVirtualMachine())-+guard let url = vncService.url else {throw VMError.vncNotConfigured}@@ -360,11 +385,11 @@ class VM {}// MARK: - Platform-specific Methods-+func getOSType() -> String {fatalError("Must be implemented by subclass")- }-+ }+func createVMVirtualizationServiceContext(cpuCount: Int,memorySize: UInt64,@@ -399,9 +424,10 @@ class VM {}// MARK: - Finalization-+/// Post-installation step to move the VM directory to the home directory- func finalize(to name: String, home: Home) throws {- try vmDirContext.finalize(to: name)+ func finalize(to name: String, home: Home, locationName: String? = nil) throws {+ let vmDir = try home.getVMDirectory(name, locationName: locationName)+ try FileManager.default.moveItem(at: vmDirContext.dir.dir.url, to: vmDir.dir.url)}}