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.

12.3 KB
Raw Blame
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.

import CuaSDK
import CuaSpacesFFI
import Foundation
import Observation

/// The user's own clouds (AWS, Google Cloud, Hetzner, Modal): what `cloud_status`
/// says, the "Your cloud" tile's connected clouds, and the "Connect a
/// cloud" sheet. The sheet's rows, words and requests are the app core's
/// (`appCloudConnect*`, the Tauri app draws the same); this runs the
/// daemon's `cloud_*` tools it asks for. Credentials never pass through
/// here: each cloud uses its own CLI sign-in. The one exception is the
/// Hetzner API token: it lives only in `token` below (never in `state`,
/// never persisted or logged), goes out on the `cloud_test` /
/// `cloud_connect` call the core asks it to, and is cleared when Connect
/// finishes or the sheet closes.
/// Runs the daemon's `cloud_*` tools (the live backend; fixtures answer
/// with synthetic clouds).
public protocol CloudToolRunning: AnyObject, Sendable {
    func cloudTool(_ tool: String, _ args: [String: Any]) async throws -> Any
}

/// A tool's JSON answer, handed across `withTimeout`.
private struct CloudStatusAnswer: @unchecked Sendable { let value: Any }

extension LiveSpacesBackend: CloudToolRunning {
    public func cloudTool(_ tool: String, _ args: [String: Any]) async throws -> Any {
        try await agentsTool(tool, args)
    }
}

/// Synthetic clouds: AWS found and, once connected, the default.
extension FixtureSpacesBackend: CloudToolRunning {
    public func cloudTool(_ tool: String, _ args: [String: Any]) async throws -> Any {
        try await MainActor.run {
            fixtureCloudCalls.append(tool)
            switch tool {
            case "cloud_status":
                var aws = Self.fixtureAws(connected: fixtureCloudConnected)
                if fixtureCloudWaiting {
                    aws.merge(["auth": "oidc", "status": "waiting-for-approval", "approval": "connection",
                               "approval_agent": "eval-runner", "account": "210987654321",
                               "budget_usd_month": 200.0, "can_approve": true]) { _, new in new }
                }
                return ["default_on": fixtureCloudConnected ? "aws" : "local", "providers": [aws]]
            case "cloud_test":
                return ["provider": "aws", "ok": true, "account": "1",
                        "checks": [["name": "credentials", "ok": true, "detail": "account 1"]]]
            case "cloud_connect":
                fixtureCloudConnected = true
                var row = Self.fixtureAws(connected: true)
                row["checks"] = [["name": "credentials", "ok": true, "detail": "account 1"]]
                return row
            case "cloud_approve":
                fixtureCloudWaiting = false
                if args["deny"] as? Bool == true { fixtureCloudConnected = false }
                return Self.fixtureAws(connected: fixtureCloudConnected)
            case "cloud_disconnect":
                fixtureCloudConnected = false
                return ["provider": args["provider"] as? String ?? "aws", "disconnected": true]
            case "cloud_hosts":
                return fixtureElastic ? Self.fixtureElasticHosts : []
            case "cloud_budget":
                return ["policy": ["autoscale": true, "max_usd_per_hour": 2.0, "monthly_usd": 300.0,
                                   "max_new_hosts": 8, "warm": true, "interactive_slo_secs": 30, "routed": true],
                        "month_usd": fixtureElastic ? 12.5 : 0.0,
                        "running_usd_per_hour": fixtureElastic ? 0.1368 : 0.0, "hosts": fixtureElastic ? 2 : 0]
            default:
                throw FixtureError(message: "unknown tool \(tool)")
            }
        }
    }

