SPB Git

Repository Public

AnthropicClient.swift 16.5 KB 359 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Shared/Sources/AIEngine/AnthropicClient.swift10// Description      : Direct HTTPS client for api.anthropic.com (Messages +11//                    Models): bounded sizes and timeouts, typed decoding,12//                    limited retries that honour Retry-After, no retry when the13//                    outcome is uncertain, and a redirect guard. The key is14//                    read from the secret store per request and never logged.15// Module           : AIEngine16// Repository       : https://git.spboucher.ai/sp-keyboard17// Created          : 2026-12-0118// Last Modified    : 2026-12-0119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation93import SecureStorage9495/// Outcome of a transport attempt that did not produce an HTTP response.96public enum TransportFailure: Error, Equatable, Sendable {97    /// Nothing reached the server (no network, DNS, connection refused): safe to retry.98    case notSent99    /// The request may have reached the server (timeout, connection lost): never retried automatically.100    case uncertain101    case timedOut102    case cancelled103    case blockedRedirect104}105106public protocol AITransport: Sendable {107    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)108}109110/// URLSession transport: ephemeral (no cache, no cookies, no credential storage), redirects refused unless111/// they stay on the allowed host over HTTPS.112public final class URLSessionAITransport: NSObject, AITransport, URLSessionTaskDelegate, @unchecked Sendable {113    public static let allowedHost = "api.anthropic.com"114    private let session: URLSession115    private let guardDelegate = RedirectGuard()116117    /// `protocolClasses` lets tests answer requests locally (URLProtocol) without touching the network.118    public init(requestTimeout: TimeInterval = 45, resourceTimeout: TimeInterval = 75, protocolClasses: [AnyClass]? = nil) {119        let configuration = URLSessionConfiguration.ephemeral120        if let protocolClasses { configuration.protocolClasses = protocolClasses }121        configuration.timeoutIntervalForRequest = requestTimeout122        configuration.timeoutIntervalForResource = resourceTimeout123        configuration.waitsForConnectivity = false124        configuration.httpCookieStorage = nil125        configuration.urlCache = nil126        configuration.urlCredentialStorage = nil127        configuration.httpShouldSetCookies = false128        configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData129        session = URLSession(configuration: configuration, delegate: guardDelegate, delegateQueue: nil)130        super.init()131    }132133    public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {134        do {135            let (data, response) = try await session.data(for: request)136            guard let http = response as? HTTPURLResponse else { throw TransportFailure.uncertain }137            if guardDelegate.consumeBlocked(for: request) { throw TransportFailure.blockedRedirect }138            return (data, http)139        } catch let failure as TransportFailure {140            throw failure141        } catch is CancellationError {142            throw TransportFailure.cancelled143        } catch let error as URLError {144            throw Self.classify(error)145        } catch {146            throw TransportFailure.uncertain147        }148    }149150    static func classify(_ error: URLError) -> TransportFailure {151        switch error.code {152        case .cancelled: .cancelled153        case .notConnectedToInternet, .cannotFindHost, .cannotConnectToHost, .dnsLookupFailed, .dataNotAllowed,154             .internationalRoamingOff, .secureConnectionFailed, .serverCertificateUntrusted, .appTransportSecurityRequiresSecureConnection:155            .notSent156        case .timedOut: .timedOut157        case .httpTooManyRedirects, .redirectToNonExistentLocation: .blockedRedirect158        default: .uncertain159        }160    }161162    public func invalidate() { session.invalidateAndCancel() }163164    private final class RedirectGuard: NSObject, URLSessionTaskDelegate, @unchecked Sendable {165        private let lock = NSLock()166        private var blocked = Set<URL>()167168        func consumeBlocked(for request: URLRequest) -> Bool {169            guard let url = request.url else { return false }170            return lock.withLock { blocked.remove(url) != nil }171        }172173        func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,174                        newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {175            let allowed = request.url?.scheme == "https" && request.url?.host == URLSessionAITransport.allowedHost176            if !allowed, let original = task.originalRequest?.url {177                lock.withLock { _ = blocked.insert(original) }178            }179            // Never follow: a redirect would resend the key header. Returning nil delivers the 3xx itself.180            completionHandler(nil)181        }182    }183}184185public struct AIRetryPolicy: Sendable, Equatable {186    public var maxRetries: Int187    public var baseDelay: Double188    /// A Retry-After longer than this is surfaced to the user instead of being waited out.189    public var maxWait: Double190191    public init(maxRetries: Int = 2, baseDelay: Double = 0.8, maxWait: Double = 12) {192        self.maxRetries = maxRetries193        self.baseDelay = baseDelay194        self.maxWait = maxWait195    }196197    public static let `default` = AIRetryPolicy()198    public static let none = AIRetryPolicy(maxRetries: 0)199}200201public struct AIRequest: Sendable, Hashable {202    public var model: AIModelInfo203    public var prompt: AIPrompt204    public var maxOutputTokens: Int205206    public init(model: AIModelInfo, prompt: AIPrompt, maxOutputTokens: Int) {207        self.model = model208        self.prompt = prompt209        self.maxOutputTokens = maxOutputTokens210    }211}212213public protocol AIService: Sendable {214    func complete(_ request: AIRequest) async throws -> AIResult215    func listModels() async throws -> [AIModelInfo]216}217218public struct AnthropicClient: AIService {219    /// API version sent in `anthropic-version` (documented value at build time, checked against the live API).220    public static let apiVersion = "2026-10-21"221    static let fallbackBeta = "server-side-fallback-2026-07-01"222    /// Models for which the server-side refusal fallback is documented.223    static let fallbackModels: Set<String> = ["claude-fable-5-2", "claude-fable-5-1", "claude-opus-5-5", "claude-opus-5", "claude-sonnet-5-5"]224    static let maxResponseBytes = 512 * 1024225226    public let baseURL: URL227    private let transport: AITransport228    private let secrets: SecretStoring229    private let retry: AIRetryPolicy230    private let sleep: @Sendable (Double) async throws -> Void231232    public init(transport: AITransport, secrets: SecretStoring, retry: AIRetryPolicy = .default,233                baseURL: URL = URL(string: "https://api.anthropic.com")!,234                sleep: @escaping @Sendable (Double) async throws -> Void = { try await Task.sleep(nanoseconds: UInt64($0 * 1_000_000_000)) }) {235        self.transport = transport236        self.secrets = secrets237        self.retry = retry238        self.baseURL = baseURL239        self.sleep = sleep240    }241242    // MARK: Requests243244    private func key() throws -> String {245        let stored: String?246        do { stored = try secrets.read(SecretName.anthropicAPIKey) } catch let error as SecretStoreError { throw AIError.keychain(error) }247        guard let stored, !APIKeyFormat.normalized(stored).isEmpty else { throw AIError.missingKey }248        return APIKeyFormat.normalized(stored)249    }250251    private func makeRequest(path: String, method: String, body: Data?, beta: String? = nil) throws -> URLRequest {252        guard baseURL.scheme == "https", let url = URL(string: path, relativeTo: baseURL) else { throw AIError.blockedRedirect }253        var request = URLRequest(url: url)254        request.httpMethod = method255        request.httpBody = body256        request.setValue(try key(), forHTTPHeaderField: "x-api-key")257        request.setValue(Self.apiVersion, forHTTPHeaderField: "anthropic-version")258        request.setValue("application/json", forHTTPHeaderField: "content-type")259        if let beta { request.setValue(beta, forHTTPHeaderField: "anthropic-beta") }260        request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData261        request.httpShouldHandleCookies = false262        return request263    }264265    public func listModels() async throws -> [AIModelInfo] {266        let request = try makeRequest(path: "/v1/models?limit=100", method: "GET", body: nil)267        let data = try await perform(request)268        guard let body = try? JSONDecoder().decode(ModelsResponseBody.self, from: data) else { throw AIError.malformedResponse }269        return body.data.map {270            AIModelInfo(id: $0.id, displayName: $0.display_name ?? $0.id, maxOutputTokens: $0.max_tokens,271                        supportsLowEffort: $0.capabilities?.effort?.low?.supported ?? false)272        }273    }274275    public func complete(_ request: AIRequest) async throws -> AIResult {276        guard !request.model.id.isEmpty else { throw AIError.noModelSelected }277        let useFallback = Self.fallbackModels.contains(request.model.id)278        let body = MessagesRequestBody(279            model: request.model.id,280            max_tokens: min(max(request.maxOutputTokens, 64), request.model.maxOutputTokens ?? AISettings.outputTokenRange.upperBound),281            system: request.prompt.system,282            messages: [.init(role: "user", content: request.prompt.user)],283            output_config: request.model.supportsLowEffort ? .init(effort: "low") : nil,284            fallbacks: useFallback ? "default" : nil)285        let encoded = try JSONEncoder().encode(body)286        let urlRequest = try makeRequest(path: "/v1/messages", method: "POST", body: encoded, beta: useFallback ? Self.fallbackBeta : nil)287        let data = try await perform(urlRequest)288        guard let response = try? JSONDecoder().decode(MessagesResponseBody.self, from: data), response.type == "message" else {289            throw AIError.malformedResponse290        }291        // Always look at the stop reason before the content.292        switch response.stop_reason {293        case "refusal": throw AIError.refused(category: response.stop_details?.category)294        case "max_tokens": throw AIError.truncated295        default: break296        }297        let text = AIPromptBuilder.cleanOutput(response.content.filter { $0.type == "text" }.compactMap(\.text).joined())298        guard !text.isEmpty else { throw AIError.emptyOutput }299        return AIResult(text: text,300                        usage: AIUsage(inputTokens: response.usage?.input_tokens ?? 0, outputTokens: response.usage?.output_tokens ?? 0),301                        model: response.model ?? request.model.id)302    }303304    // MARK: Transport loop305306    private func perform(_ request: URLRequest) async throws -> Data {307        var attempt = 0308        while true {309            try Task.checkCancellation()310            var failure = AIError.malformedResponse311            var serverDelay: Double?312            do {313                let (data, response) = try await transport.send(request)314                guard data.count <= Self.maxResponseBytes else { throw AIError.malformedResponse }315                if (200..<300).contains(response.statusCode) { return data }316                if (300..<400).contains(response.statusCode) { throw AIError.blockedRedirect }317                failure = Self.error(status: response.statusCode, data: data, headers: response)318                serverDelay = Self.retryAfter(response)319                if response.value(forHTTPHeaderField: "x-should-retry") == "false" { throw failure }320            } catch let transportFailure as TransportFailure {321                switch transportFailure {322                case .notSent: failure = .offline323                case .uncertain: throw AIError.outcomeUnknown324                case .timedOut: throw AIError.timeout325                case .cancelled: throw AIError.cancelled326                case .blockedRedirect: throw AIError.blockedRedirect327                }328            } catch is CancellationError {329                throw AIError.cancelled330            }331            guard failure.isTransient, attempt < retry.maxRetries else { throw failure }332            let delay = serverDelay ?? retry.baseDelay * pow(2, Double(attempt))333            guard delay <= retry.maxWait else { throw failure }334            attempt += 1335            do { try await sleep(delay) } catch { throw AIError.cancelled }336        }337    }338339    static func retryAfter(_ response: HTTPURLResponse) -> Double? {340        guard let raw = response.value(forHTTPHeaderField: "retry-after"), let seconds = Double(raw.trimmingCharacters(in: .whitespaces)),341              seconds.isFinite, seconds >= 0 else { return nil }342        return seconds343    }344345    static func error(status: Int, data: Data, headers: HTTPURLResponse) -> AIError {346        switch status {347        case 401: return .invalidKey348        case 403: return .forbidden349        case 404: return .modelUnavailable350        case 429: return .rateLimited(retryAfter: retryAfter(headers).map { Int($0.rounded(.up)) })351        case 529: return .overloaded352        case 500...599: return .server(status: status)353        default:354            let message = (try? JSONDecoder().decode(ErrorResponseBody.self, from: data))?.error?.message ?? ""355            return .badRequest(String(APIKeyFormat.redacting(message).prefix(200)))356        }357    }358}359
Files main
Menu

Theme