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.

feat(lume): add native SSH command with PTY-based password authentication (#913)

Francesco Bonacci5b0ae4064ac1
diff --git a/libs/lume/Package.resolved b/libs/lume/Package.resolved
index de61d2304e..1c581ba0f5 100644
--- a/libs/lume/Package.resolved
+++ b/libs/lume/Package.resolved
@@ -1,5 +1,5 @@
{
- "originHash" : "1cb747fbdb02d29b37fa7c39fd36b4176166b95adbd4c2b0a4475a21cdcf9c19",
+ "originHash" : "b0869df3ba5ae43764c89b3ecf9d8da7c06c91709d49fd9999c35e57cc5e45df",
"pins" : [
{
"identity" : "dynamic",
@@ -28,6 +28,15 @@
"version" : "1.5.0"
}
},
+ {
+ "identity" : "swift-asn1",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-asn1.git",
+ "state" : {
+ "revision" : "810496cf121e525d660cd0ea89a758740476b85f",
+ "version" : "1.5.1"
+ }
+ },
{
"identity" : "swift-atomics",
"kind" : "remoteSourceControl",
@@ -46,6 +55,24 @@
"version" : "0.5.0"
}
},
+ {
+ "identity" : "swift-collections",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-collections.git",
+ "state" : {
+ "revision" : "7b847a3b7008b2dc2f47ca3110d8c782fb2e5c7e",
+ "version" : "1.3.0"
+ }
+ },
+ {
+ "identity" : "swift-crypto",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-crypto.git",
+ "state" : {
+ "revision" : "95ba0316a9b733e92bb6b071255ff46263bbe7dc",
+ "version" : "3.15.1"
+ }
+ },
{
"identity" : "swift-format",
"kind" : "remoteSourceControl",
@@ -73,6 +100,24 @@
"version" : "0.5.0"
}
},
+ {
+ "identity" : "swift-nio",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-nio.git",
+ "state" : {
+ "revision" : "233f61bc2cfbb22d0edeb2594da27a20d2ce514e",
+ "version" : "2.93.0"
+ }
+ },
+ {
+ "identity" : "swift-nio-ssh",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-nio-ssh.git",
+ "state" : {
+ "revision" : "8f33cac67309a13aecc0a4d95044543549b20ffb",
+ "version" : "0.12.0"
+ }
+ },
{
"identity" : "swift-sdk",
"kind" : "remoteSourceControl",
diff --git a/libs/lume/Package.swift b/libs/lume/Package.swift
index ab20cec45e..ed338a5592 100644
--- a/libs/lume/Package.swift
+++ b/libs/lume/Package.swift
@@ -14,7 +14,9 @@ let package = Package(
.package(url: "https://github.com/apple/swift-atomics.git", .upToNextMajor(from: "1.2.0")),
.package(url: "https://github.com/mhdhejazi/Dynamic", branch: "master"),
.package(url: "https://github.com/jpsim/Yams.git", from: "5.0.0"),
- .package(url: "https://github.com/modelcontextprotocol/swift-sdk.git", from: "0.10.0")
+ .package(url: "https://github.com/modelcontextprotocol/swift-sdk.git", from: "0.10.0"),
+ .package(url: "https://github.com/apple/swift-nio.git", from: "2.81.0"),
+ .package(url: "https://github.com/apple/swift-nio-ssh.git", from: "0.12.0")
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
@@ -26,7 +28,11 @@ let package = Package(
.product(name: "Atomics", package: "swift-atomics"),
.product(name: "Dynamic", package: "Dynamic"),
.product(name: "Yams", package: "Yams"),
- .product(name: "MCP", package: "swift-sdk")
+ .product(name: "MCP", package: "swift-sdk"),
+ .product(name: "NIOCore", package: "swift-nio"),
+ .product(name: "NIOPosix", package: "swift-nio"),
+ .product(name: "NIOConcurrencyHelpers", package: "swift-nio"),
+ .product(name: "NIOSSH", package: "swift-nio-ssh")
],
path: "src",
resources: [
diff --git a/libs/lume/src/Commands/SSH.swift b/libs/lume/src/Commands/SSH.swift
new file mode 100644
index 0000000000..229ff689eb
--- /dev/null
+++ b/libs/lume/src/Commands/SSH.swift
@@ -0,0 +1,99 @@
+import ArgumentParser
+import Foundation
+
+struct SSH: AsyncParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "ssh",
+ abstract: "Connect to a VM via SSH or execute commands remotely",
+ discussion: """
+ Connect to a running VM via SSH. Can be used for interactive sessions
+ or to execute a single command.
+
+ This command handles password authentication automatically, so you don't
+ need sshpass installed. VMs created with --unattended use credentials
+ lume/lume by default.
+
+ Examples:
+ lume ssh my-vm # Interactive shell
+ lume ssh my-vm "ls -la" # Execute command
+ lume ssh my-vm "cd /app && npm test" # Execute complex command
+ """
+ )
+
+ @Argument(help: "Name of the virtual machine", completion: .custom(completeVMName))
+ var name: String
+
+ @Argument(parsing: .remaining, help: "Command to execute (omit for interactive shell)")
+ var command: [String] = []
+
+ @Option(name: [.short, .long], help: "SSH username (default: lume)")
+ var user: String = "lume"
+
+ @Option(name: [.short, .long], help: "SSH password (default: lume)")
+ var password: String = "lume"
+
+ @Option(name: .customLong("storage"), help: "Storage location name or path")
+ var storage: String?
+
+ @Option(name: [.short, .long], help: "Command timeout in seconds (0 for no timeout, default: 60)")
+ var timeout: Int = 60
+
+ @MainActor
+ func run() async throws {
+ // Record telemetry
+ TelemetryClient.shared.record(event: "lume_ssh")
+
+ let controller = LumeController()
+
+ // Get VM details
+ let vmDetails: VMDetails
+ do {
+ vmDetails = try controller.getDetails(name: name, storage: storage)
+ } catch {
+ throw SSHError.vmNotFound(name)
+ }
+
+ // Validate VM state
+ guard vmDetails.status == "running" else {
+ throw SSHError.vmNotRunning(name)
+ }
+
+ guard let ipAddress = vmDetails.ipAddress, !ipAddress.isEmpty else {
+ throw SSHError.noIPAddress(name)
+ }
+
+ guard vmDetails.sshAvailable == true else {
+ throw SSHError.sshNotAvailable(name)
+ }
+
+ // Create SSH client
+ let sshClient = SSHClient(
+ host: ipAddress,
+ port: 22,
+ user: user,
+ password: password
+ )
+
+ if command.isEmpty {
+ // Interactive mode
+ try await sshClient.interactive()
+ } else {
+ // Execute command
+ let fullCommand = command.joined(separator: " ")
+ let result = try await sshClient.execute(
+ command: fullCommand,
+ timeout: TimeInterval(timeout)
+ )
+
+ // Print output
+ if !result.output.isEmpty {
+ print(result.output)
+ }
+
+ // Exit with same code as remote command
+ if result.exitCode != 0 {
+ throw ExitCode(result.exitCode)
+ }
+ }
+ }
+}
diff --git a/libs/lume/src/SSH/SSHClient.swift b/libs/lume/src/SSH/SSHClient.swift
new file mode 100644
index 0000000000..d1566b82d9
--- /dev/null
+++ b/libs/lume/src/SSH/SSHClient.swift
@@ -0,0 +1,496 @@
+import Foundation
+import NIOCore
+import NIOConcurrencyHelpers
+import NIOPosix
+import NIOSSH
+
+/// Result of an SSH command execution
+public struct SSHResult: Sendable {
+ public let exitCode: Int32
+ public let output: String
+
+ public init(exitCode: Int32, output: String) {
+ self.exitCode = exitCode
+ self.output = output
+ }
+}
+
+/// SSH client using SwiftNIO SSH for typed, versioned API
+public actor SSHClient {
+ private let host: String
+ private let port: Int
+ private let user: String
+ private let password: String
+ private let eventLoopGroup: MultiThreadedEventLoopGroup
+
+ public init(
+ host: String,
+ port: UInt16 = 22,
+ user: String = "lume",
+ password: String = "lume"
+ ) {
+ self.host = host
+ self.port = Int(port)
+ self.user = user
+ self.password = password
+ self.eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
+ }
+
+ deinit {
+ try? eventLoopGroup.syncShutdownGracefully()
+ }
+
+ /// Execute a command on the remote host
+ public func execute(command: String, timeout: TimeInterval = 60) async throws -> SSHResult {
+ let channel = try await connect()
+
+ // Create a promise for the result
+ let resultPromise = channel.eventLoop.makePromise(of: SSHResult.self)
+
+ // Create the SSH child channel for command execution
+ let sshHandler = try await channel.pipeline.handler(type: NIOSSHHandler.self).get()
+
+ let childChannelPromise = channel.eventLoop.makePromise(of: Channel.self)
+ sshHandler.createChannel(childChannelPromise) { childChannel, channelType in
+ guard channelType == .session else {
+ return channel.eventLoop.makeFailedFuture(SSHError.connectionFailed("Invalid channel type"))
+ }
+
+ return childChannel.eventLoop.makeCompletedFuture {
+ let execHandler = CommandExecHandler(command: command, resultPromise: resultPromise)
+ try childChannel.pipeline.syncOperations.addHandler(execHandler)
+ }
+ }
+
+ let childChannel = try await childChannelPromise.futureResult.get()
+
+ // Set up timeout if specified
+ if timeout > 0 {
+ let timeoutTask = channel.eventLoop.scheduleTask(in: .seconds(Int64(timeout))) {
+ resultPromise.fail(SSHError.timeout)
+ childChannel.close(promise: nil)
+ }
+
+ // Cancel timeout when result is received
+ resultPromise.futureResult.whenComplete { _ in
+ timeoutTask.cancel()
+ }
+ }
+
+ // Wait for command completion
+ let result = try await resultPromise.futureResult.get()
+
+ // Clean up
+ try? await childChannel.closeFuture.get()
+ try? await channel.close().get()
+
+ return result
+ }
+
+ /// Start an interactive SSH session
+ public func interactive() async throws {
+ let channel = try await connect()
+
+ // Create the SSH child channel for interactive session
+ let sshHandler = try await channel.pipeline.handler(type: NIOSSHHandler.self).get()
+
+ let childChannelPromise = channel.eventLoop.makePromise(of: Channel.self)
+ let sessionCompletePromise = channel.eventLoop.makePromise(of: Void.self)
+
+ sshHandler.createChannel(childChannelPromise) { childChannel, channelType in
+ guard channelType == .session else {
+ return channel.eventLoop.makeFailedFuture(SSHError.connectionFailed("Invalid channel type"))
+ }
+
+ return childChannel.eventLoop.makeCompletedFuture {
+ let interactiveHandler = InteractiveSessionHandler(completePromise: sessionCompletePromise)
+ try childChannel.pipeline.syncOperations.addHandler(interactiveHandler)
+ }
+ }
+
+ let childChannel = try await childChannelPromise.futureResult.get()
+
+ // Wait for the session to complete
+ try await sessionCompletePromise.futureResult.get()
+
+ // Clean up
+ try? await childChannel.closeFuture.get()
+ try? await channel.close().get()
+ }
+
+ /// Connect to the SSH server and return the channel
+ private func connect() async throws -> Channel {
+ let bootstrap = ClientBootstrap(group: eventLoopGroup)
+ .channelInitializer { channel in
+ channel.eventLoop.makeCompletedFuture {
+ let sshHandler = NIOSSHHandler(
+ role: .client(
+ .init(
+ userAuthDelegate: PasswordAuthDelegate(
+ username: self.user,
+ password: self.password
+ ),
+ serverAuthDelegate: AcceptAllHostKeysDelegate()
+ )
+ ),
+ allocator: channel.allocator,
+ inboundChildChannelInitializer: nil
+ )
+ try channel.pipeline.syncOperations.addHandler(sshHandler)
+ try channel.pipeline.syncOperations.addHandler(SSHErrorHandler())
+ }
+ }
+ .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
+ .channelOption(ChannelOptions.socket(SocketOptionLevel(IPPROTO_TCP), TCP_NODELAY), value: 1)
+ .connectTimeout(.seconds(30))
+
+ do {
+ return try await bootstrap.connect(host: host, port: port).get()
+ } catch {
+ throw SSHError.connectionFailed(error.localizedDescription)
+ }
+ }
+}
+
+// MARK: - Host Key Validation Delegate
+
+/// Accepts all host keys (for internal VM use only - not for production)
+private final class AcceptAllHostKeysDelegate: NIOSSHClientServerAuthenticationDelegate, Sendable {
+ func validateHostKey(
+ hostKey: NIOSSHPublicKey,
+ validationCompletePromise: EventLoopPromise<Void>
+ ) {
+ // Accept all host keys for internal VM connections
+ // In production, you should validate against known hosts
+ validationCompletePromise.succeed(())
+ }
+}
+
+// MARK: - Password Authentication Delegate
+
+/// Handles password-based authentication
+private final class PasswordAuthDelegate: NIOSSHClientUserAuthenticationDelegate, Sendable {
+ private let username: String
+ private let password: String
+ private let didAttempt: NIOLockedValueBox<Bool>
+
+ init(username: String, password: String) {
+ self.username = username
+ self.password = password
+ self.didAttempt = NIOLockedValueBox(false)
+ }
+
+ func nextAuthenticationType(
+ availableMethods: NIOSSHAvailableUserAuthenticationMethods,
+ nextChallengePromise: EventLoopPromise<NIOSSHUserAuthenticationOffer?>
+ ) {
+ // Only attempt password auth once
+ let alreadyAttempted = didAttempt.withLockedValue { attempted in
+ if attempted {
+ return true
+ }
+ attempted = true
+ return false
+ }
+
+ if alreadyAttempted {
+ // We already tried, authentication failed
+ nextChallengePromise.fail(SSHError.authenticationFailed)
+ return
+ }
+
+ guard availableMethods.contains(.password) else {
+ nextChallengePromise.fail(SSHError.authenticationFailed)
+ return
+ }
+
+ nextChallengePromise.succeed(
+ NIOSSHUserAuthenticationOffer(
+ username: username,
+ serviceName: "",
+ offer: .password(.init(password: password))
+ )
+ )
+ }
+}
+
+// MARK: - Command Execution Handler
+
+/// Handles command execution on an SSH channel
+private final class CommandExecHandler: ChannelDuplexHandler {
+ typealias InboundIn = SSHChannelData
+ typealias InboundOut = ByteBuffer
+ typealias OutboundIn = ByteBuffer
+ typealias OutboundOut = SSHChannelData
+
+ private let command: String
+ private var resultPromise: EventLoopPromise<SSHResult>?
+ private var outputBuffer: ByteBuffer
+ private var exitStatus: Int32?
+ private var channelClosed = false
+
+ init(command: String, resultPromise: EventLoopPromise<SSHResult>) {
+ self.command = command
+ self.resultPromise = resultPromise
+ self.outputBuffer = ByteBuffer()
+ }
+
+ func handlerAdded(context: ChannelHandlerContext) {
+ context.channel.setOption(ChannelOptions.allowRemoteHalfClosure, value: true).whenFailure { error in
+ context.fireErrorCaught(error)
+ }
+ }
+
+ func channelActive(context: ChannelHandlerContext) {
+ // Send exec request
+ let execRequest = SSHChannelRequestEvent.ExecRequest(command: command, wantReply: true)
+ context.triggerUserOutboundEvent(execRequest).whenFailure { [weak self] error in
+ self?.failWithError(error, context: context)
+ }
+ }
+
+ func channelRead(context: ChannelHandlerContext, data: NIOAny) {
+ let channelData = unwrapInboundIn(data)
+
+ switch channelData.data {
+ case .byteBuffer(let buffer):
+ // Collect all output (stdout and stderr)
+ var mutableBuffer = buffer
+ outputBuffer.writeBuffer(&mutableBuffer)
+ case .fileRegion:
+ // Not expected, ignore
+ break
+ }
+ }
+
+ func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
+ switch event {
+ case let status as SSHChannelRequestEvent.ExitStatus:
+ exitStatus = Int32(status.exitStatus)
+ checkCompletion(context: context)
+
+ case let channelEvent as ChannelEvent where channelEvent == .inputClosed:
+ channelClosed = true
+ checkCompletion(context: context)
+
+ default:
+ context.fireUserInboundEventTriggered(event)
+ }
+ }
+
+ func channelInactive(context: ChannelHandlerContext) {
+ channelClosed = true
+ checkCompletion(context: context)
+ }
+
+ func errorCaught(context: ChannelHandlerContext, error: Error) {
+ failWithError(error, context: context)
+ }
+
+ func handlerRemoved(context: ChannelHandlerContext) {
+ // If we haven't completed yet, complete with what we have
+ checkCompletion(context: context)
+ }
+
+ private func checkCompletion(context: ChannelHandlerContext) {
+ // Only complete if we have both exit status and channel is closed (or we have exit status)
+ guard let promise = resultPromise else { return }
+
+ // Complete when we have exit status (some servers close channel before sending exit status)
+ if let status = exitStatus {
+ resultPromise = nil
+ let output = outputBuffer.readString(length: outputBuffer.readableBytes) ?? ""
+ promise.succeed(SSHResult(exitCode: status, output: output))
+ } else if channelClosed {
+ // Channel closed without exit status - assume success with exit code 0
+ resultPromise = nil
+ let output = outputBuffer.readString(length: outputBuffer.readableBytes) ?? ""
+ promise.succeed(SSHResult(exitCode: 0, output: output))
+ }
+ }
+
+ private func failWithError(_ error: Error, context: ChannelHandlerContext) {
+ if let promise = resultPromise {
+ resultPromise = nil
+ if let sshError = error as? SSHError {
+ promise.fail(sshError)
+ } else {
+ promise.fail(SSHError.commandFailed(exitCode: -1, message: error.localizedDescription))
+ }
+ }
+ context.close(promise: nil)
+ }
+}
+
+// MARK: - Interactive Session Handler
+
+/// Handles interactive SSH sessions with stdin/stdout passthrough
+private final class InteractiveSessionHandler: ChannelDuplexHandler {
+ typealias InboundIn = SSHChannelData
+ typealias InboundOut = ByteBuffer
+ typealias OutboundIn = ByteBuffer
+ typealias OutboundOut = SSHChannelData
+
+ private var completePromise: EventLoopPromise<Void>?
+ private var stdinSource: DispatchSourceRead?
+ private var originalTermios: termios?
+ private let stdinFD = FileHandle.standardInput.fileDescriptor
+
+ init(completePromise: EventLoopPromise<Void>) {
+ self.completePromise = completePromise
+ }
+
+ func handlerAdded(context: ChannelHandlerContext) {
+ context.channel.setOption(ChannelOptions.allowRemoteHalfClosure, value: true).whenFailure { error in
+ context.fireErrorCaught(error)
+ }
+ }
+
+ func channelActive(context: ChannelHandlerContext) {
+ // Request a pseudo-terminal
+ let ptyRequest = SSHChannelRequestEvent.PseudoTerminalRequest(
+ wantReply: true,
+ term: "xterm-256color",
+ terminalCharacterWidth: 80,
+ terminalRowHeight: 24,
+ terminalPixelWidth: 0,
+ terminalPixelHeight: 0,
+ terminalModes: .init([:])
+ )
+
+ context.triggerUserOutboundEvent(ptyRequest).flatMap {
+ // Request a shell
+ let shellRequest = SSHChannelRequestEvent.ShellRequest(wantReply: true)
+ return context.triggerUserOutboundEvent(shellRequest)
+ }.whenComplete { [weak self] result in
+ switch result {
+ case .success:
+ self?.setupTerminalAndStdin(context: context)
+ case .failure(let error):
+ self?.failWithError(error, context: context)
+ }
+ }
+ }
+
+ private func setupTerminalAndStdin(context: ChannelHandlerContext) {
+ // Save and set raw terminal mode
+ var rawTermios = termios()
+ if tcgetattr(stdinFD, &rawTermios) == 0 {
+ originalTermios = rawTermios
+ cfmakeraw(&rawTermios)
+ tcsetattr(stdinFD, TCSANOW, &rawTermios)
+ }
+
+ // Set up stdin reading
+ let source = DispatchSource.makeReadSource(fileDescriptor: stdinFD, queue: .global())
+ stdinSource = source
+
+ let loopBoundContext = NIOLoopBound(context, eventLoop: context.eventLoop)
+ let fd = stdinFD
+
+ source.setEventHandler { [weak self] in
+ guard self != nil else { return }
+
+ var buffer = [UInt8](repeating: 0, count: 1024)
+ let bytesRead = Darwin.read(fd, &buffer, buffer.count)
+
+ if bytesRead > 0 {
+ let data = Data(buffer[0..<bytesRead])
+ loopBoundContext.value.eventLoop.execute {
+ var byteBuffer = loopBoundContext.value.channel.allocator.buffer(capacity: bytesRead)
+ byteBuffer.writeBytes(data)
+ let channelData = SSHChannelData(type: .channel, data: .byteBuffer(byteBuffer))
+ loopBoundContext.value.writeAndFlush(NIOAny(channelData), promise: nil)
+ }
+ } else if bytesRead == 0 {
+ // EOF on stdin
+ loopBoundContext.value.eventLoop.execute {
+ loopBoundContext.value.close(mode: .output, promise: nil)
+ }
+ }
+ }
+
+ source.setCancelHandler { [weak self] in
+ self?.restoreTerminal()
+ }
+
+ source.resume()
+ }
+
+ func channelRead(context: ChannelHandlerContext, data: NIOAny) {
+ let channelData = unwrapInboundIn(data)
+
+ switch channelData.data {
+ case .byteBuffer(let buffer):
+ // Write to stdout
+ let stdoutFD = FileHandle.standardOutput.fileDescriptor
+ buffer.withUnsafeReadableBytes { ptr in
+ _ = Darwin.write(stdoutFD, ptr.baseAddress, ptr.count)
+ }
+ case .fileRegion:
+ break
+ }
+ }
+
+ func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
+ if let channelEvent = event as? ChannelEvent, channelEvent == .inputClosed {
+ complete(context: context)
+ } else {
+ context.fireUserInboundEventTriggered(event)
+ }
+ }
+
+ func channelInactive(context: ChannelHandlerContext) {
+ complete(context: context)
+ }
+
+ func errorCaught(context: ChannelHandlerContext, error: Error) {
+ failWithError(error, context: context)
+ }
+
+ func handlerRemoved(context: ChannelHandlerContext) {
+ cleanup()
+ }
+
+ private func complete(context: ChannelHandlerContext) {
+ cleanup()
+ if let promise = completePromise {
+ completePromise = nil
+ promise.succeed(())
+ }
+ }
+
+ private func failWithError(_ error: Error, context: ChannelHandlerContext) {
+ cleanup()
+ if let promise = completePromise {
+ completePromise = nil
+ promise.fail(error)
+ }
+ context.close(promise: nil)
+ }
+
+ private func cleanup() {
+ stdinSource?.cancel()
+ stdinSource = nil
+ restoreTerminal()
+ }
+
+ private func restoreTerminal() {
+ if var original = originalTermios {
+ tcsetattr(stdinFD, TCSANOW, &original)
+ originalTermios = nil
+ }
+ }
+}
+
+// MARK: - Error Handler
+
+/// Handles errors in the SSH pipeline
+private final class SSHErrorHandler: ChannelInboundHandler {
+ typealias InboundIn = Any
+
+ func errorCaught(context: ChannelHandlerContext, error: Error) {
+ // Log or handle the error appropriately
+ context.close(promise: nil)
+ }
+}
diff --git a/libs/lume/src/SSH/SSHErrors.swift b/libs/lume/src/SSH/SSHErrors.swift
new file mode 100644
index 0000000000..82a5264c3f
--- /dev/null
+++ b/libs/lume/src/SSH/SSHErrors.swift
@@ -0,0 +1,43 @@
+import Foundation
+
+/// Errors that can occur during SSH operations
+public enum SSHError: Error, LocalizedError {
+ case vmNotFound(String)
+ case vmNotRunning(String)
+ case noIPAddress(String)
+ case sshNotAvailable(String)
+ case connectionFailed(String)
+ case authenticationFailed
+ case commandFailed(exitCode: Int32, message: String)
+ case timeout
+ case ptyCreationFailed
+ case forkFailed
+ case execFailed
+
+ public var errorDescription: String? {
+ switch self {
+ case .vmNotFound(let name):
+ return "VM '\(name)' not found"
+ case .vmNotRunning(let name):
+ return "VM '\(name)' is not running"
+ case .noIPAddress(let name):
+ return "VM '\(name)' has no IP address. Wait for it to boot completely."
+ case .sshNotAvailable(let name):
+ return "SSH is not available on VM '\(name)'. Ensure SSH/Remote Login is enabled."
+ case .connectionFailed(let message):
+ return "SSH connection failed: \(message)"
+ case .authenticationFailed:
+ return "SSH authentication failed. Check username and password."
+ case .commandFailed(let exitCode, let message):
+ return "Command failed with exit code \(exitCode): \(message)"
+ case .timeout:
+ return "SSH operation timed out"
+ case .ptyCreationFailed:
+ return "Failed to create pseudo-terminal"
+ case .forkFailed:
+ return "Failed to fork process"
+ case .execFailed:
+ return "Failed to execute SSH"
+ }
+ }
+}
diff --git a/libs/lume/src/Server/MCPServer.swift b/libs/lume/src/Server/MCPServer.swift
index 4bb7ed21d5..2a7c65abc0 100644
--- a/libs/lume/src/Server/MCPServer.swift
+++ b/libs/lume/src/Server/MCPServer.swift
@@ -154,7 +154,7 @@ final class LumeMCPServer {
Shared files appear in the VM at `/Volumes/My Shared Files/`.
### 4. Execute Commands
- Run commands via SSH (requires `sshpass` installed on host):
+ Run commands via SSH:
```
lume_exec(name: "sandbox", command: "cd /Volumes/My\\\\ Shared\\\\ Files && npm test")
```
@@ -671,69 +671,30 @@ final class LumeMCPServer {
)
}
- // Find sshpass in common locations
- let sshpassPaths = [
- "/opt/homebrew/bin/sshpass",
- "/usr/local/bin/sshpass",
- "/usr/bin/sshpass"
- ]
-
- var sshpassPath: String?
- for path in sshpassPaths {
- if FileManager.default.fileExists(atPath: path) {
- sshpassPath = path
- break
- }
- }
-
- guard let sshpass = sshpassPath else {
- return CallTool.Result(
- content: [.text("Error: sshpass not found. Install it with: brew install hudochenkov/sshpass/sshpass")],
- isError: true
- )
- }
-
- // Execute command via SSH using sshpass
- let process = Process()
- process.executableURL = URL(fileURLWithPath: sshpass)
- process.arguments = [
- "-p", password,
- "ssh",
- "-o", "StrictHostKeyChecking=no",
- "-o", "UserKnownHostsFile=/dev/null",
- "-o", "LogLevel=ERROR",
- "\(user)@\(ip)",
- command
- ]
-
- let outputPipe = Pipe()
- let errorPipe = Pipe()
- process.standardOutput = outputPipe
- process.standardError = errorPipe
-
- try process.run()
- process.waitUntilExit()
-
- let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
- let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
-
- let output = String(data: outputData, encoding: .utf8) ?? ""
- let errorOutput = String(data: errorData, encoding: .utf8) ?? ""
+ // Execute command via native SSH client (no sshpass dependency)
+ let sshClient = SSHClient(
+ host: ip,
+ port: 22,
+ user: user,
+ password: password
+ )
- let isError = process.terminationStatus != 0
+ do {
+ let sshResult = try await sshClient.execute(command: command, timeout: 60)
- var result = output
- if !errorOutput.isEmpty {
- if !result.isEmpty {
- result += "\n"
+ var result = sshResult.output
+ if result.isEmpty {
+ result = sshResult.exitCode == 0
+ ? "Command completed successfully (no output)"
+ : "Command failed with exit code \(sshResult.exitCode)"
}
- result += errorOutput
- }
- if result.isEmpty {
- result = isError ? "Command failed with exit code \(process.terminationStatus)" : "Command completed successfully (no output)"
- }
- return CallTool.Result(content: [.text(result)], isError: isError)
+ return CallTool.Result(content: [.text(result)], isError: sshResult.exitCode != 0)
+ } catch let error as SSHError {
+ return CallTool.Result(content: [.text("Error: \(error.localizedDescription)")], isError: true)
+ } catch {
+ return CallTool.Result(content: [.text("Error: \(error.localizedDescription)")], isError: true)
+ }
}
private func handleCreateVM(_ args: [String: Value]?) async throws -> CallTool.Result {
diff --git a/libs/lume/src/Utils/CommandRegistry.swift b/libs/lume/src/Utils/CommandRegistry.swift
index 36778cc822..5de3d885c8 100644
--- a/libs/lume/src/Utils/CommandRegistry.swift
+++ b/libs/lume/src/Utils/CommandRegistry.swift
@@ -13,6 +13,7 @@ enum CommandRegistry {
List.self,
Run.self,
Stop.self,
+ SSH.self,
IPSW.self,
Serve.self,
Delete.self,