    /// Rows as `cloud_hosts` answers (`CloudHost`).
    static let fixtureElasticHosts: [[String: Any]] = [
        ["name": "hetzner-1", "provider": "hetzner", "type_name": "cax41", "region": "fsn1", "id": "42",
         "machine": "m-hetzner-1", "state": "joined", "started": 1_700_000_000, "expires": 1_700_086_400,
         "usd_per_hour": 0.0684, "billing_step_secs": 3600, "billing_min_secs": 3600, "pinned": false],
        ["name": "hetzner-2", "provider": "hetzner", "type_name": "cax41", "region": "fsn1", "id": "43",
         "machine": "", "state": "booting", "started": 1_700_000_100, "expires": 1_700_086_500,
         "usd_per_hour": 0.0684, "billing_step_secs": 3600, "billing_min_secs": 3600, "pinned": false],
    ]

    /// A ledger as the core writes it (`LedgerLine`, one JSON per line), with
    /// the last event a few minutes ago.
    nonisolated static func fixtureLedger(now: Int = Int(Date().timeIntervalSince1970)) -> String {
        [(now - 5400, "add", "hetzner-1"), (now - 5300, "busy", "hetzner-1"),
         (now - 1800, "idle", "hetzner-1"), (now - 240, "add", "hetzner-2")]
            .map { at, event, host in
                #"{"at":\#(at),"event":"\#(event)","host":"\#(host)","provider":"hetzner","type_name":"cax41","region":"fsn1","usd_per_hour":0.0684,"billing_step_secs":3600,"billing_min_secs":3600,"reason":""}"#
            }.joined(separator: "\n")
    }

    static func fixtureAws(connected: Bool) -> [String: Any] {
        ["name": "aws", "title": "AWS", "tier": "vm", "connected": connected,
         "credentials": ["found": true, "source": "~/.aws profile default"],
         "region": "us-west-2", "label": "AWS \u{00B7} us-west-2", "ttl_hours": 8,
         "kinds": [["image": "linux", "kind": "container", "supported": true,
                    "machine_type": "t4g.medium", "usd_per_hour": 0.0368],
                   ["image": "windows", "kind": "vm", "supported": false,
                    "reason": "Windows on AWS is not offered yet."]]]
    }
}

@MainActor @Observable
public final class CloudModel {
    private let tools: CloudToolRunning?
    /// `cloud_status` as it came (nil: not read, or no answer).
    var status: Any?
    public private(set) var state = appCloudConnectInitial()
    /// The sheet shows. Closing it drops the typed token.
    public var showing = false {
        didSet { if !showing { token = "" } }
    }
    /// The Hetzner API token as typed. Memory only: the core hears just
    /// whether it is empty (`token_entered`), never its text.
    private(set) var token = ""
    /// Connected: the wizard reads the clouds again.
    public var onConnected: () -> Void = {}

    public init(tools: CloudToolRunning?) {
        self.tools = tools
    }

    private var statusJson: String {
        guard let status else { return "{}" }
        return (try? JSONSerialization.data(withJSONObject: status, options: [.fragmentsAllowed]))
            .map { String(decoding: $0, as: UTF8.self) } ?? "{}"
    }

    public var input: AppCloudConnectInput {
        (try? appCloudConnectInputFromStatusJson(json: statusJson)) ?? AppCloudConnectInput(providers: [])
    }

    /// The clouds the Computers page draws (`cloud_page`); nil until `cloud_status` has answered.
    public var cloudsInput: AppCloudsInput? {
        guard status != nil else { return nil }
        return try? appCloudsInputFromStatus(json: statusJson, now: UInt64(Date().timeIntervalSince1970), canApprove: false)
    }

    /// Approves (or, with `approve` false, denies) what an agent set up in
    /// `provider`: the daemon's person-only `cloud_approve`. Each cloud in
    /// `cloud_status` says whether this person may (`can_approve`).
    public func approve(_ provider: String, approve: Bool) async throws {
        guard let tools else { throw CuaError.InvalidArgument(message: "Clouds need the cua daemon") }
        _ = try await tools.cloudTool("cloud_approve", ["provider": provider, "deny": !approve])
        await refresh()
    }

    /// Forgets a cloud; with `deleteResources`, deletes what Cua created there first.
    public func disconnect(_ provider: String, deleteResources: Bool) async throws {
        guard let tools else { throw CuaError.InvalidArgument(message: "Clouds need the cua daemon") }
        _ = try await tools.cloudTool("cloud_disconnect", ["provider": provider, "delete": deleteResources])
        await refresh()
    }

