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.

21.6 KB
Raw Blame
import Foundation

public enum HostEvent: Sendable {
    case icons([String: CustomIcon], revision: Int64)
    /// The stream's first event; `network` is nil from hosts before the network view.
    case hello(hostId: String, rev: Int64, usage: Usage, screen: ScreenState?, network: NetworkView?)
    case bot(Bot)
    case botDeleted(id: String, rev: Int64)
    case entry(Entry)
    case usage(Usage)
    case screen(ScreenState)
    /// An artifact published or renamed (the catch-up replays it too).
    case artifact(Artifact)
    /// For the voice of a call on this device (only the device holding the call receives it).
    case call(CallCue)
    /// The computer's network changed (members, roles, presence, offered bots, cloud assistants).
    case network(NetworkView)
    case resync
    /// An event this app version couldn't decode (host newer/older than the app).
    case undecodable(type: String)
}

/// A setup terminal's output stream.
public enum TermEvent: Sendable {
    case output(Data)
    case exit(Int)
}

public struct Empty: Codable, Sendable {
    public init() {}
}

/// A full editor update must explicitly clear a previous model override.
struct BotUpdate: Encodable {
    let draft: BotDraft
    private enum CodingKeys: String, CodingKey { case model, mode }

    func encode(to encoder: Encoder) throws {
        try draft.encode(to: encoder)
        var container = encoder.container(keyedBy: CodingKeys.self)
        if draft.model == nil { try container.encodeNil(forKey: .model) }
        if draft.mode == nil { try container.encodeNil(forKey: .mode) }
    }
}

public struct HostClient: Sendable {
    public let transport: any HostTransport

    public init(transport: any HostTransport) {
        self.transport = transport
    }

    static let decoder = JSONDecoder()
    static let encoder = JSONEncoder()

    public func call<T: Decodable>(_ method: String, _ body: some Encodable = Empty(), timeout: TimeInterval = 20) async throws -> T {
        let data = try await transport.call(method, body: try Self.encoder.encode(body), timeout: timeout)
        return try Self.decoder.decode(T.self, from: data)
    }

    /// Catch-up since `since`, then live updates.
    public func events(since: Int64, client: String) -> AsyncThrowingStream<HostEvent, Error> {
        map(transport.stream(.events(since: since, client: client)), Self.parseEvent)
    }

    /// A setup terminal's output: everything so far, then live, finishing after `.exit`.
    public func termOutput(_ term: String) -> AsyncThrowingStream<TermEvent, Error> {
        map(transport.stream(.term(term))) { data in
            struct Raw: Decodable { var type: String; var data: String?; var code: Int? }
            guard let raw = try? Self.decoder.decode(Raw.self, from: data) else { return nil }
            switch raw.type {
            case "output": return raw.data.flatMap { Data(base64Encoded: $0) }.map(TermEvent.output)
            case "exit": return .exit(raw.code ?? -1)
            default: return nil
            }
        }
    }

    private func map<T: Sendable>(_ source: AsyncThrowingStream<Data, Error>, _ parse: @escaping @Sendable (Data) -> T?) -> AsyncThrowingStream<T, Error> {
        AsyncThrowingStream { continuation in
            let task = Task {
                do {
                    for try await data in source {
                        if let event = parse(data) { continuation.yield(event) }
                    }
                    continuation.finish()
                } catch {
                    continuation.finish(throwing: error)
                }
            }
            continuation.onTermination = { _ in task.cancel() }
        }
    }

