Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraCore/Sources/Errors.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 Foundation8990/// Every failure the app can show. Messages are written for the person using the app and never contain secrets.91public enum AstraError: Error, Sendable, Hashable, Codable, LocalizedError {92 case missingCredential(ProviderKind)93 case unauthorized(String?)94 case forbidden(String?)95 case rateLimited(retryAfter: TimeInterval?, message: String?)96 case quotaExceeded(String?)97 case modelNotFound(String)98 case contextTooLong(String?)99 case contentFiltered(String?)100 case invalidRequest(String)101 case overloaded(String?)102 case server(status: Int, message: String?)103 case network(String)104 case timeout105 case insecureEndpoint(String)106 case decoding(String)107 case protocolViolation(String)108 case unsupported(String)109 case local(String)110 case cancelled111112 public var errorDescription: String? { message }113114 public var title: String {115 switch self {116 case .missingCredential: "No API key"117 case .unauthorized: "Key rejected"118 case .forbidden: "Not allowed"119 case .rateLimited: "Rate limited"120 case .quotaExceeded: "Out of credit"121 case .modelNotFound: "Model unavailable"122 case .contextTooLong: "Conversation too long"123 case .contentFiltered: "Blocked by the provider"124 case .invalidRequest: "Request rejected"125 case .overloaded: "Provider overloaded"126 case .server: "Provider error"127 case .network: "Network problem"128 case .timeout: "Timed out"129 case .insecureEndpoint: "Insecure endpoint"130 case .decoding, .protocolViolation: "Unexpected response"131 case .unsupported: "Not supported"132 case .local: "On-device model"133 case .cancelled: "Stopped"134 }135 }136137 public var message: String {138 switch self {139 case .missingCredential(let p): "Add your \(p.displayName) API key in Models to use this model."140 case .unauthorized(let m): m ?? "The provider rejected this API key. Check it or replace it."141 case .forbidden(let m): m ?? "This key is not allowed to use that model or feature."142 case .rateLimited(let after, let m):143 if let after, after > 0 { "The provider is rate limiting this key. Try again in \(Int(after.rounded(.up))) s." }144 else { m ?? "The provider is rate limiting this key. Try again shortly." }145 case .quotaExceeded(let m): m ?? "This account has no remaining credit or quota."146 case .modelNotFound(let id): "The provider does not offer “\(id)” to this key."147 case .contextTooLong(let m): m ?? "The conversation no longer fits in this model's context window. Shorten it or lower the context budget."148 case .contentFiltered(let m): m ?? "The provider declined to answer this request."149 case .invalidRequest(let m): m150 case .overloaded(let m): m ?? "The provider is overloaded right now. Try again in a moment."151 case .server(let status, let m): m ?? "The provider returned an error (HTTP \(status))."152 case .network(let m): m153 case .timeout: "The provider took too long to answer."154 case .insecureEndpoint(let m): m155 case .decoding(let m): "The response could not be read: \(m)"156 case .protocolViolation(let m): "The response stream was malformed: \(m)"157 case .unsupported(let m): m158 case .local(let m): m159 case .cancelled: "Generation was stopped."160 }161 }162163 /// True when retrying the same request later can succeed without changing anything.164 public var isTransient: Bool {165 switch self {166 case .rateLimited, .overloaded, .network, .timeout: true167 case .server(let status, _): status >= 500168 default: false169 }170 }171172 public static func wrap(_ error: Error) -> AstraError {173 if let e = error as? AstraError { return e }174 if error is CancellationError { return .cancelled }175 if let u = error as? URLError {176 switch u.code {177 case .cancelled: return .cancelled178 case .timedOut: return .timeout179 case .notConnectedToInternet, .dataNotAllowed: return .network("This device is offline.")180 case .networkConnectionLost: return .network("The connection was lost while the answer was arriving.")181 case .cannotFindHost, .cannotConnectToHost, .dnsLookupFailed: return .network("The server could not be reached.")182 case .secureConnectionFailed, .serverCertificateUntrusted, .serverCertificateHasBadDate, .serverCertificateNotYetValid,183 .serverCertificateHasUnknownRoot, .clientCertificateRejected:184 return .network("A secure connection to the server could not be established.")185 case .appTransportSecurityRequiresSecureConnection: return .insecureEndpoint("iOS blocked this plain-HTTP connection.")186 default: return .network(u.localizedDescription)187 }188 }189 return .network((error as? LocalizedError)?.errorDescription ?? String(describing: error))190 }191}192193/// Maps an HTTP failure to a typed error. `message` must already be the provider's human text, never a raw body with headers.194public func mapHTTPError(status: Int, code: String?, message: String?, retryAfter: TimeInterval?, model: String?) -> AstraError {195 let lowered = ((code ?? "") + " " + (message ?? "")).lowercased()196 let clean = message.map { Redactor.redact(String($0.prefix(400))) }197 switch status {198 case 401: return .unauthorized(clean)199 case 402: return .quotaExceeded(clean)200 case 403:201 if lowered.contains("moderation") || lowered.contains("flagged") { return .contentFiltered(clean) }202 return .forbidden(clean)203 case 404:204 if lowered.contains("model"), let model { return .modelNotFound(model) }205 return .invalidRequest(clean ?? "The endpoint was not found (HTTP 404).")206 case 408: return .timeout207 case 413: return .contextTooLong(clean)208 case 429:209 if lowered.contains("insufficient_quota") || lowered.contains("billing") || lowered.contains("credit") { return .quotaExceeded(clean) }210 return .rateLimited(retryAfter: retryAfter, message: clean)211 case 400, 422:212 if lowered.contains("context_length") || lowered.contains("context window") || lowered.contains("too long") || lowered.contains("maximum context")213 || lowered.contains("too many tokens") { return .contextTooLong(clean) }214 if lowered.contains("model_not_found") || lowered.contains("not a valid model"), let model { return .modelNotFound(model) }215 if lowered.contains("content_policy") || lowered.contains("content management") { return .contentFiltered(clean) }216 return .invalidRequest(clean ?? "The provider rejected the request (HTTP \(status)).")217 case 529, 503: return .overloaded(clean)218 default: return .server(status: status, message: clean)219 }220}221222/// Removes anything that looks like a credential before text reaches a log, a diagnostic record, an export or the screen.223public enum Redactor {224 private static let patterns: [(NSRegularExpression, String)] = {225 let raw: [(String, String)] = [226 (#"sk-ant-[A-Za-z0-9_\-]{8,}"#, "sk-ant-•••"),227 (#"sk-or-v1-[A-Za-z0-9]{8,}"#, "sk-or-v1-•••"),228 (#"sk-proj-[A-Za-z0-9_\-]{8,}"#, "sk-proj-•••"),229 (#"sk-[A-Za-z0-9_\-]{16,}"#, "sk-•••"),230 (#"hf_[A-Za-z0-9]{16,}"#, "hf_•••"),231 (#"xai-[A-Za-z0-9]{16,}"#, "xai-•••"),232 (#"AIza[A-Za-z0-9_\-]{20,}"#, "AIza•••"),233 (#"(?i)([?&]key=)[A-Za-z0-9_\-]{8,}"#, "$1•••"),234 (#"(?i)(bearer)\s+[A-Za-z0-9._~+/=\-]{8,}"#, "$1 •••"),235 (#"(?i)((?:x-api-key|api-key|authorization|x-goog-api-key|proxy-authorization)["']?\s*[:=]\s*["']?)[^\s"',;}]{6,}"#, "$1•••"),236 (#"(?i)((?:api[_-]?key|access[_-]?token|session[_-]?token|refresh[_-]?token|client[_-]?secret|secret|password|passwd)["']?\s*[:=]\s*["']?)[^\s"',;}&]{6,}"#, "$1•••"),237 (#"(?i)((?:^|[?&\s])(?:token|key|sig|signature)=)[A-Za-z0-9._~+/\-]{8,}"#, "$1•••"),238 ]239 return raw.compactMap { p, r in (try? NSRegularExpression(pattern: p)).map { ($0, r) } }240 }()241242 public static func redact(_ text: String) -> String {243 var out = text244 for (regex, replacement) in patterns {245 out = regex.stringByReplacingMatches(in: out, range: NSRange(out.startIndex..., in: out), withTemplate: replacement)246 }247 return out248 }249250 /// Header names whose values are never recorded.251 public static let sensitiveHeaders: Set<String> = ["authorization", "x-api-key", "api-key", "proxy-authorization", "cookie", "set-cookie", "x-goog-api-key"]252253 public static func redact(headers: [String: String]) -> [String: String] {254 var out: [String: String] = [:]255 for (k, v) in headers { out[k] = sensitiveHeaders.contains(k.lowercased()) ? "•••" : redact(v) }256 return out257 }258259 /// Shows only enough of a key to recognise it: prefix and last four characters.260 public static func mask(key: String) -> String {261 let t = key.trimmingCharacters(in: .whitespacesAndNewlines)262 guard t.count > 12 else { return String(repeating: "•", count: max(t.count, 4)) }263 let prefixLength = t.hasPrefix("sk-ant-") ? 7 : t.hasPrefix("sk-or-") ? 6 : t.hasPrefix("sk-") ? 3 : t.hasPrefix("xai-") ? 4 : t.hasPrefix("AIza") ? 4 : 0264 return String(t.prefix(prefixLength)) + "••••••••" + String(t.suffix(4))265 }266}267