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/Domain.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// MARK: - JSON9192/// A JSON value that is `Sendable`, `Codable` and `Hashable`; used for tool schemas, tool arguments and provider payloads.93public enum JSONValue: Sendable, Hashable, Codable, ExpressibleByStringLiteral, ExpressibleByDictionaryLiteral, ExpressibleByArrayLiteral,94 ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByNilLiteral {95 case null96 case bool(Bool)97 case number(Double)98 case string(String)99 case array([JSONValue])100 case object([String: JSONValue])101102 public init(stringLiteral value: String) { self = .string(value) }103 public init(dictionaryLiteral elements: (String, JSONValue)...) { self = .object(Dictionary(elements, uniquingKeysWith: { _, b in b })) }104 public init(arrayLiteral elements: JSONValue...) { self = .array(elements) }105 public init(booleanLiteral value: Bool) { self = .bool(value) }106 public init(integerLiteral value: Int) { self = .number(Double(value)) }107 public init(floatLiteral value: Double) { self = .number(value) }108 public init(nilLiteral: ()) { self = .null }109110 public init(from decoder: Decoder) throws {111 let c = try decoder.singleValueContainer()112 if c.decodeNil() { self = .null }113 else if let b = try? c.decode(Bool.self) { self = .bool(b) }114 else if let n = try? c.decode(Double.self) { self = .number(n) }115 else if let s = try? c.decode(String.self) { self = .string(s) }116 else if let a = try? c.decode([JSONValue].self) { self = .array(a) }117 else if let o = try? c.decode([String: JSONValue].self) { self = .object(o) }118 else { throw DecodingError.dataCorruptedError(in: c, debugDescription: "Unsupported JSON value") }119 }120121 public func encode(to encoder: Encoder) throws {122 var c = encoder.singleValueContainer()123 switch self {124 case .null: try c.encodeNil()125 case .bool(let b): try c.encode(b)126 case .number(let n):127 if n.rounded() == n, abs(n) < 9_007_199_254_740_992 { try c.encode(Int64(n)) } else { try c.encode(n) }128 case .string(let s): try c.encode(s)129 case .array(let a): try c.encode(a)130 case .object(let o): try c.encode(o)131 }132 }133134 public subscript(key: String) -> JSONValue? { if case .object(let o) = self { return o[key] }; return nil }135 public subscript(index: Int) -> JSONValue? { if case .array(let a) = self, a.indices.contains(index) { return a[index] }; return nil }136 public var stringValue: String? { if case .string(let s) = self { return s }; return nil }137 public var doubleValue: Double? {138 switch self { case .number(let n): return n; case .string(let s): return Double(s); default: return nil }139 }140 /// Nil for non-finite values and for magnitudes that do not fit in `Int` (never traps on model-supplied numbers).141 public var intValue: Int? { doubleValue.flatMap { $0.isFinite && abs($0) < 9.0e18 ? Int($0) : nil } }142 public var boolValue: Bool? { if case .bool(let b) = self { return b }; return nil }143 public var arrayValue: [JSONValue]? { if case .array(let a) = self { return a }; return nil }144 public var objectValue: [String: JSONValue]? { if case .object(let o) = self { return o }; return nil }145 public var isNull: Bool { self == .null }146147 /// Parses JSON text; returns nil when the text is not valid JSON.148 public static func parse(_ text: String) -> JSONValue? { parse(Data(text.utf8)) }149 public static func parse(_ data: Data) -> JSONValue? { try? JSONDecoder().decode(JSONValue.self, from: data) }150151 /// Serializes to JSON text with sorted keys (stable for hashing, diffing and tests).152 public func serialized(pretty: Bool = false) -> String {153 let e = JSONEncoder()154 e.outputFormatting = pretty ? [.sortedKeys, .prettyPrinted, .withoutEscapingSlashes] : [.sortedKeys, .withoutEscapingSlashes]155 return (try? e.encode(self)).flatMap { String(data: $0, encoding: .utf8) } ?? "null"156 }157 public var data: Data { Data(serialized().utf8) }158}159160// MARK: - Models161162/// Where a model runs. `custom` is a user-configured OpenAI-compatible endpoint.163public enum ProviderKind: String, Sendable, Codable, Hashable, CaseIterable, Identifiable {164 case openAI, anthropic, google, xAI, openRouter, custom, mlx, appleFoundation165 public var id: String { rawValue }166 public var isLocal: Bool { self == .mlx || self == .appleFoundation }167 /// Cloud providers that take a bring-your-own key, in the order the app lists them.168 public static let cloudKeyed: [ProviderKind] = [.openAI, .anthropic, .google, .xAI, .openRouter]169 public var displayName: String {170 switch self {171 case .openAI: "OpenAI"172 case .anthropic: "Anthropic"173 case .google: "Google Gemini"174 case .xAI: "xAI"175 case .openRouter: "OpenRouter"176 case .custom: "Custom endpoint"177 case .mlx: "On-device (MLX)"178 case .appleFoundation: "Apple Intelligence"179 }180 }181}182183/// Stable identity of a model: provider, optional custom endpoint profile, provider model id.184public struct ModelRef: Sendable, Codable, Hashable, Identifiable {185 public var provider: ProviderKind186 public var endpointID: String?187 public var modelID: String188 public init(provider: ProviderKind, modelID: String, endpointID: String? = nil) {189 self.provider = provider; self.modelID = modelID; self.endpointID = endpointID190 }191 public var id: String { [provider.rawValue, endpointID ?? "", modelID].joined(separator: "|") }192 public init?(id: String) {193 let parts = id.split(separator: "|", maxSplits: 2, omittingEmptySubsequences: false).map(String.init)194 guard parts.count == 3, let p = ProviderKind(rawValue: parts[0]), !parts[2].isEmpty else { return nil }195 self.init(provider: p, modelID: parts[2], endpointID: parts[1].isEmpty ? nil : parts[1])196 }197}198199public enum Capability: String, Sendable, Codable, Hashable, CaseIterable {200 case text, vision, tools, reasoning, structuredOutput, promptCaching, audioInput, documents201 public var label: String {202 switch self {203 case .text: "Text"204 case .vision: "Vision"205 case .tools: "Tools"206 case .reasoning: "Reasoning"207 case .structuredOutput: "Structured"208 case .promptCaching: "Caching"209 case .audioInput: "Audio"210 case .documents: "Files"211 }212 }213 public var symbol: String {214 switch self {215 case .text: "text.alignleft"216 case .vision: "eye"217 case .tools: "wrench.and.screwdriver"218 case .reasoning: "brain"219 case .structuredOutput: "curlybraces"220 case .promptCaching: "bolt.horizontal"221 case .audioInput: "waveform"222 case .documents: "doc"223 }224 }225}226227/// Where a capability or metadata claim comes from. The UI shows badges only for claims that have a source.228public enum MetadataSource: Sendable, Codable, Hashable {229 /// Returned by the provider's own API at `fetchedAt`.230 case providerAPI(fetchedAt: Date)231 /// Curated from the provider's documentation on the given day (ISO date) at the given URL.232 case documentation(asOf: String, url: String)233 /// Observed on this device at runtime (a loaded local model, the system model's availability).234 case runtime235 /// Entered by the user (custom endpoints).236 case user237 case unknown238239 public var label: String {240 switch self {241 case .providerAPI: "Provider API"242 case .documentation(let asOf, _): "Docs, \(asOf)"243 case .runtime: "Measured on device"244 case .user: "Set by you"245 case .unknown: "Unverified"246 }247 }248}249250/// Published price per million tokens, in US dollars, with its date. Always an estimate basis, never an invoice.251public struct Pricing: Sendable, Codable, Hashable {252 public var inputPerMTok: Double253 public var outputPerMTok: Double254 public var cachedInputPerMTok: Double?255 public var cacheWritePerMTok: Double?256 public var asOf: String257 public var sourceURL: String?258 public init(inputPerMTok: Double, outputPerMTok: Double, cachedInputPerMTok: Double? = nil, cacheWritePerMTok: Double? = nil,259 asOf: String, sourceURL: String? = nil) {260 self.inputPerMTok = inputPerMTok; self.outputPerMTok = outputPerMTok; self.cachedInputPerMTok = cachedInputPerMTok261 self.cacheWritePerMTok = cacheWritePerMTok; self.asOf = asOf; self.sourceURL = sourceURL262 }263 public var isFree: Bool { inputPerMTok == 0 && outputPerMTok == 0 }264}265266public struct ModelInfo: Sendable, Codable, Hashable, Identifiable {267 public var ref: ModelRef268 public var displayName: String269 public var summary: String?270 public var contextLength: Int?271 public var maxOutputTokens: Int?272 public var capabilities: Set<Capability>273 public var source: MetadataSource274 public var pricing: Pricing?275 /// Request parameters the provider says this model accepts (OpenRouter `supported_parameters`); nil = unknown.276 public var supportedParameters: Set<String>?277 /// Owner or upstream family as reported by the provider ("openai", "anthropic", "meta-llama"...).278 public var vendor: String?279 public var createdAt: Date?280 public var id: String { ref.id }281282 public init(ref: ModelRef, displayName: String, summary: String? = nil, contextLength: Int? = nil, maxOutputTokens: Int? = nil,283 capabilities: Set<Capability> = [.text], source: MetadataSource = .unknown, pricing: Pricing? = nil,284 supportedParameters: Set<String>? = nil, vendor: String? = nil, createdAt: Date? = nil) {285 self.ref = ref; self.displayName = displayName; self.summary = summary; self.contextLength = contextLength286 self.maxOutputTokens = maxOutputTokens; self.capabilities = capabilities; self.source = source; self.pricing = pricing287 self.supportedParameters = supportedParameters; self.vendor = vendor; self.createdAt = createdAt288 }289}290291// MARK: - Prompt292293public struct ImageInput: Sendable, Hashable, Codable {294 public var data: Data295 public var mimeType: String296 public init(data: Data, mimeType: String = "image/jpeg") { self.data = data; self.mimeType = mimeType }297}298299public struct ToolCall: Sendable, Hashable, Codable, Identifiable {300 public var id: String301 public var name: String302 public var arguments: JSONValue303 public init(id: String, name: String, arguments: JSONValue) { self.id = id; self.name = name; self.arguments = arguments }304}305306public struct ToolDefinition: Sendable, Hashable, Codable, Identifiable {307 public var name: String308 public var summary: String309 /// JSON Schema object describing the arguments.310 public var parameters: JSONValue311 public var id: String { name }312 public init(name: String, summary: String, parameters: JSONValue) { self.name = name; self.summary = summary; self.parameters = parameters }313}314315/// One turn handed to a provider. Branch resolution, context budgeting and retrieval happen before this point.316public struct PromptMessage: Sendable, Hashable, Codable {317 public enum Role: String, Sendable, Codable { case user, assistant, tool }318 public var role: Role319 public var text: String320 public var images: [ImageInput]321 /// Assistant turns that called tools.322 public var toolCalls: [ToolCall]323 /// Tool turns: the call being answered.324 public var toolCallID: String?325 public var toolName: String?326 public var toolIsError: Bool327328 public init(role: Role, text: String, images: [ImageInput] = [], toolCalls: [ToolCall] = [], toolCallID: String? = nil,329 toolName: String? = nil, toolIsError: Bool = false) {330 self.role = role; self.text = text; self.images = images; self.toolCalls = toolCalls331 self.toolCallID = toolCallID; self.toolName = toolName; self.toolIsError = toolIsError332 }333 public static func user(_ text: String, images: [ImageInput] = []) -> Self { .init(role: .user, text: text, images: images) }334 public static func assistant(_ text: String, toolCalls: [ToolCall] = []) -> Self { .init(role: .assistant, text: text, toolCalls: toolCalls) }335 public static func tool(_ text: String, callID: String, name: String, isError: Bool = false) -> Self {336 .init(role: .tool, text: text, toolCallID: callID, toolName: name, toolIsError: isError)337 }338}339340public enum ReasoningEffort: String, Sendable, Codable, Hashable, CaseIterable, Identifiable {341 case off, low, medium, high342 public var id: String { rawValue }343 public var title: String { rawValue.capitalized }344}345346/// Generation parameters. A nil field means "provider default"; adapters drop fields the selected model does not accept.347public struct GenerationParameters: Sendable, Codable, Hashable {348 public var temperature: Double?349 public var topP: Double?350 public var maxOutputTokens: Int?351 public var reasoning: ReasoningEffort?352 public var seed: Int?353 public var stop: [String]354 /// Local models only: tokens kept in the window.355 public var contextLength: Int?356 public init(temperature: Double? = nil, topP: Double? = nil, maxOutputTokens: Int? = nil, reasoning: ReasoningEffort? = nil,357 seed: Int? = nil, stop: [String] = [], contextLength: Int? = nil) {358 self.temperature = temperature; self.topP = topP; self.maxOutputTokens = maxOutputTokens; self.reasoning = reasoning359 self.seed = seed; self.stop = stop; self.contextLength = contextLength360 }361 public static let `default` = GenerationParameters()362}363364/// OpenRouter routing preferences; ignored by every other provider.365public struct RoutingPreferences: Sendable, Codable, Hashable {366 public var providerOrder: [String]367 public var allowFallbacks: Bool368 /// When true, only upstream providers that do not retain or train on prompts are used (`data_collection: "deny"`).369 public var denyDataCollection: Bool370 public var fallbackModels: [String]371 public init(providerOrder: [String] = [], allowFallbacks: Bool = true, denyDataCollection: Bool = false, fallbackModels: [String] = []) {372 self.providerOrder = providerOrder; self.allowFallbacks = allowFallbacks373 self.denyDataCollection = denyDataCollection; self.fallbackModels = fallbackModels374 }375 public var isDefault: Bool { self == RoutingPreferences() }376}377378public struct GenerationRequest: Sendable, Hashable {379 public var model: ModelRef380 public var system: String?381 public var messages: [PromptMessage]382 public var parameters: GenerationParameters383 public var tools: [ToolDefinition]384 public var routing: RoutingPreferences?385 /// Lets a local runtime reuse its KV cache across turns of one conversation.386 public var sessionKey: String?387 public init(model: ModelRef, system: String? = nil, messages: [PromptMessage], parameters: GenerationParameters = .default,388 tools: [ToolDefinition] = [], routing: RoutingPreferences? = nil, sessionKey: String? = nil) {389 self.model = model; self.system = system; self.messages = messages; self.parameters = parameters390 self.tools = tools; self.routing = routing; self.sessionKey = sessionKey391 }392}393394// MARK: - Stream events395396public enum StopReason: String, Sendable, Codable, Hashable {397 case endOfTurn, maxTokens, toolCalls, stopSequence, contentFilter, cancelled, error, unknown398 public var label: String {399 switch self {400 case .endOfTurn: "Complete"401 case .maxTokens: "Reached the output limit"402 case .toolCalls: "Called tools"403 case .stopSequence: "Stop sequence"404 case .contentFilter: "Stopped by the provider's filter"405 case .cancelled: "Stopped"406 case .error: "Failed"407 case .unknown: "Ended"408 }409 }410}411412/// Token counts as reported by the provider or measured by the local runtime. A nil field was not reported.413public struct TokenUsage: Sendable, Codable, Hashable {414 public var inputTokens: Int?415 public var outputTokens: Int?416 public var cachedInputTokens: Int?417 public var cacheWriteTokens: Int?418 public var reasoningTokens: Int?419 /// Cost reported by the provider itself (OpenRouter), in US dollars.420 public var reportedCostUSD: Double?421 public init(inputTokens: Int? = nil, outputTokens: Int? = nil, cachedInputTokens: Int? = nil, cacheWriteTokens: Int? = nil,422 reasoningTokens: Int? = nil, reportedCostUSD: Double? = nil) {423 self.inputTokens = inputTokens; self.outputTokens = outputTokens; self.cachedInputTokens = cachedInputTokens424 self.cacheWriteTokens = cacheWriteTokens; self.reasoningTokens = reasoningTokens; self.reportedCostUSD = reportedCostUSD425 }426 public var totalTokens: Int? {427 guard inputTokens != nil || outputTokens != nil else { return nil }428 return (inputTokens ?? 0) + (outputTokens ?? 0)429 }430 /// Later reports override earlier ones field by field (providers send partial usage at start and totals at the end).431 public func merged(with other: TokenUsage) -> TokenUsage {432 TokenUsage(inputTokens: other.inputTokens ?? inputTokens, outputTokens: other.outputTokens ?? outputTokens,433 cachedInputTokens: other.cachedInputTokens ?? cachedInputTokens, cacheWriteTokens: other.cacheWriteTokens ?? cacheWriteTokens,434 reasoningTokens: other.reasoningTokens ?? reasoningTokens, reportedCostUSD: other.reportedCostUSD ?? reportedCostUSD)435 }436}437438/// Identity of the answer as the provider reports it: this is what the UI shows, never the id that was merely requested.439public struct MessageStart: Sendable, Codable, Hashable {440 public var responseID: String?441 public var reportedModel: String?442 /// Upstream provider that actually served the request (OpenRouter).443 public var servedBy: String?444 public init(responseID: String? = nil, reportedModel: String? = nil, servedBy: String? = nil) {445 self.responseID = responseID; self.reportedModel = reportedModel; self.servedBy = servedBy446 }447}448449/// Typed events every adapter (cloud or local) emits. Transport formats never leave the adapters.450public enum StreamEvent: Sendable, Hashable {451 case messageStarted(MessageStart)452 case textDelta(String)453 /// Only a summary the provider legitimately exposes, or a local model's own visible thinking block. Never reconstructed.454 case reasoningSummaryDelta(String)455 case toolCallStarted(id: String, name: String)456 case toolCallDelta(id: String, argumentsFragment: String)457 case toolCallCompleted(ToolCall)458 case usage(TokenUsage)459 case messageCompleted(StopReason)460 case error(AstraError)461462 public var isTerminal: Bool {463 switch self { case .messageCompleted, .error: true; default: false }464 }465}466