    /// The connected clouds, for the New Space wizard.
    public var clouds: [AppConnectedCloud] {
        (try? appConnectedCloudsFromStatusJson(json: statusJson)) ?? []
    }

    /// The default location's word (`default.on`), when the status says.
    public var defaultOn: String? {
        (status as? [String: Any])?["default_on"] as? String
    }

    public var view: AppCloudConnectView { appCloudConnectView(input: input, state: state) }

    /// Reads `cloud_status` again (a missing daemon or tool leaves none).
    /// Bounded, as New Space waits for it: a daemon that does not answer in
    /// time leaves what was read before.
    public func refresh() async {
        guard let tools else { return }
        switch await withTimeout(seconds: Self.refreshSeconds, { CloudStatusAnswer(value: try await tools.cloudTool("cloud_status", [:])) }) {
        case .success(let answer): status = answer.value
        case .failure(let error): if !(error is TimeoutError) { status = nil }
        }
    }

    /// How long `refresh` waits for `cloud_status`.
    static let refreshSeconds: Double = 10

    /// The token field changed. The core is told only when it goes between
    /// empty and not empty.
    public func setToken(_ text: String) {
        let was = !token.isEmpty
        token = text
        guard was != !text.isEmpty else { return }
        state = appCloudConnectReduce(input: input, state: state, action: .setTokenEntered(entered: !text.isEmpty))
    }

    /// Opens the sheet on a fresh state.
    public func open() {
        token = ""
        state = appCloudConnectInitial()
        showing = true
        Task { await refresh() }
    }

    /// Applies `action`; Test and Connect run the request the core returns.
    /// "No cloud" (and any other no-request Connect) finishes the flow on
    /// the spot, with no `cloud_test` / `cloud_connect` call at all.
    public func send(_ action: AppCloudConnectAction) async {
        let before = input
        state = appCloudConnectReduce(input: before, state: state, action: action)
        switch action {
        case .test, .connect: break
        default: return
        }
        if view.done {
            showing = false
            return
        }
        guard let request = view.request else { return }
        guard let tools else {
            state = appCloudConnectReduce(input: before, state: state, action: .failed(error: "No cua daemon"))
            return
        }
        do {
            switch request {
            case let .test(target):
                let r = try await tools.cloudTool("cloud_test", Self.args(target, token: token)) as? [String: Any] ?? [:]
                let checks = (r["checks"] as? [[String: Any]] ?? []).map {
                    AppCloudCheckInput(name: $0["name"] as? String ?? "", ok: $0["ok"] as? Bool ?? false,
                                       detail: $0["detail"] as? String ?? "")
                }
                state = appCloudConnectReduce(input: before, state: state, action: .tested(
                    ok: r["ok"] as? Bool ?? false, account: r["account"] as? String ?? "", checks: checks))
            case let .connect(target, makeDefault):
                var args = Self.args(target, token: token)
                args["make_default"] = makeDefault
                let r = try await tools.cloudTool("cloud_connect", args) as? [String: Any] ?? [:]
                token = ""
                state = appCloudConnectReduce(input: before, state: state, action: .connected(
                    label: r["label"] as? String ?? target.provider))
                await refresh()
                showing = false
                onConnected()
            }
        } catch {
            if case .connect = request { token = "" }
            state = appCloudConnectReduce(input: before, state: state,
                                          action: .failed(error: LiveSpacesBackend.words(error)))
        }
    }

    static func args(_ t: AppCloudTargetArgs, token: String = "") -> [String: Any] {
        var a: [String: Any] = ["provider": t.provider]
        if let v = t.profile { a["profile"] = v }
        if let v = t.region { a["region"] = v }
        if let v = t.project { a["project"] = v }
        if let v = t.environment { a["environment"] = v }
        if t.usesToken, !token.isEmpty { a["token"] = token }
        return a
    }
}