    public static func parseEvent(_ data: Data) -> HostEvent? {
        struct Envelope: Decodable {
            var type: String
            var hostId: String?
            var rev: Int64?
        }
        struct BotWrap: Decodable { var bot: Bot }
        struct StubWrap: Decodable { var bot: BotStub }
        struct EntryWrap: Decodable { var entry: Entry }
        struct UsageWrap: Decodable { var usage: Usage }
        struct ScreenWrap: Decodable { var screen: ScreenState }
        struct ArtifactWrap: Decodable { var artifact: Artifact }
        struct NetworkWrap: Decodable { var network: NetworkView }
        let d = decoder
        guard let env = try? d.decode(Envelope.self, from: data) else { return nil }
        switch env.type {
        case "icons":
            struct Icons: Decodable { var icons: [String: CustomIcon]; var iconsRevision: Int64? }
            return (try? d.decode(Icons.self, from: data)).map { .icons($0.icons, revision: $0.iconsRevision ?? 0) }
        case "hello":
            let usage = (try? d.decode(UsageWrap.self, from: data))?.usage ?? Usage()
            let screen = (try? d.decode(ScreenWrap.self, from: data))?.screen
            let network = (try? d.decode(NetworkWrap.self, from: data))?.network
            return .hello(hostId: env.hostId ?? "", rev: env.rev ?? 0, usage: usage, screen: screen, network: network)
        case "bot":
            if let stub = try? d.decode(StubWrap.self, from: data), stub.bot.deleted == true {
                return .botDeleted(id: stub.bot.id, rev: stub.bot.rev)
            }
            return (try? d.decode(BotWrap.self, from: data)).map { .bot($0.bot) } ?? .undecodable(type: "bot")
        case "entry":
            return (try? d.decode(EntryWrap.self, from: data)).map { .entry($0.entry) } ?? .undecodable(type: "entry")
        case "usage":
            return (try? d.decode(UsageWrap.self, from: data)).map { .usage($0.usage) }
        case "screen":
            return (try? d.decode(ScreenWrap.self, from: data)).map { .screen($0.screen) }
        case "artifact":
            // Not worth a rewind: a card or the Library reads the artifact again.
            return (try? d.decode(ArtifactWrap.self, from: data)).map { .artifact($0.artifact) }
        case "call":
            return (try? d.decode(CallCue.self, from: data)).map { .call($0) }
        case "network":
            // Not worth a rewind: the next stream's hello carries the view again.
            return (try? d.decode(NetworkWrap.self, from: data)).map { .network($0.network) }
        case "resync":
            return .resync
        default:
            return nil
        }
    }
}

// MARK: - Typed calls

public extension HostClient {
    func hello() async throws -> Hello { try await call("hello") }

    /// The computer's network, read-only (hosts before it: "unknown method").
    func networkView() async throws -> NetworkView { try await call("networkView") }

    /// Updates a computer that's behind this app to the latest release (`Hello.canUpdate`).
    func installHostUpdate() async throws {
        let _: Empty = try await call("installHostUpdate")
    }

    /// The computer asks its user (up to 90 seconds), then signs `claim` for this phone's account
    /// (`Hello.canJoinAccount`), as JSON to pass on to `CloudClient.completeClaim` as it came.
    func joinAccount(_ claim: CloudClaim, certificate: DeviceCertificate) async throws -> Data {
        struct Body: Encodable { var claimId: String; var nonce: String; var certificate: DeviceCertificate }
        let body = Body(claimId: claim.claimId, nonce: claim.nonce, certificate: certificate)
        return try await transport.call("joinAccount", body: try Self.encoder.encode(body), timeout: 120)
    }

    func history(botId: String, beforeSeq: Int64, limit: Int = 100) async throws -> [Entry] {
        struct Body: Encodable { var botId: String; var beforeSeq: Int64; var limit: Int }
        struct Res: Decodable { var entries: [Entry] }
        let res: Res = try await call("history", Body(botId: botId, beforeSeq: beforeSeq, limit: limit))
        return res.entries
    }

    /// What a voice call carried, from the computer: the chat this device holds may not reach back to it.
    func callEntries(botId: String, call: String) async throws -> [Entry] {
        struct Res: Decodable { var entries: [Entry] }
        let res: Res = try await self.call("callEntries", ["botId": botId, "callId": call])
        return res.entries
    }

    /// The newest 200 bot-to-bot notices between a bot's chat and a peer, oldest first.
    func botConversation(botId: String, peerId: String) async throws -> [Entry] {
        struct Res: Decodable { var entries: [Entry] }
        let res: Res = try await call("botConversation", ["botId": botId, "peerId": peerId])
        return res.entries
    }

