Skip to content

armgit / chums

Public Imported from GitHub
0

Talk to Claude Code and Codex agents from an Apple Watch and an iPhone. Each agent is a character on the watch.

6.2 KB
Raw Blame
import Foundation

// The hub, as the widgets, the Control and Siri reach it: one request at a time, from the extension or the app, with
// the same address and token as the watch (HubConfig, generated by tools/gen-config.sh).

struct WAgent: Codable, Identifiable, Hashable {
    let id: String
    let name: String
    let character: String
    let status: String
    let line: String?
    let needs: Bool
}

struct WApproval: Codable, Hashable {
    let requestId: String
    let session: String
    let tool: String
    let description: String
    let summary: String?
}

struct WLine: Codable, Hashable {
    let id: String
    let text: String
    let kind: String
    let at: Double?
    let agent: String?
}

struct WState: Codable {
    let rev: Int
    let agents: [WAgent]
    let approvals: [WApproval]
    let spoken: [WLine]
    var focus: String? = nil                     // the agent you last talked to, or looked at on the iPhone

    /// The agent a widget with none picked shows: the one you last talked to (or looked at on the iPhone).
    var current: WAgent? { focus.flatMap { id in agents.first { $0.id == id } } ?? mostUrgent }
    /// Without one: one asking or stuck, else one at work, else the first.
    var mostUrgent: WAgent? {
        func rank(_ a: WAgent) -> Int {
            if a.needs { return 0 }
            switch a.status { case "blocked": return 1; case "waiting", "limited": return 2; case "working", "compacting": return 3
                              case "offline": return 5; default: return 4 }
        }
        return agents.enumerated().min { (rank($0.element), $0.offset) < (rank($1.element), $1.offset) }?.element
    }
    func approval(for agent: String) -> WApproval? { approvals.first { $0.session == agent } }

    /// Every agent in the app's order (SoulView.looks), the ones that need you first, then the ones at work.
    var byUrgency: [WAgent] {
        func rank(_ a: WAgent) -> Int { a.needs ? 0 : a.status == "blocked" ? 1 : a.status == "working" || a.status == "compacting" ? 2 : 3 }
        func place(_ a: WAgent) -> Int { WidgetHub.order.firstIndex(of: a.character) ?? WidgetHub.order.count }
        return agents.sorted { (rank($0), place($0)) < (rank($1), place($1)) }
    }
}

enum WidgetHub {
    /// The characters in the app's order (SoulView.looks, which the widgets can't see).
    static let order = ["noodle", "squint", "ray", "tangle", "peeps", "stretch", "crunch", "nana"]

    /// What a widget shows before the hub has answered once (the gallery, a placeholder).
    static let sample = WState(rev: 0, agents: [
        WAgent(id: "noodle", name: "Noodle", character: "noodle", status: "working", line: "Running the tests", needs: false),
        WAgent(id: "squint", name: "Squint", character: "squint", status: "waiting", line: "Send the invoice now?", needs: true),
        WAgent(id: "ray", name: "Ray", character: "ray", status: "idle", line: "Done. All ten tests pass.", needs: false),
    ], approvals: [], spoken: [])

    private static func request(_ host: String, _ path: String, method: String = "GET", body: Data? = nil, timeout: Double = 10) -> URLRequest? {
        guard let url = URL(string: host + path) else { return nil }
        var r = URLRequest(url: url, timeoutInterval: timeout)
        r.httpMethod = method
        r.setValue("Bearer \(HubConfig.token)", forHTTPHeaderField: "Authorization")
        if let body { r.httpBody = body; r.setValue("application/json", forHTTPHeaderField: "Content-Type") }
        return r
    }
    /// The hub's addresses: 127.0.0.1 is the Mac only in the Simulator; on an iPhone it's the iPhone itself, and the token
    /// would go there in the clear.
    private static let hosts: [String] = {
#if targetEnvironment(simulator)
        HubConfig.hosts
#else
        HubConfig.hosts.filter { !$0.contains("127.0.0.1") && !$0.contains("localhost") }
#endif
    }()
    /// The first address that answers (the internet one on a device, the Mac's own in the Simulator).
    private static func send(_ path: String, method: String = "GET", body: Data? = nil, timeout: Double = 10) async -> Data? {
        for host in hosts {
            guard let r = request(host, path, method: method, body: body, timeout: timeout),
                  let (data, resp) = try? await URLSession.shared.data(for: r),
                  (resp as? HTTPURLResponse)?.statusCode == 200 else { continue }
            return data
        }
        return nil
    }

    static func state() async -> WState? {
        guard let d = await send("/v1/state?since=0") else { return nil }
        return try? JSONDecoder().decode(WState.self, from: d)
    }
    static func verdict(_ requestId: String, allow: Bool) async -> Bool {
        let body = try? JSONSerialization.data(withJSONObject: ["requestId": requestId, "behavior": allow ? "allow" : "deny"])
        return await send("/v1/verdict", method: "POST", body: body) != nil
    }
    /// Words to an agent, as if said on the iPhone (its answer is spoken there).
    static func say(_ text: String, agent: String) async -> Bool {
        let body = try? JSONSerialization.data(withJSONObject: ["text": text, "agent": agent, "device": "phone"])
        return await send("/v1/say", method: "POST", body: body, timeout: 20) != nil
    }
    /// The agent's answer to something said at `after` (ms since 1970): its first line after that, waited for.
    static func reply(agent: String, after: Double, timeout: Double) async -> String? {
        let end = Date().addingTimeInterval(timeout)
        while Date() < end {
            if let s = await state(),
               let l = s.spoken.last(where: { $0.agent == agent && $0.kind != "echo" && ($0.at ?? 0) > after }) { return l.text }
            try? await Task.sleep(for: .seconds(1.5))
        }
        return nil
    }
}

/// Words for an agent's status, the same as the watch's.
func statusWords(_ a: WAgent) -> String {
    switch a.status {
    case "offline": return "Not running on your Mac"
    case "working": return a.line.map { "Working · \($0)" } ?? "Working"
    case "compacting": return "Tidying its memory"
    case "limited": return "Rate limited"
    case "blocked": return a.line.map { "Stuck: \($0)" } ?? "Stuck"
    default: return a.needs ? (a.line.map { "Needs you: \($0)" } ?? "Needs you") : (a.line ?? "Idle")
    }
}