SPB Git

Repository Public

ProviderSupport.swift 23.0 KB 449 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraProviders/Sources/ProviderSupport.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import AstraCore89import Foundation9091/// Looks up the API key at request time, so a key added or rotated in Settings is used by the next request.92/// Returns nil (or an empty string) when no key is stored.93public typealias KeyProvider = @Sendable () throws -> String?9495// MARK: - Secrets9697enum Secrets {98    /// Removes the literal secrets and anything shaped like a credential from text bound for an error, a log or the screen.99    static func scrub(_ text: String, secrets: [String]) -> String {100        var out = text101        for secret in secrets where secret.count >= 4 { out = out.replacingOccurrences(of: secret, with: "•••") }102        // A message cut to a fixed length can end in the middle of a secret: mask a trailing fragment of one too.103        for secret in secrets where secret.count >= 8 {104            var length = min(secret.count - 1, out.count)105            while length >= 6 {106                if out.hasSuffix(secret.prefix(length)) { out = String(out.dropLast(length)) + "•••"; break }107                length -= 1108            }109        }110        return Redactor.redact(out)111    }112113    static func scrub(_ text: String?, secrets: [String]) -> String? { text.map { scrub($0, secrets: secrets) } }114115    /// Applies `scrub` to every user-visible string an error carries.116    static func scrub(_ error: AstraError, secrets: [String]) -> AstraError {117        func s(_ t: String) -> String { scrub(t, secrets: secrets) }118        func o(_ t: String?) -> String? { t.map(s) }119        switch error {120        case .unauthorized(let m): return .unauthorized(o(m))121        case .forbidden(let m): return .forbidden(o(m))122        case .rateLimited(let after, let m): return .rateLimited(retryAfter: after, message: o(m))123        case .quotaExceeded(let m): return .quotaExceeded(o(m))124        case .modelNotFound(let m): return .modelNotFound(s(m))125        case .contextTooLong(let m): return .contextTooLong(o(m))126        case .contentFiltered(let m): return .contentFiltered(o(m))127        case .invalidRequest(let m): return .invalidRequest(s(m))128        case .overloaded(let m): return .overloaded(o(m))129        case .server(let status, let m): return .server(status: status, message: o(m))130        case .network(let m): return .network(s(m))131        case .insecureEndpoint(let m): return .insecureEndpoint(s(m))132        case .decoding(let m): return .decoding(s(m))133        case .protocolViolation(let m): return .protocolViolation(s(m))134        case .unsupported(let m): return .unsupported(s(m))135        case .local(let m): return .local(s(m))136        case .internalFailure(let m): return .internalFailure(s(m))137        case .missingCredential, .timeout, .cancelled: return error138        }139    }140}141142/// Holds the secrets a running request resolved, so an error raised anywhere in that request can be scrubbed of them.143final class SecretBox: @unchecked Sendable {144    private let lock = NSLock()145    private var stored: [String] = []146    func add(_ secret: String?) { if let secret, !secret.isEmpty { lock.withLock { stored.append(secret) } } }147    var values: [String] { lock.withLock { stored } }148}149150// MARK: - Error bodies151152/// The error a provider put in a response body, whatever its dialect:153/// OpenAI `{"error":{"message","type","code","param"}}`, Anthropic `{"type":"error","error":{"type","message"}}`,154/// OpenRouter `{"error":{"code":402,"message","metadata":{...}}}`, Mistral `{"object":"error","message","type","code"}` (where155/// `message` may itself be `{"detail":[{"loc","msg"}]}`), Cerebras `{"message","type","param","code"}`, FastAPI-style156/// `{"detail": "..."}` or `{"detail":[{"loc","msg"}]}` (DeepInfra), and the looser shapes of compatible servers.157struct ProviderErrorBody: Sendable, Equatable {158    var code: String?159    var message: String?160    var param: String?161    /// Retry delay carried in the body (Google `RetryInfo`), in seconds.162    var retryDelay: TimeInterval?163164    static func parse(_ data: Data) -> ProviderErrorBody {165        guard let json = JSONValue.parse(data) else {166            // Not JSON (an HTML gateway page, a plain-text proxy error): never surface the raw body.167            return ProviderErrorBody()168        }169        return parse(json)170    }171172    static func parse(_ json: JSONValue) -> ProviderErrorBody {173        var out = ProviderErrorBody()174        let error = json["error"] ?? json175        if let text = error.stringValue {176            // xAI: {"code": "invalid-argument", "error": "<message>"}177            out.message = text178            out.code = json["code"]?.stringValue ?? json["code"]?.intValue.map(String.init)179            return out180        }181        var codes: [String] = []182        for key in ["code", "type", "status"] {183            if let s = error[key]?.stringValue, !s.isEmpty { codes.append(s) } else if let n = error[key]?.intValue { codes.append(String(n)) }184        }185        if let metadata = error["metadata"] {186            for key in ["error_type", "provider_code"] { if let s = metadata[key]?.stringValue, !s.isEmpty { codes.append(s) } }187            if let reasons = metadata["reasons"]?.arrayValue, !reasons.isEmpty { codes.append("moderation") }188        }189        // Google: {"error": {"code": 400, "status": "INVALID_ARGUMENT", "details": [{"reason": "API_KEY_INVALID"}, {"retryDelay": "17s"}]}}190        for detail in error["details"]?.arrayValue ?? [] {191            if let reason = detail["reason"]?.stringValue, !reason.isEmpty { codes.append(reason) }192            if let delay = detail["retryDelay"]?.stringValue, delay.hasSuffix("s"), let seconds = Double(delay.dropLast()) { out.retryDelay = RetryDelay.sane(seconds) }193        }194        out.code = codes.isEmpty ? nil : codes.joined(separator: " ")195        out.message = error["message"]?.stringValue ?? json["message"]?.stringValue ?? json["detail"]?.stringValue196        out.param = error["param"]?.stringValue197        if out.message == nil, let validation = validation(error["message"]?["detail"] ?? error["detail"] ?? json["detail"]) {198            out.message = validation.message199            out.param = out.param ?? validation.param200        }201        return out202    }203204    /// A validation list `[{"loc": ["body", "seed"], "msg": "Extra inputs are not permitted", "input": …}]` as "seed: Extra inputs are205    /// not permitted". `input` echoes what the client sent (possibly prompt text), so it is never read.206    private static func validation(_ detail: JSONValue?) -> (message: String, param: String?)? {207        guard let entries = detail?.arrayValue, !entries.isEmpty else { return nil }208        var lines: [String] = [], param: String?209        for entry in entries.prefix(4) {210            guard let msg = entry["msg"]?.stringValue, !msg.isEmpty else { continue }211            let path = (entry["loc"]?.arrayValue ?? []).compactMap { $0.stringValue ?? $0.intValue.map(String.init) }.filter { $0 != "body" }212            if param == nil { param = path.first }213            lines.append(path.isEmpty ? msg : path.joined(separator: ".") + ": " + msg)214        }215        return lines.isEmpty ? nil : (lines.joined(separator: "; "), param)216    }217}218219/// Recognises "this model does not take that parameter" rejections so a request can be retried without it.220enum UnsupportedParameter {221    /// One removable request field and the other spellings a server may use for it in an error message.222    struct Candidate: Sendable {223        var key: String224        var aliases: [String] = []225        init(_ key: String, _ aliases: [String] = []) { self.key = key; self.aliases = aliases }226    }227228    /// Returns the key of the candidate the rejection names, or nil when the failure is about something else.229    static func detect(_ failure: ProviderHTTP.Failure, candidates: [Candidate]) -> String? {230        guard failure.status == 400 || failure.status == 422 else { return nil }231        let body = failure.body232        let message = (body.message ?? "").lowercased()233        let code = (body.code ?? "").lowercased()234        let complains = code.contains("unsupported_parameter") || code.contains("unsupported_value") || code.contains("unknown_parameter")235            || message.contains("unsupported parameter") || message.contains("unsupported value") || message.contains("not supported")236            || message.contains("does not support") || message.contains("unknown parameter") || message.contains("unrecognized")237            || message.contains("extra inputs are not permitted") || message.contains("extra fields not permitted")238            || message.contains("unexpected keyword") || message.contains("is not allowed") || message.contains("unknown name")239            || message.contains("invalid value at") || message.contains("only supported") || message.contains("not permitted")240            || message.contains("is unsupported") || message.contains("is not enabled")241        guard complains else { return nil }242        if let param = body.param?.lowercased() {243            for c in candidates {244                for name in [c.key] + c.aliases where param == name.lowercased() || param.hasPrefix(name.lowercased() + ".") { return c.key }245            }246        }247        // Longest names first so "max_completion_tokens" is not mistaken for "max_tokens".248        let names = candidates.flatMap { c in ([c.key] + c.aliases).map { (name: $0.lowercased(), key: c.key) } }.sorted { $0.name.count > $1.name.count }249        for entry in names {250            let pattern = #"(^|[^a-z0-9_])"# + NSRegularExpression.escapedPattern(for: entry.name) + #"([^a-z0-9_]|$)"#251            if message.range(of: pattern, options: .regularExpression) != nil { return entry.key }252        }253        return nil254    }255}256257// MARK: - HTTP258259/// Shared request plumbing: JSON calls, streaming calls, typed errors, diagnostics. Holds no secret.260struct ProviderHTTP: Sendable {261    let kind: ProviderKind262    let transport: any HTTPTransport263    let diagnostics: (any DiagnosticsSink)?264265    struct Failure: Error {266        var status: Int267        var body: ProviderErrorBody268        var retryAfter: TimeInterval?269        func mapped(model: String?, secrets: [String]) -> AstraError {270            let message = Secrets.scrub(body.message, secrets: secrets)271            return Secrets.scrub(mapHTTPError(status: status, code: body.code, message: message, retryAfter: retryAfter, model: model), secrets: secrets)272        }273    }274275    static func requestID(_ response: HTTPURLResponse) -> String? {276        for name in ["request-id", "x-request-id", "x-generation-id", "x-kong-request-id", "msh-request-id", "x-ds-trace-id"] { if let v = response.header(name), !v.isEmpty { return v } }277        return nil278    }279280    static func request(_ url: URL, method: String = "GET", headers: [String: String], body: JSONValue? = nil, timeout: TimeInterval? = nil) -> URLRequest {281        var r = URLRequest(url: url)282        r.httpMethod = method283        r.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData284        if let timeout { r.timeoutInterval = timeout }285        for (name, value) in headers { r.setValue(value, forHTTPHeaderField: name) }286        if let body {287            r.httpBody = body.data288            r.setValue("application/json", forHTTPHeaderField: "Content-Type")289        }290        return r291    }292293    /// Sends a non-streaming request and decodes a JSON body; a non-2xx status becomes a typed error.294    func json(_ request: URLRequest, model: String? = nil, secrets: [String], normalize: (Failure) -> Failure = { $0 }) async throws -> (JSONValue, HTTPURLResponse) {295        let data: Data, response: HTTPURLResponse296        do { (data, response) = try await transport.send(request) } catch { throw Secrets.scrub(AstraError.wrap(error), secrets: secrets) }297        guard (200..<300).contains(response.statusCode) else {298            let parsed = ProviderErrorBody.parse(data)299            throw normalize(Failure(status: response.statusCode, body: parsed, retryAfter: response.retryAfter ?? parsed.retryDelay)).mapped(model: model, secrets: secrets)300        }301        guard let json = JSONValue.parse(data) else { throw AstraError.decoding("the provider did not answer with JSON") }302        return (json, response)303    }304305    /// Opens a streaming request. A non-2xx status throws `Failure` (unmapped, so callers can inspect it for a parameter fallback).306    func open(_ request: URLRequest, modelID: String, retryCount: Int, secrets: [String]) async throws -> (HTTPURLResponse, AsyncThrowingStream<String, Error>) {307        let started = Date()308        let response: HTTPURLResponse, lines: AsyncThrowingStream<String, Error>309        do { (response, lines) = try await transport.stream(request) } catch { throw Secrets.scrub(AstraError.wrap(error), secrets: secrets) }310        await diagnostics?.httpResponse(provider: kind, modelID: modelID, status: response.statusCode, requestID: Self.requestID(response),311                                        timeToHeaders: Date().timeIntervalSince(started), retryCount: retryCount)312        guard (200..<300).contains(response.statusCode) else {313            let body = await collectBody(lines)314            let parsed = ProviderErrorBody.parse(body)315            throw Failure(status: response.statusCode, body: parsed, retryAfter: response.retryAfter ?? parsed.retryDelay)316        }317        return (response, lines)318    }319}320321extension ProviderHTTP {322    /// Opens a streaming request, giving `adjust` the chance to edit the body and retry when the provider rejects a parameter.323    /// At most `maxAdjustments` retries; each one is reported to diagnostics with its retry count.324    func openAdjusting(body initial: [String: JSONValue], modelID: String, secrets: [String], maxAdjustments: Int = 3,325                       makeRequest: (JSONValue) throws -> URLRequest,326                       normalize: (Failure) -> Failure = { $0 },327                       adjust: (Failure, inout [String: JSONValue]) -> Bool) async throws -> (HTTPURLResponse, AsyncThrowingStream<String, Error>) {328        var body = initial329        var attempt = 0330        while true {331            do {332                return try await open(try makeRequest(.object(body)), modelID: modelID, retryCount: attempt, secrets: secrets)333            } catch let failure as Failure {334                let failure = normalize(failure)335                if attempt < maxAdjustments, adjust(failure, &body) { attempt += 1; continue }336                throw failure.mapped(model: modelID, secrets: secrets)337            }338        }339    }340}341342// MARK: - Streams343344typealias EventContinuation = AsyncThrowingStream<StreamEvent, Error>.Continuation345346/// Runs `body` in a task tied to the stream: when the consumer stops iterating or is cancelled, the task is cancelled,347/// which ends the iteration over the transport's line stream and so cancels the HTTP request itself.348func makeEventStream(secrets: @escaping @Sendable () -> [String],349                     _ body: @escaping @Sendable (EventContinuation) async throws -> Void) -> AsyncThrowingStream<StreamEvent, Error> {350    AsyncThrowingStream(bufferingPolicy: .unbounded) { continuation in351        let task = Task {352            do {353                try await body(continuation)354                if Task.isCancelled { continuation.finish(throwing: AstraError.cancelled) } else { continuation.finish() }355            } catch {356                if Task.isCancelled { continuation.finish(throwing: AstraError.cancelled); return }357                continuation.finish(throwing: Secrets.scrub(AstraError.wrap(error), secrets: secrets()))358            }359        }360        continuation.onTermination = { _ in task.cancel() }361    }362}363364/// Reads a key through its provider closure. A missing or blank key is `missingCredential` for providers that require one.365func resolveKey(_ provider: KeyProvider, kind: ProviderKind, required: Bool) throws -> String? {366    let raw: String?367    do { raw = try provider() } catch let e as AstraError { throw e } catch {368        // The store failed (a locked device, a Keychain error): the key may well exist, so this is not "add a key".369        throw AstraError.internalFailure("The saved \(kind.displayName) key could not be read: \((error as? LocalizedError)?.errorDescription ?? "the Keychain refused the request"). Unlock the device and try again.")370    }371    let key = raw?.trimmingCharacters(in: .whitespacesAndNewlines)372    if let key, !key.isEmpty { return key }373    if required { throw AstraError.missingCredential(kind) }374    return nil375}376377// MARK: - Provider state378379/// Opaque per-turn data a provider wants back in the next request of a tool cycle (reasoning text, thinking blocks,380/// signatures, encrypted reasoning). It rides on `ToolCall.providerState`, which the app stores and returns unchanged.381/// It is never shown, logged or put in an error; it only ever goes back to the provider that produced it.382enum ProviderState {383    /// Larger states are dropped: the encoder then takes the path it uses for a call that never had state.384    static let maxBytes = 256 * 1024385386    /// Wraps `payload` with the format that produced it, or nil when there is nothing to keep or it is too large.387    static func make(_ format: String, _ payload: JSONValue) -> JSONValue? {388        switch payload {389        case .null: return nil390        case .string(let s) where s.isEmpty: return nil391        case .array(let a) where a.isEmpty: return nil392        default: break393        }394        let state: JSONValue = ["format": .string(format), "payload": payload]395        // `JSONValue` is itself expressible by `nil` (JSON null), so the absent case is spelled out.396        guard state.serialized().utf8.count <= maxBytes else { return JSONValue?.none }397        return state398    }399400    /// The payload of a call's state when it was produced in `format`; state from another provider or dialect is ignored.401    static func payload(_ call: ToolCall, format: String) -> JSONValue? {402        guard let state = call.providerState, state["format"]?.stringValue == format else { return nil }403        return state["payload"]404    }405406    /// The first call of a turn carries the turn-level state.407    static func payload(_ calls: [ToolCall], format: String) -> JSONValue? {408        for call in calls { if let found = payload(call, format: format) { return found } }409        return nil410    }411}412413// MARK: - Tool calls414415enum ToolArguments {416    /// Parses accumulated argument text. Empty text is an empty object; anything that is not a JSON object is kept verbatim417    /// under `_raw` so the caller can show or repair it instead of losing it.418    static func parse(_ text: String) -> JSONValue {419        let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)420        if trimmed.isEmpty { return .object([:]) }421        if let value = JSONValue.parse(trimmed), case .object = value { return value }422        return .object(["_raw": .string(text)])423    }424425    /// Serialises arguments for the wire. A call whose arguments never parsed is replayed with its original text.426    static func wireText(_ arguments: JSONValue) -> String {427        if case .object(let o) = arguments, o.count == 1, let raw = o["_raw"]?.stringValue { return raw }428        if case .object = arguments { return arguments.serialized() }429        return "{}"430    }431432    static func wireObject(_ arguments: JSONValue) -> JSONValue {433        if case .object = arguments { return arguments }434        return .object([:])435    }436}437438func dataURL(_ image: ImageInput) -> String { "data:\(image.mimeType);base64,\(image.data.base64EncodedString())" }439440extension Date {441    /// ISO calendar day in UTC, the format `Pricing.asOf` and `MetadataSource.documentation(asOf:)` use.442    var isoDay: String {443        var calendar = Calendar(identifier: .gregorian)444        calendar.timeZone = TimeZone(identifier: "UTC") ?? .gmt445        let c = calendar.dateComponents([.year, .month, .day], from: self)446        return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)447    }448}449
Files main
Menu

Theme