Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Core/Models/AIModel.swift4// Description: Unified model catalogue entries (direct + OpenRouter), logo registry, routing modes, presets, prompts, memories, usage and security DTOs.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation1112/// Facts published by a route's own catalogue (OpenRouter `GET /models`). Never hand-written, never guessed.13struct CatalogInfo: Hashable, Sendable, Codable {14 struct Reasoning: Hashable, Sendable, Codable { var mandatory: Bool?; var efforts: [String]?; var defaultEffort: String? }15 var slug: String?16 var inputModalities: [String]17 var outputModalities: [String]18 var supportedParameters: [String]19 var tokenizer: String?20 var huggingFaceId: String?21 var moderated: Bool?22 var expirationDate: String?23 var aliasOf: String?24 var created: Double?25 var reasoning: Reasoning?26 var rankedIn: [String]27 /// `openrouter` or `local` — which catalogue published these facts.28 var source: String?29 // facts of the local route (MacLustr AI, MLX)30 var quantization: String?31 var license: String?32 var revision: String?33 var servedBy: String?34 /// Third-party benchmark figures passed through with their source name (only present in `/api/models/detail`).35 var benchmarks: JSONValue?36 var prices: [String: Double]?3738 private enum K: String, CodingKey { case slug, inputModalities, outputModalities, supportedParameters, tokenizer, huggingFaceId, moderated, expirationDate, aliasOf, created, reasoning, rankedIn, benchmarks, prices, source, quantization, license, revision, servedBy }39 init(from decoder: Decoder) throws {40 let c = try decoder.container(keyedBy: K.self)41 slug = c.flexString(.slug)42 inputModalities = (try? c.decodeIfPresent([String].self, forKey: .inputModalities)) ?? []43 outputModalities = (try? c.decodeIfPresent([String].self, forKey: .outputModalities)) ?? []44 supportedParameters = (try? c.decodeIfPresent([String].self, forKey: .supportedParameters)) ?? []45 tokenizer = c.flexString(.tokenizer); huggingFaceId = c.flexString(.huggingFaceId); moderated = c.flexBool(.moderated)46 expirationDate = c.flexString(.expirationDate); aliasOf = c.flexString(.aliasOf); created = c.flexDouble(.created)47 reasoning = try? c.decodeIfPresent(Reasoning.self, forKey: .reasoning)48 rankedIn = (try? c.decodeIfPresent([String].self, forKey: .rankedIn)) ?? []49 benchmarks = try? c.decodeIfPresent(JSONValue.self, forKey: .benchmarks)50 prices = try? c.decodeIfPresent([String: Double].self, forKey: .prices)51 source = c.flexString(.source); quantization = c.flexString(.quantization); license = c.flexString(.license); revision = c.flexString(.revision); servedBy = c.flexString(.servedBy)52 }53 var createdDate: Date? { created.map { Date(timeIntervalSince1970: $0) } }54}5556/// One entry of the unified catalogue: a model verified by the local bench (direct route) or listed by OpenRouter.57/// Every field beyond `id` is decoded tolerantly: an unknown provider, status or category never breaks the catalogue.58struct AIModel: Identifiable, Hashable, Sendable, Codable {59 var id: String60 /// The API that executes the request: openai · anthropic · xai · openrouter (or anything a newer server adds).61 var provider: String62 var displayName: String63 var kind: String64 var available: Bool65 var hidden: Bool66 var favorite: Bool67 var contextWindow: Int?68 var maxOutputTokens: Int?69 var priceInput: Double?70 var priceOutput: Double?71 var priceCachedInput: Double?72 var priceNotes: String?73 var vision: Bool74 var reasoning: Bool75 var tools: Bool76 var audioInput: Bool77 var imageGeneration: Bool78 var structuredOutput: Bool79 var effortLevels: [String]?80 var qualityScore: Double?81 var p50LatencyMs: Int?82 var p50TtftMs: Int?83 var unavailableReason: String?84 /// `direct` or `openrouter` — the badge shown next to the model.85 var route: String86 /// Who made the model (main logo): registry slug when known, else the raw vendor slug.87 var creator: String88 var creatorName: String89 /// Slug of the logo registry, nil → neutral monogram.90 var logo: String?91 /// verified · catalog · untested · unavailable · unsupported (or a value this build does not know yet).92 var status: String93 var description: String?94 var categories: [String]95 var catalog: CatalogInfo?96 var lastUsedAt: Date?9798 private enum K: String, CodingKey { case id, provider, displayName, kind, available, hidden, favorite, contextWindow, maxOutputTokens, pricing, capabilities, benchmark, unavailableReason, route, creator, creatorName, logo, status, description, categories, catalog, lastUsedAt }99100 init(id: String, provider: String, displayName: String, kind: String = "chat", available: Bool = true, route: String? = nil, creator: String? = nil, creatorName: String? = nil, logo: String? = nil, status: String = "verified") {101 self.id = id; self.provider = provider; self.displayName = displayName; self.kind = kind; self.available = available102 hidden = false; favorite = false; vision = false; reasoning = false; tools = false; audioInput = false; imageGeneration = false; structuredOutput = false103 self.route = route ?? AIModel.impliedRoute(id: id, provider: provider)104 self.creator = creator ?? provider; self.creatorName = creatorName ?? AIModel.providerLabel(creator ?? provider)105 self.logo = logo ?? LogoRegistry.slug(for: creator ?? provider); self.status = status; categories = []106 }107108 init(from decoder: Decoder) throws {109 let c = try decoder.container(keyedBy: K.self)110 id = try c.decode(String.self, forKey: .id)111 provider = c.flexString(.provider) ?? (id.hasPrefix("or:") ? "openrouter" : id.hasPrefix("local:") ? "local" : "openai")112 displayName = c.flexString(.displayName) ?? id113 kind = c.flexString(.kind) ?? "chat"114 available = c.flexBool(.available) ?? false115 hidden = c.flexBool(.hidden) ?? false116 favorite = c.flexBool(.favorite) ?? false117 contextWindow = c.flexInt(.contextWindow); maxOutputTokens = c.flexInt(.maxOutputTokens)118 let pricing = try? c.decodeIfPresent(JSONValue.self, forKey: .pricing)119 priceInput = pricing?["input"]?.doubleValue; priceOutput = pricing?["output"]?.doubleValue120 priceCachedInput = pricing?["cachedInput"]?.doubleValue; priceNotes = pricing?["notes"]?.stringValue121 let caps = try? c.decodeIfPresent(JSONValue.self, forKey: .capabilities)122 // a capability is true, false or "unknown": only a verified `true` lights the glyph123 func cap(_ k: String) -> Bool { caps?[k]?.boolValue ?? false }124 vision = cap("vision"); reasoning = cap("reasoning"); tools = cap("tools")125 audioInput = cap("audioInput"); imageGeneration = cap("imageGeneration"); structuredOutput = cap("structuredOutput")126 effortLevels = caps?["effortLevels"]?.arrayValue?.compactMap(\.stringValue)127 let bench = try? c.decodeIfPresent(JSONValue.self, forKey: .benchmark)128 qualityScore = bench?["qualityScore"]?.doubleValue; p50LatencyMs = bench?["p50LatencyMs"]?.intValue; p50TtftMs = bench?["p50TtftMs"]?.intValue129 unavailableReason = c.flexString(.unavailableReason)130 route = c.flexString(.route) ?? AIModel.impliedRoute(id: id, provider: provider)131 // older servers (0.3) do not send the maker: a direct model is made by its provider132 let rawCreator = c.flexString(.creator) ?? (id.hasPrefix("or:") ? String(id.dropFirst(3).prefix { $0 != "/" }) : provider)133 creator = rawCreator134 creatorName = c.flexString(.creatorName) ?? AIModel.providerLabel(rawCreator)135 logo = c.contains(.logo) ? c.flexString(.logo) : LogoRegistry.slug(for: rawCreator)136 status = c.flexString(.status) ?? (available ? "verified" : "unavailable")137 description = c.flexString(.description)138 categories = (try? c.decodeIfPresent([String].self, forKey: .categories)) ?? []139 catalog = try? c.decodeIfPresent(CatalogInfo.self, forKey: .catalog)140 lastUsedAt = c.flexDate(.lastUsedAt)141 }142143 func encode(to encoder: Encoder) throws {144 var c = encoder.container(keyedBy: K.self)145 try c.encode(id, forKey: .id); try c.encode(provider, forKey: .provider); try c.encode(displayName, forKey: .displayName); try c.encode(kind, forKey: .kind)146 try c.encode(available, forKey: .available); try c.encode(hidden, forKey: .hidden); try c.encode(favorite, forKey: .favorite)147 try c.encodeIfPresent(contextWindow, forKey: .contextWindow); try c.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens)148 var pricing: [String: JSONValue] = [:]149 if let priceInput { pricing["input"] = .number(priceInput) }; if let priceOutput { pricing["output"] = .number(priceOutput) }150 if let priceCachedInput { pricing["cachedInput"] = .number(priceCachedInput) }; if let priceNotes { pricing["notes"] = .string(priceNotes) }151 try c.encode(JSONValue.object(pricing), forKey: .pricing)152 var caps: [String: JSONValue] = ["vision": .bool(vision), "reasoning": .bool(reasoning), "tools": .bool(tools), "audioInput": .bool(audioInput), "imageGeneration": .bool(imageGeneration), "structuredOutput": .bool(structuredOutput)]153 if let effortLevels { caps["effortLevels"] = .array(effortLevels.map(JSONValue.string)) }154 try c.encode(JSONValue.object(caps), forKey: .capabilities)155 var bench: [String: JSONValue] = [:]156 if let qualityScore { bench["qualityScore"] = .number(qualityScore) }157 if let p50LatencyMs { bench["p50LatencyMs"] = .number(Double(p50LatencyMs)) }158 if let p50TtftMs { bench["p50TtftMs"] = .number(Double(p50TtftMs)) }159 try c.encode(JSONValue.object(bench), forKey: .benchmark)160 try c.encodeIfPresent(unavailableReason, forKey: .unavailableReason)161 try c.encode(route, forKey: .route); try c.encode(creator, forKey: .creator); try c.encode(creatorName, forKey: .creatorName)162 if let logo { try c.encode(logo, forKey: .logo) } else { try c.encodeNil(forKey: .logo) }163 try c.encode(status, forKey: .status); try c.encodeIfPresent(description, forKey: .description); try c.encode(categories, forKey: .categories)164 try c.encodeIfPresent(catalog, forKey: .catalog); try c.encodeIfPresent(lastUsedAt.map(ISO8601.string), forKey: .lastUsedAt)165 }166167 /// Conversational models that may be selected: verified by the bench, or listed by the OpenRouter catalogue168 /// (labelled « non testé »). Unavailable, unsupported and hidden models are never offered.169 var isSelectableForChat: Bool { available && !hidden && ["chat", "chat-pro", "search"].contains(kind) && status != "unavailable" && status != "unsupported" }170 var isOpenRouter: Bool { route == "openrouter" }171 /// Served by the owner's own inference service (MacLustr AI): no per-token price, never billed.172 var isLocal: Bool { route == "local" }173 /// The route when the server does not state it (older servers): from the id prefix or the provider.174 static func impliedRoute(id: String, provider: String?) -> String {175 if id.hasPrefix("or:") || provider == "openrouter" { return "openrouter" }176 if id.hasPrefix("local:") || provider == "local" { return "local" }177 return "direct"178 }179 /// « Gemini 4 Neon · OpenRouter », « Qwen3 · local » — for plain-text menus where the badge cannot be drawn.180 var nameWithRoute: String { isOpenRouter ? "\(displayName) · OpenRouter" : isLocal ? String(localized: "\(displayName) · local") : displayName }181 var isVerified: Bool { status == "verified" }182 /// Listed by the OpenRouter catalogue, not benchmarked locally — must be said wherever facts are shown.183 var isCatalogOnly: Bool { status == "catalog" }184 var isFree: Bool { categories.contains("free") || (priceInput == 0 && priceOutput == 0) }185 var isOpenWeight: Bool { categories.contains("open-weight") || catalog?.huggingFaceId != nil }186 var shortName: String {187 displayName.replacingOccurrences(of: "Claude ", with: "").replacingOccurrences(of: #" \(\d{4}-\d{2}-\d{2}\)$"#, with: "", options: .regularExpression)188 }189 /// Lowercased text searched by the model sheet and the Explorer.190 var searchHaystack: String { "\(displayName) \(id) \(creatorName) \(creator)".lowercased() }191 static func providerLabel(_ p: String?) -> String {192 switch p {193 case "openai": return "OpenAI"; case "anthropic": return "Anthropic"; case "xai": return "xAI"; case "openrouter": return "OpenRouter"; case "local": return "MacLustr AI"194 default:195 guard let p, !p.isEmpty else { return "—" }196 return LogoRegistry.makers[LogoRegistry.slug(for: p) ?? p]?.name ?? p197 }198 }199 static func routeLabel(_ route: String?) -> String {200 switch route { case "openrouter": "OpenRouter"; case "local": String(localized: "Local (MacLustr)"); default: String(localized: "Direct") }201 }202 /// How a cost is qualified next to its amount: a local answer costs nothing and is neither billed nor estimated.203 static func costLabel(_ cost: Double?, exact: Bool, route: String?) -> String? {204 if route == "local" { return String(localized: "local · 0 $") }205 guard let cost else { return nil }206 return "\(Format.usd(cost)) \(exact ? String(localized: "facturé") : String(localized: "estimé"))"207 }208}209210/// The canonical maker-logo registry (generated part: `LogoRegistry.generated.swift`).211enum LogoRegistry {212 /// Registry slug of a maker or catalogue vendor prefix (`meta-llama` → `meta`), nil when no logo exists.213 static func slug(for creator: String?) -> String? {214 guard let creator, !creator.isEmpty else { return nil }215 let key = creator.lowercased()216 if makers[key] != nil { return key }217 if let alias = aliases[key], makers[alias] != nil { return alias }218 return nil219 }220 /// Asset name of a logo (`Logos/<slug>` or `Logos/<slug>-color`), nil → monogram.221 static func asset(_ slug: String?, color: Bool = false) -> String? {222 guard let slug, let maker = makers[slug] else { return nil }223 return "Logos/" + (color && maker.color ? "\(slug)-color" : slug)224 }225}226227enum RoutingMode: String, Codable, CaseIterable, Sendable, Identifiable {228 case manual, auto, fast, quality, economy229 var id: String { rawValue }230}231232enum Effort: String, Codable, CaseIterable, Sendable, Identifiable {233 case low, medium, high, xhigh, max234 var id: String { rawValue }235}236237struct Preset: Identifiable, Hashable, Sendable, Codable {238 var id: String239 var name: String240 var description: String?241 var icon: String?242 var builtin: Bool243 var routingMode: String244 var modelId: String?245 var effort: String?246 var toolsEnabled: Bool?247 var toolNames: [String]?248 private enum K: String, CodingKey { case id, name, description, icon, builtin, routing_mode, model_id, effort, tools_enabled, tool_names }249 init(from decoder: Decoder) throws {250 let c = try decoder.container(keyedBy: K.self)251 id = try c.decode(String.self, forKey: .id); name = c.flexString(.name) ?? "Profil"; description = c.flexString(.description); icon = c.flexString(.icon)252 builtin = c.flexBool(.builtin) ?? false; routingMode = c.flexString(.routing_mode) ?? "manual"; modelId = c.flexString(.model_id); effort = c.flexString(.effort)253 toolsEnabled = c.flexBool(.tools_enabled); toolNames = try? c.decodeIfPresent([String].self, forKey: .tool_names)254 }255 func encode(to encoder: Encoder) throws {256 var c = encoder.container(keyedBy: K.self)257 try c.encode(id, forKey: .id); try c.encode(name, forKey: .name); try c.encodeIfPresent(description, forKey: .description); try c.encodeIfPresent(icon, forKey: .icon)258 try c.encode(builtin, forKey: .builtin); try c.encode(routingMode, forKey: .routing_mode); try c.encodeIfPresent(modelId, forKey: .model_id); try c.encodeIfPresent(effort, forKey: .effort)259 try c.encodeIfPresent(toolsEnabled, forKey: .tools_enabled); try c.encodeIfPresent(toolNames, forKey: .tool_names)260 }261}262263struct SavedPrompt: Identifiable, Hashable, Sendable, Codable {264 var id: String265 var title: String266 var body: String267 var tags: [String]268 var favorite: Bool269 var useCount: Int270 private enum K: String, CodingKey { case id, title, body, tags, favorite, use_count }271 init(from decoder: Decoder) throws {272 let c = try decoder.container(keyedBy: K.self)273 id = try c.decode(String.self, forKey: .id); title = c.flexString(.title) ?? ""; body = c.flexString(.body) ?? ""274 tags = (try? c.decodeIfPresent([String].self, forKey: .tags)) ?? []; favorite = c.flexBool(.favorite) ?? false; useCount = c.flexInt(.use_count) ?? 0275 }276 init(id: String, title: String, body: String, tags: [String] = [], favorite: Bool = false, useCount: Int = 0) {277 self.id = id; self.title = title; self.body = body; self.tags = tags; self.favorite = favorite; self.useCount = useCount278 }279 func encode(to encoder: Encoder) throws {280 var c = encoder.container(keyedBy: K.self)281 try c.encode(id, forKey: .id); try c.encode(title, forKey: .title); try c.encode(body, forKey: .body); try c.encode(tags, forKey: .tags)282 try c.encode(favorite, forKey: .favorite); try c.encode(useCount, forKey: .use_count)283 }284 /// Names of the `{{variables}}` of the prompt, in order of first appearance.285 var variables: [String] { PromptTemplate.variables(in: body) }286}287288struct Memory: Identifiable, Hashable, Sendable, Decodable {289 var id: String290 var category: String291 var content: String292 var source: String293 var status: String294 var sourceTitle: String?295 var updatedAt: Date296 private enum K: String, CodingKey { case id, category, content, source, status, source_title, updated_at }297 init(from decoder: Decoder) throws {298 let c = try decoder.container(keyedBy: K.self)299 id = try c.decode(String.self, forKey: .id); category = c.flexString(.category) ?? "context"; content = c.flexString(.content) ?? ""300 source = c.flexString(.source) ?? "auto"; status = c.flexString(.status) ?? "active"; sourceTitle = c.flexString(.source_title); updatedAt = c.flexDate(.updated_at) ?? Date()301 }302}303304struct Passkey: Identifiable, Hashable, Sendable, Decodable {305 var id: String306 var label: String?307 var createdAt: Date?308 var lastUsedAt: Date?309 var synced: Bool310 var current: Bool311 private enum K: String, CodingKey { case id, label, createdAt, lastUsedAt, synced, current }312 init(from decoder: Decoder) throws {313 let c = try decoder.container(keyedBy: K.self)314 id = try c.decode(String.self, forKey: .id); label = c.flexString(.label); createdAt = c.flexDate(.createdAt); lastUsedAt = c.flexDate(.lastUsedAt)315 synced = c.flexBool(.synced) ?? false; current = c.flexBool(.current) ?? false316 }317}318319struct DeviceSession: Identifiable, Hashable, Sendable, Decodable {320 var id: String321 var label: String?322 var createdAt: Date?323 var lastSeen: Date?324 var ip: String?325 var current: Bool326 private enum K: String, CodingKey { case id, label, createdAt, lastSeen, ip, current }327 init(from decoder: Decoder) throws {328 let c = try decoder.container(keyedBy: K.self)329 id = try c.decode(String.self, forKey: .id); label = c.flexString(.label); createdAt = c.flexDate(.createdAt); lastSeen = c.flexDate(.lastSeen)330 ip = c.flexString(.ip); current = c.flexBool(.current) ?? false331 }332}333334struct UsageReport: Sendable, Decodable {335 struct Totals: Sendable, Decodable {336 var requests: Int; var cost: Double; var inputTokens: Int; var outputTokens: Int; var avgLatency: Int?; var errors: Int337 private enum K: String, CodingKey { case requests, cost, input_tokens, output_tokens, avg_latency, errors }338 init(from decoder: Decoder) throws {339 let c = try decoder.container(keyedBy: K.self)340 requests = c.flexInt(.requests) ?? 0; cost = c.flexDouble(.cost) ?? 0; inputTokens = c.flexInt(.input_tokens) ?? 0; outputTokens = c.flexInt(.output_tokens) ?? 0341 avgLatency = c.flexInt(.avg_latency); errors = c.flexInt(.errors) ?? 0342 }343 }344 struct Day: Sendable, Decodable, Identifiable {345 var day: Date; var provider: String; var cost: Double; var requests: Int346 var id: String { "\(day.timeIntervalSince1970)-\(provider)" }347 private enum K: String, CodingKey { case day, provider, cost, requests }348 init(from decoder: Decoder) throws {349 let c = try decoder.container(keyedBy: K.self)350 day = c.flexDate(.day) ?? Date(); provider = c.flexString(.provider) ?? "—"; cost = c.flexDouble(.cost) ?? 0; requests = c.flexInt(.requests) ?? 0351 }352 }353 struct ByModel: Sendable, Decodable, Identifiable {354 var modelId: String; var provider: String; var requests: Int; var cost: Double355 var id: String { modelId }356 private enum K: String, CodingKey { case model_id, provider, requests, cost }357 init(from decoder: Decoder) throws {358 let c = try decoder.container(keyedBy: K.self)359 modelId = c.flexString(.model_id) ?? "—"; provider = c.flexString(.provider) ?? "—"; requests = c.flexInt(.requests) ?? 0; cost = c.flexDouble(.cost) ?? 0360 }361 }362 struct Spending: Sendable, Decodable {363 struct Limits: Sendable, Codable { var dailyLimitUsd: Double; var monthlyLimitUsd: Double; var alertAtPercent: Double }364 var today: Double; var month: Double; var limits: Limits365 }366 struct ByRoute: Sendable, Decodable, Identifiable {367 var route: String; var provider: String; var requests: Int; var cost: Double; var costExact: Double368 var id: String { "\(route)-\(provider)" }369 private enum K: String, CodingKey { case route, provider, requests, cost, cost_exact }370 init(from decoder: Decoder) throws {371 let c = try decoder.container(keyedBy: K.self)372 route = c.flexString(.route) ?? "direct"; provider = c.flexString(.provider) ?? "—"; requests = c.flexInt(.requests) ?? 0; cost = c.flexDouble(.cost) ?? 0; costExact = c.flexDouble(.cost_exact) ?? 0373 }374 }375 struct ByConversation: Sendable, Decodable, Identifiable {376 var conversationId: String; var title: String; var requests: Int; var cost: Double; var lastAt: Date?377 var id: String { conversationId }378 private enum K: String, CodingKey { case conversation_id, title, requests, cost, last_at }379 init(from decoder: Decoder) throws {380 let c = try decoder.container(keyedBy: K.self)381 conversationId = c.flexString(.conversation_id) ?? UUID().uuidString; title = c.flexString(.title) ?? Conversation.untitled382 requests = c.flexInt(.requests) ?? 0; cost = c.flexDouble(.cost) ?? 0; lastAt = c.flexDate(.last_at)383 }384 }385 /// How much of the period's cost was billed by the provider (exact) versus computed from tokens × list price.386 struct CostBasis: Sendable, Decodable {387 var exact: Double; var estimated: Double; var note: String?388 private enum K: String, CodingKey { case exact, estimated, note }389 init(from decoder: Decoder) throws {390 let c = try decoder.container(keyedBy: K.self)391 exact = c.flexDouble(.exact) ?? 0; estimated = c.flexDouble(.estimated) ?? 0; note = c.flexString(.note)392 }393 }394 var totals: Totals395 var daily: [Day]396 var byModel: [ByModel]397 var spending: Spending398 var byRoute: [ByRoute]?399 var byConversation: [ByConversation]?400 var costBasis: CostBasis?401}402403/// `{{variable}}` placeholders of saved prompts (same syntax as the web app).404enum PromptTemplate {405 static func variables(in body: String) -> [String] {406 var seen: [String] = []407 for m in body.matches(of: /\{\{\s*([^{}\n]{1,60}?)\s*\}\}/) { let name = String(m.1); if !seen.contains(name) { seen.append(name) } }408 return seen409 }410 /// Replaces every placeholder that has a value; unknown placeholders are left as written.411 static func fill(_ body: String, values: [String: String]) -> String {412 body.replacing(/\{\{\s*([^{}\n]{1,60}?)\s*\}\}/) { m in values[String(m.1)] ?? String(m.0) }413 }414}415