    /// Creates a group chat (or returns the one these bots already share).
    func createGroup(_ draft: GroupDraft) async throws -> Bot {
        struct Res: Decodable { var bot: Bot }
        let res: Res = try await call("createBot", draft)
        return res.bot
    }

    func updateGroup(_ draft: GroupDraft) async throws -> Bot {
        struct Res: Decodable { var bot: Bot }
        let res: Res = try await call("updateBot", draft)
        return res.bot
    }

    func createBot(_ draft: BotDraft) async throws -> Bot {
        struct Res: Decodable { var bot: Bot }
        let res: Res = try await call("createBot", draft)
        return res.bot
    }

    func updateBot(_ draft: BotDraft) async throws -> Bot {
        struct Res: Decodable { var bot: Bot }
        let res: Res = try await call("updateBot", BotUpdate(draft: draft))
        return res.bot
    }

    /// Puts the bot in `section`, or takes it out of its own (nil, sent as null); nothing else changes.
    func setSection(_ botId: String, to section: String?) async throws {
        let body: [String: String?] = ["id": botId, "section": section]
        let _: Empty = try await call("updateBot", body)
    }

    func deleteBot(_ id: String) async throws {
        let _: Empty = try await call("deleteBot", ["botId": id])
    }

    /// The roster as the user dragged it, top first.
    func reorderBots(_ ids: [String]) async throws {
        let _: Empty = try await call("reorderBots", ["ids": ids])
    }

    /// Moves every bot of the computer in section `from` to `to` (a name already in use merges the
    /// two); nil removes the section, its bots staying without one.
    func renameSection(from: String, to: String?) async throws {
        let body: [String: String?] = ["from": from, "to": to]
        let _: Empty = try await call("renameSection", body)
    }

    /// The chat read; a no-op when nothing there is unread.
    func markRead(_ id: String) async throws {
        let _: Empty = try await call("markRead", ["botId": id])
    }

    /// Toggles the user's `emoji` reaction on a chat message.
    func react(entryId: String, emoji: String) async throws -> Entry {
        struct Res: Decodable { var entry: Entry }
        let res: Res = try await call("react", ["entryId": entryId, "emoji": emoji])
        return res.entry
    }

    /// `replyTo`: the chat message this one quotes.
    /// `pasted`: what the user pasted rather than typed, which memory never takes as their own words.
    /// `call`: the voice call it was said in (on-device or speech to text).
    func send(botId: String, text: String, clientNonce: String, replyTo: String? = nil, attachments: [String]? = nil,
              pasted: [String]? = nil, call: String? = nil) async throws -> Entry {
        struct Body: Encodable {
            var botId: String; var text: String; var clientNonce: String; var replyTo: String?; var attachments: [String]?
            var pasted: [String]?; var call: String?
        }
        struct Res: Decodable { var entry: Entry }
        let body = Body(botId: botId, text: text, clientNonce: clientNonce, replyTo: replyTo, attachments: attachments,
                        pasted: pasted?.isEmpty == false ? pasted : nil, call: call)
        let res: Res = try await self.call("send", body)
        return res.entry
    }

    /// Bytes per `upload` call: base64 of it stays well under the channel's 1 MiB message.
    static let uploadChunk = 384 * 1024

    /// Sends one file in chunks for a later `send`; `id` names the upload there.
    func upload(botId: String, id: String, name: String, data: Data) async throws {
        struct Body: Encodable { var botId, uploadId, name, data: String; var offset: Int; var done: Bool }
        var offset = 0
        repeat {
            let end = min(offset + Self.uploadChunk, data.count)
            let chunk = data.subdata(in: offset..<end).base64EncodedString()
            let _: Empty = try await call("upload", Body(botId: botId, uploadId: id, name: name, data: chunk, offset: offset, done: end == data.count), timeout: 60)
            offset = end
        } while offset < data.count
    }

    /// A sent file, fetched back in chunks.
    func readUpload(botId: String, id: String) async throws -> Data {
        struct Body: Encodable { var botId, uploadId: String; var offset: Int }
        struct Res: Decodable { var data: String; var size: Int }
        var out = Data()
        repeat {
            let res: Res = try await call("readUpload", Body(botId: botId, uploadId: id, offset: out.count), timeout: 60)
            guard let chunk = Data(base64Encoded: res.data), !chunk.isEmpty else { break }
            out.append(chunk)
            if out.count >= res.size { break }
        } while true
        return out
    }

