SPB Git

Repository Public License

AnthropicClient.swift 21.4 KB 435 lines swift

1import Foundation2import PrismCore3import PrismSecurity45/// Errors a caller can act on. Each maps to a specific state in the UI (hard rule 1: say what really happened).6public enum ClaudeError: Error, LocalizedError, Sendable, Equatable {7    case missingKey8    case invalidKey9    case forbidden(String)10    case notFound(String)11    case badRequest(String)12    case rateLimited(retryAfter: Double?)13    case overloaded14    case server(status: Int, message: String)15    case offline16    case network(String)17    case cancelled18    case malformedResponse(String)1920    public var errorDescription: String? {21        switch self {22        case .missingKey: "No Anthropic API key is stored. Add one in Settings."23        case .invalidKey: "Anthropic rejected the API key. Check it in Settings."24        case .forbidden(let m): "Anthropic refused the request: \(m)"25        case .notFound(let m): "Not found: \(m)"26        case .badRequest(let m): "Anthropic rejected the request: \(m)"27        case .rateLimited(let after): "The rate limit was reached." + (after.map { " Try again in \(Int($0.rounded(.up))) s." } ?? "")28        case .overloaded: "Anthropic's API is overloaded right now. Try again shortly."29        case .server(let status, let m): "Anthropic's API had a problem (HTTP \(status)). \(m)"30        case .offline: "This Mac is offline. Claude features are unavailable; your apps keep working."31        case .network(let m): "The connection to Anthropic failed: \(m)"32        case .cancelled: "Cancelled."33        case .malformedResponse(let m): "Unexpected response from Anthropic: \(m)"34        }35    }3637    var isRetryable: Bool {38        switch self {39        case .rateLimited, .overloaded, .server, .network: true40        default: false41        }42    }43}4445public struct HTTPResponseHead: Sendable {46    public var status: Int47    public var headers: [String: String]48    public init(status: Int, headers: [String: String] = [:]) {49        self.status = status50        self.headers = Dictionary(headers.map { ($0.key.lowercased(), $0.value) }, uniquingKeysWith: { a, _ in a })51    }52    public func header(_ name: String) -> String? { headers[name.lowercased()] }53}5455/// The network seam. Production uses URLSession; tests replay recorded fixtures.56public protocol HTTPTransport: Sendable {57    /// Returns the response head and the body as a stream of text lines (SSE events arrive line by line).58    func send(_ request: URLRequest) async throws -> (HTTPResponseHead, AsyncThrowingStream<String, Error>)59}6061public struct URLSessionTransport: HTTPTransport {62    let session: URLSession6364    public init(timeout: TimeInterval = 600) {65        let config = URLSessionConfiguration.ephemeral66        config.timeoutIntervalForRequest = 12067        config.timeoutIntervalForResource = timeout68        config.httpCookieStorage = nil69        config.urlCache = nil70        session = URLSession(configuration: config)71    }7273    public func send(_ request: URLRequest) async throws -> (HTTPResponseHead, AsyncThrowingStream<String, Error>) {74        let (bytes, response) = try await session.bytes(for: request)75        guard let http = response as? HTTPURLResponse else { throw ClaudeError.malformedResponse("not an HTTP response") }76        var headers: [String: String] = [:]77        for (k, v) in http.allHeaderFields { headers[String(describing: k)] = String(describing: v) }78        let stream = AsyncThrowingStream<String, Error> { continuation in79            let task = Task {80                do {81                    for try await line in bytes.lines { continuation.yield(line) }82                    continuation.finish()83                } catch { continuation.finish(throwing: error) }84            }85            continuation.onTermination = { _ in task.cancel() }86        }87        return (HTTPResponseHead(status: http.statusCode, headers: headers), stream)88    }89}9091public struct ModelInfo: Sendable, Hashable, Identifiable {92    public var id: String93    public var displayName: String94    public var maxInputTokens: Int?95    public var maxOutputTokens: Int?96    public var createdAt: String?97}9899public struct TokenUsage: Sendable, Hashable {100    public var inputTokens = 0101    public var outputTokens = 0102    public var cacheReadTokens = 0103    public var cacheWriteTokens = 0104    public init() {}105106    public static func + (a: TokenUsage, b: TokenUsage) -> TokenUsage {107        var r = TokenUsage()108        r.inputTokens = a.inputTokens + b.inputTokens109        r.outputTokens = a.outputTokens + b.outputTokens110        r.cacheReadTokens = a.cacheReadTokens + b.cacheReadTokens111        r.cacheWriteTokens = a.cacheWriteTokens + b.cacheWriteTokens112        return r113    }114115    public var totalTokens: Int { inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens }116}117118/// One complete assistant turn, reassembled from the stream. Content blocks are kept exactly as received119/// so they can be sent back unchanged (thinking blocks are only valid unmodified).120public struct AssistantTurn: Sendable, Equatable {121    public var id: String122    public var model: String123    public var content: [JSONValue]124    public var stopReason: String125    public var stopDetails: JSONValue?126    public var usage: TokenUsage127    public var requestID: String?128129    public var text: String { content.filter { $0["type"] == "text" }.compactMap { $0["text"]?.stringValue }.joined() }130    public var toolUses: [(id: String, name: String, input: JSONValue, inputError: String?)] {131        content.filter { $0["type"] == "tool_use" }.map {132            ($0["id"]?.stringValue ?? "", $0["name"]?.stringValue ?? "", $0["input"] ?? .emptyObject, $0["_prism_input_error"]?.stringValue)133        }134    }135136    /// Content as it must be echoed in the next request (without PRISM's private annotations).137    public var echoContent: [JSONValue] {138        content.map { block in139            guard var o = block.objectValue, o["_prism_input_error"] != nil else { return block }140            o["_prism_input_error"] = nil141            return .object(o)142        }143    }144}145146public enum StreamEvent: Sendable, Equatable {147    case textDelta(String)148    case toolUseStarted(id: String, name: String)149    case usage(TokenUsage)150    /// The stream broke and the turn is being requested again; partial output shown so far is void.151    case restarted152}153154public struct ClaudeConfiguration: Sendable {155    public var baseURL = URL(string: "https://api.anthropic.com")!156    public var apiVersion = "2026-10-21"157    public var maxRetries = 3158    /// Base delay for exponential backoff; tests set it to zero.159    public var retryBaseDelay: Double = 1.0160    public init() {}161}162163/// A thin, dedicated client for the Anthropic Messages and Models APIs (no official Swift SDK exists;164/// shapes follow the current raw-HTTP documentation).165public struct AnthropicClient: Sendable {166    public let transport: HTTPTransport167    public let secrets: SecretStore168    public var configuration: ClaudeConfiguration169    /// Receives one line per request for the Monitor: method, path, status, request id, attempt. Never the key.170    public var log: @Sendable (String) -> Void171172    public init(transport: HTTPTransport = URLSessionTransport(), secrets: SecretStore, configuration: ClaudeConfiguration = ClaudeConfiguration(), log: @escaping @Sendable (String) -> Void = { _ in }) {173        self.transport = transport; self.secrets = secrets; self.configuration = configuration; self.log = log174    }175176    private func request(_ method: String, _ path: String, body: JSONValue? = nil, betas: [String] = [], key overrideKey: String? = nil) throws -> URLRequest {177        let stored = try? secrets.secret(for: SecretAccount.anthropicAPIKey)178        guard let key = overrideKey ?? stored ?? nil, !key.isEmpty else { throw ClaudeError.missingKey }179        var r = URLRequest(url: configuration.baseURL.appendingPathComponent(path))180        r.httpMethod = method181        r.setValue(key, forHTTPHeaderField: "x-api-key")182        r.setValue(configuration.apiVersion, forHTTPHeaderField: "anthropic-version")183        if !betas.isEmpty { r.setValue(betas.joined(separator: ","), forHTTPHeaderField: "anthropic-beta") }184        if let body {185            r.setValue("application/json", forHTTPHeaderField: "Content-Type")186            r.httpBody = body.canonicalData()187        }188        return r189    }190191    static func error(status: Int, head: HTTPResponseHead, body: String) -> ClaudeError {192        let parsed = try? JSONValue.parse(body)193        let message = Redactor.redact(parsed?["error"]?["message"]?.stringValue ?? String(body.prefix(300)))194        switch status {195        case 401: return .invalidKey196        case 403: return .forbidden(message)197        case 404: return .notFound(message)198        case 400, 413, 422: return .badRequest(message)199        case 429: return .rateLimited(retryAfter: head.header("retry-after").flatMap(Double.init))200        case 529: return .overloaded201        default: return .server(status: status, message: message)202        }203    }204205    public static func map(_ error: Error) -> ClaudeError {206        if let e = error as? ClaudeError { return e }207        if error is CancellationError { return .cancelled }208        if let u = error as? URLError {209            switch u.code {210            case .cancelled: return .cancelled211            case .notConnectedToInternet, .dataNotAllowed, .internationalRoamingOff: return .offline212            // A connection that drops mid-request is transient (Wi-Fi roaming, sleep): worth retrying, unlike being offline.213            case .networkConnectionLost: return .network("The connection was lost.")214            default: return .network(u.localizedDescription)215            }216        }217        return .network(error.localizedDescription)218    }219220    /// Sends with retry and backoff for rate limits, overload, 5xx and transient network failures.221    private func perform(_ request: URLRequest, label: String) async throws -> (HTTPResponseHead, AsyncThrowingStream<String, Error>) {222        var attempt = 0223        while true {224            try Task.checkCancellation()225            attempt += 1226            let failure: ClaudeError227            var mayRetry = true228            do {229                let (head, lines) = try await transport.send(request)230                let id = head.header("request-id") ?? "-"231                log("\(request.httpMethod ?? "GET") \(label) → \(head.status) request-id=\(id) attempt=\(attempt)")232                if (200..<300).contains(head.status) { return (head, lines) }233                var body = ""234                for try await line in lines { body += line + "\n"; if body.count > 20_000 { break } }235                failure = Self.error(status: head.status, head: head, body: body)236                if head.header("x-should-retry") == "false" { mayRetry = false }237            } catch {238                let mapped = Self.map(error)239                if case .cancelled = mapped { throw mapped }240                if (error as? ClaudeError) != nil, !mapped.isRetryable { throw mapped }241                if !(error is ClaudeError) { log("\(request.httpMethod ?? "GET") \(label) failed: \(mapped.localizedDescription) attempt=\(attempt)") }242                guard mapped.isRetryable, attempt <= configuration.maxRetries else { throw mapped }243                try await backoff(attempt, mapped)244                continue245            }246            guard mayRetry, failure.isRetryable, attempt <= configuration.maxRetries else { throw failure }247            try await backoff(attempt, failure)248        }249    }250251    private func backoff(_ attempt: Int, _ error: ClaudeError) async throws {252        var delay = configuration.retryBaseDelay * pow(2, Double(attempt - 1))253        if case .rateLimited(let after) = error, let after { delay = max(delay, min(after, 60)) }254        delay = min(delay, 60)255        if delay > 0 {256            do { try await Task.sleep(for: .seconds(delay * Double.random(in: 0.8...1.2))) } catch { throw ClaudeError.cancelled }257        }258    }259260    // MARK: Models261262    /// The models this account can actually use, newest first (hard rule 8: discovered at runtime).263    public func listModels(key: String? = nil) async throws -> [ModelInfo] {264        var out: [ModelInfo] = []265        var after: String?266        for _ in 0..<10 {267            var components = URLComponents()268            components.queryItems = [URLQueryItem(name: "limit", value: "100")] + (after.map { [URLQueryItem(name: "after_id", value: $0)] } ?? [])269            var r = try request("GET", "v1/models", key: key)270            r.url = URL(string: r.url!.absoluteString + "?" + (components.percentEncodedQuery ?? ""))271            let (_, lines) = try await perform(r, label: "/v1/models")272            var body = ""273            do { for try await line in lines { body += line } } catch { throw Self.map(error) }274            guard let json = try? JSONValue.parse(body), let data = json["data"]?.arrayValue else { throw ClaudeError.malformedResponse("model list") }275            for m in data {276                guard let id = m["id"]?.stringValue else { continue }277                out.append(ModelInfo(id: id, displayName: m["display_name"]?.stringValue ?? id, maxInputTokens: m["max_input_tokens"]?.intValue,278                                     maxOutputTokens: m["max_tokens"]?.intValue, createdAt: m["created_at"]?.stringValue))279            }280            guard json["has_more"]?.boolValue == true, let last = json["last_id"]?.stringValue else { break }281            after = last282        }283        return out284    }285286    // MARK: Messages (streaming)287288    /// Streams one assistant turn. `onEvent` is called as text and tool calls arrive; the reassembled turn is returned.289    /// A stream that breaks part-way (connection lost, overload event, truncated body) is requested again from the start,290    /// up to `maxRetries` times: no tool has run yet for that turn, so repeating it is safe. `onEvent(.restarted)` tells the291    /// UI to discard the partial text it showed.292    public func streamMessage(_ body: JSONValue, betas: [String] = [], onEvent: @Sendable (StreamEvent) -> Void = { _ in }) async throws -> AssistantTurn {293        var payload = body.objectValue ?? [:]294        payload["stream"] = true295        let r = try request("POST", "v1/messages", body: .object(payload), betas: betas)296        var attempt = 0297        while true {298            attempt += 1299            let (head, lines) = try await perform(r, label: "/v1/messages")300            var parser = SSEAssembler(requestID: head.header("request-id"))301            do {302                for try await line in lines {303                    try Task.checkCancellation()304                    for event in try parser.consume(line: line) { onEvent(event) }305                }306                if Task.isCancelled { throw ClaudeError.cancelled }307                return try parser.finish()308            } catch {309                let mapped = Self.map(error)310                let truncated: Bool = { if case .malformedResponse = mapped { return true } else { return false } }()311                guard mapped.isRetryable || truncated, attempt <= configuration.maxRetries, !Task.isCancelled else { throw mapped }312                log("POST /v1/messages stream interrupted (\(mapped.localizedDescription)); retrying, attempt=\(attempt + 1)")313                onEvent(.restarted)314                try await backoff(attempt, mapped)315            }316        }317    }318}319320/// Reassembles an assistant message from `data:` lines of the Messages SSE stream.321struct SSEAssembler {322    private var id = "", model = ""323    private var blocks: [Int: [String: JSONValue]] = [:]324    private var partialJSON: [Int: String] = [:]325    private var stopReason: String?326    private var stopDetails: JSONValue?327    private var usage = TokenUsage()328    private var sawStop = false329    let requestID: String?330331    init(requestID: String?) { self.requestID = requestID }332333    private mutating func apply(usage u: JSONValue?) {334        guard let u else { return }335        if let v = u["input_tokens"]?.intValue { usage.inputTokens = v }336        if let v = u["output_tokens"]?.intValue { usage.outputTokens = v }337        if let v = u["cache_read_input_tokens"]?.intValue { usage.cacheReadTokens = v }338        if let v = u["cache_creation_input_tokens"]?.intValue { usage.cacheWriteTokens = v }339    }340341    mutating func consume(line: String) throws -> [StreamEvent] {342        guard line.hasPrefix("data:") else { return [] }343        let payload = line.dropFirst(5).trimmingCharacters(in: .whitespaces)344        guard !payload.isEmpty, let event = try? JSONValue.parse(payload), let type = event["type"]?.stringValue else { return [] }345        switch type {346        case "message_start":347            id = event["message"]?["id"]?.stringValue ?? ""348            model = event["message"]?["model"]?.stringValue ?? ""349            apply(usage: event["message"]?["usage"])350            return [.usage(usage)]351        case "content_block_start":352            guard let index = event["index"]?.intValue, let block = event["content_block"]?.objectValue else { return [] }353            blocks[index] = block354            if block["type"] == "tool_use" {355                partialJSON[index] = ""356                return [.toolUseStarted(id: block["id"]?.stringValue ?? "", name: block["name"]?.stringValue ?? "")]357            }358        case "content_block_delta":359            guard let index = event["index"]?.intValue, let delta = event["delta"], blocks[index] != nil else { return [] }360            switch delta["type"]?.stringValue {361            case "text_delta":362                let t = delta["text"]?.stringValue ?? ""363                blocks[index]!["text"] = .string((blocks[index]!["text"]?.stringValue ?? "") + t)364                return [.textDelta(t)]365            case "input_json_delta": partialJSON[index, default: ""] += delta["partial_json"]?.stringValue ?? ""366            case "thinking_delta": blocks[index]!["thinking"] = .string((blocks[index]!["thinking"]?.stringValue ?? "") + (delta["thinking"]?.stringValue ?? ""))367            case "signature_delta": blocks[index]!["signature"] = delta["signature"] ?? .null368            case "citations_delta":369                if let c = delta["citation"] { blocks[index]!["citations"] = .array((blocks[index]!["citations"]?.arrayValue ?? []) + [c]) }370            default: break371            }372        case "content_block_stop":373            guard let index = event["index"]?.intValue, let raw = partialJSON.removeValue(forKey: index) else { return [] }374            // Tool inputs are parsed strictly; a broken input is kept for an error result instead of being run.375            if raw.trimmingCharacters(in: .whitespaces).isEmpty {376                blocks[index]!["input"] = .emptyObject377            } else if let parsed = try? JSONValue.parse(raw), parsed.objectValue != nil {378                blocks[index]!["input"] = parsed379            } else {380                blocks[index]!["input"] = .emptyObject381                blocks[index]!["_prism_input_error"] = .string(String(raw.prefix(2000)))382            }383        case "message_delta":384            if let r = event["delta"]?["stop_reason"]?.stringValue { stopReason = r }385            if let d = event["delta"]?["stop_details"], !d.isNull { stopDetails = d }386            apply(usage: event["usage"])387            return [.usage(usage)]388        case "message_stop": sawStop = true389        case "error":390            let kind = event["error"]?["type"]?.stringValue ?? ""391            let message = event["error"]?["message"]?.stringValue ?? "stream error"392            throw kind == "overloaded_error" ? ClaudeError.overloaded : ClaudeError.server(status: 200, message: message)393        default: break394        }395        return []396    }397398    func finish() throws -> AssistantTurn {399        guard sawStop, let stopReason else { throw ClaudeError.malformedResponse("the stream ended before the message was complete") }400        let content = blocks.keys.sorted().map { JSONValue.object(blocks[$0]!) }401        return AssistantTurn(id: id, model: model, content: content, stopReason: stopReason, stopDetails: stopDetails, usage: usage, requestID: requestID)402    }403}404405/// Estimated list prices in USD per million tokens. These are a snapshot (see `asOf`) used only for the406/// on-screen estimate; the invoice from Anthropic is the actual cost. Input/output rates come from the407/// published table; where a cache rate was not listed, the usual multipliers are assumed (read 0.1×, write 1.25× input).408public struct PriceTable: Sendable, Equatable {409    public struct Price: Sendable, Equatable {410        public var input: Double411        public var output: Double412        public var cacheRead: Double413        public var cacheWrite: Double414    }415416    public var asOf: String417    public var prices: [String: Price]418419    public static let snapshot = PriceTable(asOf: "2026-11-03", prices: [420        "claude-fable-5-2": Price(input: 8, output: 40, cacheRead: 0.20, cacheWrite: 10),421        "claude-opus-5-5": Price(input: 4, output: 20, cacheRead: 0.20, cacheWrite: 5),422        "claude-opus-5": Price(input: 5, output: 25, cacheRead: 0.50, cacheWrite: 6.25),423        "claude-sonnet-5-5": Price(input: 2, output: 10, cacheRead: 0.10, cacheWrite: 2.5),424        "claude-sonnet-5": Price(input: 2, output: 10, cacheRead: 0.20, cacheWrite: 2.5),425        "claude-haiku-5-5": Price(input: 0.10, output: 0.50, cacheRead: 0.01, cacheWrite: 0.125),426    ])427428    /// Nil when the model is not in the table: the UI then says "unknown" instead of inventing a number.429    public func estimate(model: String, usage: TokenUsage) -> Double? {430        guard let p = prices[model] ?? prices.first(where: { model.hasPrefix($0.key) })?.value else { return nil }431        return (Double(usage.inputTokens) * p.input + Double(usage.outputTokens) * p.output432            + Double(usage.cacheReadTokens) * p.cacheRead + Double(usage.cacheWriteTokens) * p.cacheWrite) / 1_000_000433    }434}435
Files main
Menu

Theme