Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Claude Remote / Codex Remote9// File : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteAPI/APIError.swift10// Module : ClaudeRemoteAPI11// Repository : https://git.spboucher.ai/claude-remote-apple12// Project Website : https://claude.spboucher.ai13// Created : 2026-11-2914// Last Modified : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteModels89import Foundation90import os9192/// Loggers of the kit. Nothing secret is ever interpolated publicly: tokens, bodies, terminal93/// bytes and file contents are never logged at all; paths and queries are `.private`.94public enum CRLog {95 public static let subsystem = "ai.spboucher.clauderemote.kit"96 public static let api = Logger(subsystem: subsystem, category: "api")97 public static let auth = Logger(subsystem: subsystem, category: "auth")98 public static let socket = Logger(subsystem: subsystem, category: "socket")99 public static let terminal = Logger(subsystem: subsystem, category: "terminal")100 public static let core = Logger(subsystem: subsystem, category: "core")101}102103/// A failed API call: the server's `{error:{code,message,details}}` with its HTTP status, or a104/// client-side failure (`status == 0`).105public struct APIError: Error, Hashable, Sendable, LocalizedError, CustomStringConvertible {106 public enum Kind: Hashable, Sendable {107 /// 401 `unauthenticated`: the session is revoked, expired or unknown → sign in again.108 case unauthenticated109 /// 401 `token_expired`: handled by `APIClient` (refresh + retry); surfaces only if refresh fails.110 case tokenExpired111 case invalidCredentials112 case secondFactorRequired113 case forbidden114 case notFound115 /// 409 `conflict`: the file changed on disk (`conflictSha256` = current hash, nil = deleted).116 case conflict117 /// 409 `exists`: upload destination exists; retry with `overwrite: true`.118 case exists119 /// Any other 409 (`invalid_state`, `session_live`, `task_finished`, `not_idempotent`, …).120 case invalidState121 /// 429 `locked`: too many failed sign-in attempts; see `retryAfter`.122 case locked123 case rateLimited124 case tooManySessions125 case payloadTooLarge126 /// 415 `binary`: the file is not text.127 case binary128 case invalidRequest129 case notImplemented130 case runtimeUnavailable131 case server132 /// No answer from the server (offline, DNS, TLS, timeout).133 case network134 case cancelled135 case decoding136 /// Refused locally (non-HTTPS base URL, missing credential).137 case client138 }139140 public var status: Int141 public var code: String142 public var message: String143 public var details: JSONValue?144 /// From the `Retry-After` header or `details.retryAfterSec`.145 public var retryAfter: TimeInterval?146147 public init(status: Int, code: String, message: String, details: JSONValue? = nil, retryAfter: TimeInterval? = nil) {148 self.status = status149 self.code = code150 self.message = message151 self.details = details152 self.retryAfter = retryAfter153 }154155 public var kind: Kind {156 switch (status, code) {157 case (0, "network"): return .network158 case (0, "cancelled"): return .cancelled159 case (0, "decoding"): return .decoding160 case (0, _): return .client161 case (401, "token_expired"): return .tokenExpired162 case (401, "invalid_credentials"), (401, "invalid_code"), (401, "passkey_rejected"), (401, "invalid_setup_token"): return .invalidCredentials163 case (401, _): return .unauthenticated164 case (403, "second_factor_required"): return .secondFactorRequired165 case (403, _): return .forbidden166 case (404, _): return .notFound167 case (409, "conflict"): return .conflict168 case (409, "exists"): return .exists169 case (409, _): return .invalidState170 case (413, _): return .payloadTooLarge171 case (415, _): return .binary172 case (429, "locked"): return .locked173 case (429, "too_many_sessions"): return .tooManySessions174 case (429, _): return .rateLimited175 case (400, _), (422, _): return .invalidRequest176 case (501, _): return .notImplemented177 case (503, _): return .runtimeUnavailable178 default: return .server179 }180 }181182 /// The session is gone for good: the UI must return to sign-in.183 public var requiresSignIn: Bool { kind == .unauthenticated }184 /// Worth retrying later without user action.185 public var isTransient: Bool { [.network, .runtimeUnavailable, .rateLimited].contains(kind) || status == 502 || status == 504 }186 /// For `.conflict`: sha256 of the file now on disk (nil when it was deleted).187 public var conflictSha256: String? { details?["sha256"]?.stringValue }188 /// Field errors of a 400 `invalid_request`: `[{path, message}]`.189 public var validationIssues: [(path: String, message: String)] {190 (details?.arrayValue ?? []).compactMap { item in191 guard let message = item["message"]?.stringValue else { return nil }192 let path = item["path"]?.stringValue ?? item["path"]?.arrayValue?.compactMap { $0.stringValue ?? $0.intValue.map(String.init) }.joined(separator: ".") ?? ""193 return (path, message)194 }195 }196197 public var errorDescription: String? { message }198 public var description: String { "APIError(\(status) \(code): \(message))" }199200 // MARK: Factories201202 public static func network(_ message: String = "The server could not be reached.") -> APIError {203 APIError(status: 0, code: "network", message: message)204 }205 public static let cancelled = APIError(status: 0, code: "cancelled", message: "Cancelled.")206 public static func client(_ code: String, _ message: String) -> APIError { APIError(status: 0, code: code, message: message) }207 public static let notSignedIn = APIError(status: 401, code: "unauthenticated", message: "authentication required")208209 /// Maps an HTTP error answer. Tolerates non-JSON bodies (proxies, HTML error pages).210 public static func from(status: Int, data: Data, headers: [AnyHashable: Any] = [:]) -> APIError {211 var retry: TimeInterval?212 for (key, value) in headers where (key as? String)?.lowercased() == "retry-after" {213 retry = (value as? String).flatMap(TimeInterval.init)214 }215 if let body = try? JSONDecoder().decode(APIErrorBody.self, from: data) {216 if retry == nil { retry = body.error.details?["retryAfterSec"]?.numberValue }217 return APIError(status: status, code: body.error.code, message: body.error.message, details: body.error.details, retryAfter: retry)218 }219 let code: String220 switch status {221 case 401: code = "unauthenticated"222 case 403: code = "forbidden"223 case 404: code = "not_found"224 case 429: code = "rate_limited"225 case 502: code = "bad_gateway"226 case 503: code = "unavailable"227 default: code = "http_\(status)"228 }229 return APIError(status: status, code: code, message: HTTPURLResponse.localizedString(forStatusCode: status), retryAfter: retry)230 }231232 /// Maps a transport failure (`URLError`, cancellation) or passes an `APIError` through.233 public static func wrap(_ error: Error) -> APIError {234 if let e = error as? APIError { return e }235 if error is CancellationError { return .cancelled }236 if let e = error as? URLError {237 if e.code == .cancelled { return .cancelled }238 return APIError(status: 0, code: "network", message: e.localizedDescription)239 }240 if error is DecodingError { return APIError(status: 0, code: "decoding", message: "The server answered with an unexpected format.") }241 return APIError(status: 0, code: "network", message: error.localizedDescription)242 }243}244245/// Identity of the running app, sent as `X-CR-Client: native/<platform>/<appVersion>`.246public struct ClientInfo: Hashable, Sendable {247 public var platform: NativePlatform248 public var appVersion: String249250 public init(platform: NativePlatform, appVersion: String) {251 self.platform = platform252 self.appVersion = appVersion.isEmpty ? "0" : String(appVersion.prefix(40))253 }254255 public var headerValue: String { "native/\(platform.rawValue)/\(appVersion)" }256257 /// Platform of the running process (iPad → `ipados`).258 @MainActor public static var currentPlatform: NativePlatform {259 #if os(macOS)260 return .macos261 #else262 return ProcessInfo.processInfo.isiOSAppOnMac ? .ipados : (UIDeviceIdiom.isPad ? .ipados : .ios)263 #endif264 }265266 /// Reads `CFBundleShortVersionString` of the main bundle.267 @MainActor public static func current(bundle: Bundle = .main) -> ClientInfo {268 ClientInfo(platform: currentPlatform, appVersion: bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0")269 }270}271272#if canImport(UIKit)273import UIKit274@MainActor enum UIDeviceIdiom {275 static var isPad: Bool { UIDevice.current.userInterfaceIdiom == .pad }276}277#endif278