    /// The user makes this bot the lead, in place of the one before.
    func setLead(_ botId: String) async throws {
        let _: Empty = try await self.call("setLead", ["botId": botId])
    }

    /// A call's audio is live: a lead opens it, and its opening is the call's.
    func callStarted(_ botId: String, call: String) async throws {
        let _: Empty = try await self.call("callStarted", ["botId": botId, "callId": call])
    }

    // MARK: voice calls (host/src/chat/calls)

    /// The call is on (again, for a provider session that was replaced): the voice's instructions and tools, and a
    /// realtime provider's credential. `mode`: `realtime`, `speech` or `device`.
    func startCall(botId: String, call: String, mode: String, provider: VoiceProvider? = nil, model: String? = nil,
                   voice: String? = nil, language: String?) async throws -> CallSession {
        struct Body: Encodable {
            var botId, callId, mode: String; var provider, model, voice, language: String?
        }
        let body = Body(botId: botId, callId: call, mode: mode, provider: provider?.rawValue, model: model, voice: voice,
                        language: language)
        let data = try await transport.call("startCall", body: try Self.encoder.encode(body), timeout: 30)
        return try CallSession(json: data)
    }

    /// Runs one of the voice's tool calls on the computer, with what was said that it hasn't got yet (`lines`);
    /// `arguments` and the answer are JSON.
    func callTool(call: String, name: String, arguments: Data, lines: [CallLine]) async throws -> Data {
        let args = (try? JSONSerialization.jsonObject(with: arguments)) ?? [String: Any]()
        let said = try JSONSerialization.jsonObject(with: Self.encoder.encode(lines))
        let body = try JSONSerialization.data(withJSONObject: ["callId": call, "name": name, "arguments": args, "lines": said])
        let data = try await transport.call("callTool", body: body, timeout: 60)
        let result = ((try? JSONSerialization.jsonObject(with: data)) as? [String: Any])?["result"] ?? [String: Any]()
        return try JSONSerialization.data(withJSONObject: result)
    }

    /// What was just said on the call, kept on the computer.
    func callLines(call: String, lines: [CallLine]) async throws {
        struct Body: Encodable { var callId: String; var lines: [CallLine] }
        let _: Empty = try await self.call("callLines", Body(callId: call, lines: lines))
    }

    /// The call is over: its line in the chat, with the rest of the transcript (`lines`), which the computer titles.
    /// Safe to repeat: the computer ends a call once.
    func endCall(botId: String, call: String, seconds: Int, lines: [CallLine]) async throws -> Entry? {
        struct Body: Encodable { var botId, callId: String; var seconds: Int; var lines: [CallLine] }
        struct Res: Decodable { var entry: Entry? }
        let res: Res = try await self.call("endCall", Body(botId: botId, callId: call, seconds: seconds, lines: lines))
        return res.entry
    }

    func stop(_ botId: String) async throws {
        let _: Empty = try await call("stop", ["botId": botId])
    }

    /// A queued message, now: into the running turn when the agent can take it, else as the next one (host 2.39.0).
    func steer(botId: String, entryId: String) async throws {
        let _: Empty = try await call("steer", ["botId": botId, "entryId": entryId])
    }

    /// A queued message taken back: it never goes out (host 2.39.0).
    func unqueue(botId: String, entryId: String) async throws {
        let _: Empty = try await call("unqueue", ["botId": botId, "entryId": entryId])
    }

    func devServer(_ action: DevServer.Action, botId: String, id: String) async throws {
        let _: Empty = try await call(action.rawValue, ["botId": botId, "id": id])
    }

    /// The server's recent output.
    func devServerLogs(botId: String, id: String) async throws -> String {
        struct Res: Decodable { var text: String }
        let res: Res = try await call("devServerLogs", ["botId": botId, "id": id])
        return res.text
    }

