Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

3.8 KB
Raw Blame
import Foundation

/// How the encrypted channel reaches a host: direct on the LAN or through the cloud relay.
public enum HostRoute: Sendable, Equatable {
    case direct, relay
}

public enum HostStreamRequest: Sendable {
    case events(since: Int64, client: String)
    case term(String)
    case screenCandidates(String)

    /// Events a slow consumer may leave unread before the stream ends; `nil` keeps every one.
    var bufferLimit: Int? {
        if case .screenCandidates = self { ScreenCandidate.maxCount + 2 } else { nil }
    }
}

public enum LinkState: Sendable, Equatable {
    case connecting
    case ready(HostRoute)
    /// The relay says the computer isn't connected (asleep, off): the mailbox still works.
    case hostOffline(lastSeen: Date?)
    /// Revoked, or the computer's identity changed: retrying won't help.
    case unauthorized(String)
    /// Can't reach the computer at all (neither directly nor through the relay), or it can't confirm
    /// this device's access for now.
    case failed(String)
}

public protocol HostTransport: Sendable {
    func call(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data
    /// Each element is one event's JSON (what SSE puts after `data:`).
    func stream(_ request: HostStreamRequest) -> AsyncThrowingStream<Data, Error>
    /// A new stream per call: the current state first, then every change.
    func states() -> AsyncStream<LinkState>
    /// Waits however long an outage lasts until the host can be reached again; throws once it can't be.
    func waitForRoute() async throws
}

public extension HostTransport {
    func waitForRoute() async throws {
        for await state in states() {
            try Task.checkCancellation()
            switch state {
            case .ready: return
            case let .unauthorized(message): throw HostError.unauthorized(message)
            case .connecting, .hostOffline, .failed: continue
            }
        }
        try Task.checkCancellation()
        throw HostError.unreachable
    }
}

/// A transport to a remote computer: learns its addresses and keys, and holds messages
/// in the relay mailbox while it is offline. `ChannelTransport` is the real one.
public protocol RemoteTransport: HostTransport {
    func computerUpdates() -> AsyncStream<Computer>
    func enqueue(botId: String, text: String, clientNonce: String, replyTo: String?) async throws
    func cancelQueued(clientNonce: String) async -> MailboxCancel
    func listQueued() async throws -> [QueuedItem]
    func mailboxEvents() -> AsyncStream<MailboxEvent>
    /// Stops for good: closes sockets and ends every stream.
    func shutdown() async
}

public enum HostError: LocalizedError, Sendable, Equatable {
    case http(Int, String)
    case unreachable
    /// With no relay, a computer that's off and a phone that's away look the same.
    case unreachableDirectly
    case computerOffline(lastSeen: Date?)
    case unauthorized(String)
    case upgradeRequired

    public var errorDescription: String? {
        switch self {
        case .http(401, _): "This device isn't allowed on that computer anymore."
        case let .http(_, message): message
        case .unreachable: "Can't reach your computer. Is it on and connected to the internet?"
        case .unreachableDirectly: "Can't reach your computer. Check you're on the same network or that Tailscale is on."
        case .computerOffline: "Your computer is offline."
        case let .unauthorized(message): message
        case .upgradeRequired: "Update Codync to connect to this computer."
        }
    }

    /// The link failed, not the request: the same call can work once the computer is reachable again.
    public var isTransient: Bool {
        switch self {
        case .unreachable, .unreachableDirectly, .computerOffline: true
        default: false
        }
    }
}