    func respondPermission(entryId: String, optionId: String?) async throws {
        struct Body: Encodable { var entryId: String; var optionId: String? }
        let _: Empty = try await call("respondPermission", Body(entryId: entryId, optionId: optionId))
    }

    /// Push tickets are bound to this device's key; `pushKey` lets the host seal notification text (§6.7).
    func registerDevice(ticket: String, relay: String, name: String, pushKey: String?, ctx: String) async throws {
        struct Body: Encodable { var ticket: String; var relay: String; var name: String; var pushKey: String?; var ctx: String }
        let _: Empty = try await call("registerDevice", Body(ticket: ticket, relay: relay, name: name, pushKey: pushKey, ctx: ctx))
    }

    /// Stops this device's alerts: notifications switched off in the app, or the phone signed out.
    func unregisterDevice() async throws {
        let _: Empty = try await call("unregisterDevice")
    }

    /// Removes this device from the computer (deleting the account, starting over): its access and alerts go.
    /// A computer older than `forgetDevice` only stops the alerts; the key is erased right after either way.
    func forgetDevice() async throws {
        do {
            let _: Empty = try await call("forgetDevice")
        } catch {
            let _: Empty = try await call("unregisterDevice")
        }
    }

    func registerActivity(botId: String, ticket: String) async throws {
        let _: Empty = try await call("registerActivity", ["botId": botId, "ticket": ticket])
    }

    func selectWorkspace(_ path: String) async throws -> String {
        struct Reply: Decodable { var path: String }
        let reply: Reply = try await call("selectWorkspace", ["path": path])
        return reply.path
    }

    func listDirs(_ path: String?) async throws -> DirListing {
        struct Body: Encodable { var path: String? }
        return try await call("listDirs", Body(path: path))
    }
}

// MARK: - Agent setup

public extension HostClient {
    func refreshBackends() async throws -> [Backend] {
        struct Res: Decodable { var backends: [Backend] }
        let res: Res = try await call("refreshBackends", timeout: 60)
        return res.backends
    }

    /// Starts (or rejoins) installing or signing in to `backend` in a terminal on the computer.
    /// `method`: a terminal sign-in method from `agentAuth`; nil runs Codync's own command.
    func agentSetup(backend: String, step: SetupStep, method: String?, cols: Int, rows: Int) async throws -> String {
        struct Body: Encodable { var backend: String; var step: SetupStep; var method: String?; var cols: Int; var rows: Int }
        struct Res: Decodable { var term: String }
        // The first sign-in through a registry build can download it.
        let res: Res = try await call("agentSetup", Body(backend: backend, step: step, method: method, cols: cols, rows: rows), timeout: 300)
        return res.term
    }

    /// Starts the agent to see whether it's signed in and how it can be (first run may download it).
    func agentModels(_ backend: String) async throws -> AgentModels {
        try await call("agentModels", ["backend": backend], timeout: 300)
    }

    func agentAuth(_ backend: String) async throws -> AgentAuth {
        try await call("agentAuth", ["backend": backend], timeout: 300)
    }

    /// Lets the agent sign itself in; returns once it's done (or gave up).
    func agentAuthenticate(_ backend: String, method: String) async throws -> AgentAuth {
        try await call("agentAuthenticate", ["backend": backend, "method": method], timeout: 660)
    }

    /// Saves keys for the agent on the computer (empty values remove them).
    func setAgentEnv(_ backend: String, vars: [String: String]) async throws -> AgentAuth {
        struct Body: Encodable { var backend: String; var vars: [String: String] }
        return try await call("setAgentEnv", Body(backend: backend, vars: vars), timeout: 300)
    }

    func termInput(_ term: String, _ bytes: Data) async throws {
        let _: Empty = try await call("termInput", ["term": term, "data": bytes.base64EncodedString()])
    }

    func termResize(_ term: String, cols: Int, rows: Int) async throws {
        struct Body: Encodable { var term: String; var cols: Int; var rows: Int }
        let _: Empty = try await call("termResize", Body(term: term, cols: cols, rows: rows))
    }

    func termClose(_ term: String) async throws {
        let _: Empty = try await call("termClose", ["term": term])
    }
}