SPB Git

Repository Public

Domain.swift 23.8 KB 498 lines swift

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            // JSON has no NaN or infinity: one such value must not make the whole document unencodable.128            guard n.isFinite else { try c.encodeNil(); return }129            if n.rounded() == n, abs(n) < 9_007_199_254_740_992 { try c.encode(Int64(n)) } else { try c.encode(n) }130        case .string(let s): try c.encode(s)131        case .array(let a): try c.encode(a)132        case .object(let o): try c.encode(o)133        }134    }135136    public subscript(key: String) -> JSONValue? { if case .object(let o) = self { return o[key] }; return nil }137    public subscript(index: Int) -> JSONValue? { if case .array(let a) = self, a.indices.contains(index) { return a[index] }; return nil }138    public var stringValue: String? { if case .string(let s) = self { return s }; return nil }139    public var doubleValue: Double? {140        switch self { case .number(let n): return n; case .string(let s): return Double(s); default: return nil }141    }142    /// Nil for non-finite values and for magnitudes that do not fit in `Int` (never traps on model-supplied numbers).143    public var intValue: Int? { doubleValue.flatMap { $0.isFinite && abs($0) < 9.0e18 ? Int($0) : nil } }144    public var boolValue: Bool? { if case .bool(let b) = self { return b }; return nil }145    public var arrayValue: [JSONValue]? { if case .array(let a) = self { return a }; return nil }146    public var objectValue: [String: JSONValue]? { if case .object(let o) = self { return o }; return nil }147    public var isNull: Bool { self == .null }148149    /// Parses JSON text; returns nil when the text is not valid JSON.150    public static func parse(_ text: String) -> JSONValue? { parse(Data(text.utf8)) }151    public static func parse(_ data: Data) -> JSONValue? { try? JSONDecoder().decode(JSONValue.self, from: data) }152153    /// Serializes to JSON text with sorted keys (stable for hashing, diffing and tests).154    public func serialized(pretty: Bool = false) -> String {155        let e = JSONEncoder()156        e.outputFormatting = pretty ? [.sortedKeys, .prettyPrinted, .withoutEscapingSlashes] : [.sortedKeys, .withoutEscapingSlashes]157        return (try? e.encode(self)).flatMap { String(data: $0, encoding: .utf8) } ?? "null"158    }159    public var data: Data { Data(serialized().utf8) }160}161162// MARK: - Models163164/// Where a model runs. `custom` is a user-configured OpenAI-compatible endpoint.165public enum ProviderKind: String, Sendable, Codable, Hashable, CaseIterable, Identifiable {166    case openAI, anthropic, google, xAI, mistral, deepSeek, moonshot, cerebras, deepInfra, openRouter, custom, mlx, appleFoundation167    public var id: String { rawValue }168    public var isLocal: Bool { self == .mlx || self == .appleFoundation }169    /// Cloud providers that take a bring-your-own key, in the order the app lists them.170    public static let cloudKeyed: [ProviderKind] = [.openAI, .anthropic, .google, .xAI, .mistral, .deepSeek, .moonshot, .cerebras, .deepInfra, .openRouter]171    public var displayName: String {172        switch self {173        case .openAI: "OpenAI"174        case .anthropic: "Anthropic"175        case .google: "Google Gemini"176        case .xAI: "xAI"177        case .mistral: "Mistral"178        case .deepSeek: "DeepSeek"179        case .moonshot: "Kimi (Moonshot AI)"180        case .cerebras: "Cerebras"181        case .deepInfra: "DeepInfra"182        case .openRouter: "OpenRouter"183        case .custom: "Custom endpoint"184        case .mlx: "On-device (MLX)"185        case .appleFoundation: "Apple Intelligence"186        }187    }188}189190/// Stable identity of a model: provider, optional custom endpoint profile, provider model id.191public struct ModelRef: Sendable, Codable, Hashable, Identifiable {192    public var provider: ProviderKind193    public var endpointID: String?194    public var modelID: String195    public init(provider: ProviderKind, modelID: String, endpointID: String? = nil) {196        self.provider = provider; self.modelID = modelID; self.endpointID = endpointID197    }198    public var id: String { [provider.rawValue, endpointID ?? "", modelID].joined(separator: "|") }199    public init?(id: String) {200        let parts = id.split(separator: "|", maxSplits: 2, omittingEmptySubsequences: false).map(String.init)201        guard parts.count == 3, let p = ProviderKind(rawValue: parts[0]), !parts[2].isEmpty else { return nil }202        self.init(provider: p, modelID: parts[2], endpointID: parts[1].isEmpty ? nil : parts[1])203    }204}205206public enum Capability: String, Sendable, Codable, Hashable, CaseIterable {207    case text, vision, tools, reasoning, structuredOutput, promptCaching, audioInput, documents208    public var label: String {209        switch self {210        case .text: "Text"211        case .vision: "Vision"212        case .tools: "Tools"213        case .reasoning: "Reasoning"214        case .structuredOutput: "Structured"215        case .promptCaching: "Caching"216        case .audioInput: "Audio"217        case .documents: "Files"218        }219    }220    public var symbol: String {221        switch self {222        case .text: "text.alignleft"223        case .vision: "eye"224        case .tools: "wrench.and.screwdriver"225        case .reasoning: "brain"226        case .structuredOutput: "curlybraces"227        case .promptCaching: "bolt.horizontal"228        case .audioInput: "waveform"229        case .documents: "doc"230        }231    }232}233234/// Where a capability or metadata claim comes from. The UI shows badges only for claims that have a source.235public enum MetadataSource: Sendable, Codable, Hashable {236    /// Returned by the provider's own API at `fetchedAt`.237    case providerAPI(fetchedAt: Date)238    /// Curated from the provider's documentation on the given day (ISO date) at the given URL.239    case documentation(asOf: String, url: String)240    /// Observed on this device at runtime (a loaded local model, the system model's availability).241    case runtime242    /// Entered by the user (custom endpoints).243    case user244    case unknown245246    public var label: String {247        switch self {248        case .providerAPI: "Provider API"249        case .documentation(let asOf, _): "Docs, \(asOf)"250        case .runtime: "Measured on device"251        case .user: "Set by you"252        case .unknown: "Unverified"253        }254    }255}256257/// Published price per million tokens, in US dollars, with its date. Always an estimate basis, never an invoice.258public struct Pricing: Sendable, Codable, Hashable {259    public var inputPerMTok: Double260    public var outputPerMTok: Double261    public var cachedInputPerMTok: Double?262    public var cacheWritePerMTok: Double?263    public var asOf: String264    public var sourceURL: String?265    public init(inputPerMTok: Double, outputPerMTok: Double, cachedInputPerMTok: Double? = nil, cacheWritePerMTok: Double? = nil,266                asOf: String, sourceURL: String? = nil) {267        self.inputPerMTok = inputPerMTok; self.outputPerMTok = outputPerMTok; self.cachedInputPerMTok = cachedInputPerMTok268        self.cacheWritePerMTok = cacheWritePerMTok; self.asOf = asOf; self.sourceURL = sourceURL269    }270    public var isFree: Bool { inputPerMTok == 0 && outputPerMTok == 0 }271}272273public struct ModelInfo: Sendable, Codable, Hashable, Identifiable {274    public var ref: ModelRef275    public var displayName: String276    public var summary: String?277    public var contextLength: Int?278    public var maxOutputTokens: Int?279    public var capabilities: Set<Capability>280    public var source: MetadataSource281    public var pricing: Pricing?282    /// Request parameters the provider says this model accepts (OpenRouter `supported_parameters`); nil = unknown.283    public var supportedParameters: Set<String>?284    /// Owner or upstream family as reported by the provider ("openai", "anthropic", "meta-llama"...).285    public var vendor: String?286    public var createdAt: Date?287    public var id: String { ref.id }288289    public init(ref: ModelRef, displayName: String, summary: String? = nil, contextLength: Int? = nil, maxOutputTokens: Int? = nil,290                capabilities: Set<Capability> = [.text], source: MetadataSource = .unknown, pricing: Pricing? = nil,291                supportedParameters: Set<String>? = nil, vendor: String? = nil, createdAt: Date? = nil) {292        self.ref = ref; self.displayName = displayName; self.summary = summary; self.contextLength = contextLength293        self.maxOutputTokens = maxOutputTokens; self.capabilities = capabilities; self.source = source; self.pricing = pricing294        self.supportedParameters = supportedParameters; self.vendor = vendor; self.createdAt = createdAt295    }296}297298// MARK: - Prompt299300public struct ImageInput: Sendable, Hashable, Codable {301    public var data: Data302    public var mimeType: String303    public init(data: Data, mimeType: String = "image/jpeg") { self.data = data; self.mimeType = mimeType }304}305306public struct ToolCall: Sendable, Hashable, Codable, Identifiable {307    public var id: String308    public var name: String309    public var arguments: JSONValue310    /// Opaque state the provider needs to see again when this call is sent back in the history of a tool cycle311    /// (a thought signature, a thinking block, encrypted reasoning). Only the adapter that produced it reads it; it is312    /// stored with the conversation or the agent checkpoint so that a cycle survives a restart. It is never shown.313    public var providerState: JSONValue?314    public init(id: String, name: String, arguments: JSONValue, providerState: JSONValue? = nil) {315        self.id = id; self.name = name; self.arguments = arguments; self.providerState = providerState316    }317}318319public struct ToolDefinition: Sendable, Hashable, Codable, Identifiable {320    public var name: String321    public var summary: String322    /// JSON Schema object describing the arguments.323    public var parameters: JSONValue324    public var id: String { name }325    public init(name: String, summary: String, parameters: JSONValue) { self.name = name; self.summary = summary; self.parameters = parameters }326}327328/// One turn handed to a provider. Branch resolution, context budgeting and retrieval happen before this point.329public struct PromptMessage: Sendable, Hashable, Codable {330    public enum Role: String, Sendable, Codable { case user, assistant, tool }331    public var role: Role332    public var text: String333    public var images: [ImageInput]334    /// Assistant turns that called tools.335    public var toolCalls: [ToolCall]336    /// Tool turns: the call being answered.337    public var toolCallID: String?338    public var toolName: String?339    public var toolIsError: Bool340341    public init(role: Role, text: String, images: [ImageInput] = [], toolCalls: [ToolCall] = [], toolCallID: String? = nil,342                toolName: String? = nil, toolIsError: Bool = false) {343        self.role = role; self.text = text; self.images = images; self.toolCalls = toolCalls344        self.toolCallID = toolCallID; self.toolName = toolName; self.toolIsError = toolIsError345    }346    public static func user(_ text: String, images: [ImageInput] = []) -> Self { .init(role: .user, text: text, images: images) }347    public static func assistant(_ text: String, toolCalls: [ToolCall] = []) -> Self { .init(role: .assistant, text: text, toolCalls: toolCalls) }348    public static func tool(_ text: String, callID: String, name: String, isError: Bool = false) -> Self {349        .init(role: .tool, text: text, toolCallID: callID, toolName: name, toolIsError: isError)350    }351}352353public enum ReasoningEffort: String, Sendable, Codable, Hashable, CaseIterable, Identifiable {354    case off, low, medium, high355    public var id: String { rawValue }356    public var title: String { rawValue.capitalized }357}358359/// Generation parameters. A nil field means "provider default"; adapters drop fields the selected model does not accept.360public struct GenerationParameters: Sendable, Codable, Hashable {361    public var temperature: Double?362    public var topP: Double?363    public var maxOutputTokens: Int?364    public var reasoning: ReasoningEffort?365    public var seed: Int?366    public var stop: [String]367    /// Local models only: tokens kept in the window.368    public var contextLength: Int?369    public init(temperature: Double? = nil, topP: Double? = nil, maxOutputTokens: Int? = nil, reasoning: ReasoningEffort? = nil,370                seed: Int? = nil, stop: [String] = [], contextLength: Int? = nil) {371        self.temperature = temperature; self.topP = topP; self.maxOutputTokens = maxOutputTokens; self.reasoning = reasoning372        self.seed = seed; self.stop = stop; self.contextLength = contextLength373    }374    public static let `default` = GenerationParameters()375}376377/// OpenRouter routing preferences; ignored by every other provider.378public struct RoutingPreferences: Sendable, Codable, Hashable {379    public var providerOrder: [String]380    public var allowFallbacks: Bool381    /// When true, only upstream providers that do not retain or train on prompts are used (`data_collection: "deny"`).382    public var denyDataCollection: Bool383    public var fallbackModels: [String]384    public init(providerOrder: [String] = [], allowFallbacks: Bool = true, denyDataCollection: Bool = false, fallbackModels: [String] = []) {385        self.providerOrder = providerOrder; self.allowFallbacks = allowFallbacks386        self.denyDataCollection = denyDataCollection; self.fallbackModels = fallbackModels387    }388    public var isDefault: Bool { self == RoutingPreferences() }389}390391public struct GenerationRequest: Sendable, Hashable {392    public var model: ModelRef393    public var system: String?394    public var messages: [PromptMessage]395    public var parameters: GenerationParameters396    public var tools: [ToolDefinition]397    public var routing: RoutingPreferences?398    /// Lets a local runtime reuse its KV cache across turns of one conversation.399    public var sessionKey: String?400    public init(model: ModelRef, system: String? = nil, messages: [PromptMessage], parameters: GenerationParameters = .default,401                tools: [ToolDefinition] = [], routing: RoutingPreferences? = nil, sessionKey: String? = nil) {402        self.model = model; self.system = system; self.messages = messages; self.parameters = parameters403        self.tools = tools; self.routing = routing; self.sessionKey = sessionKey404    }405}406407// MARK: - Stream events408409public enum StopReason: String, Sendable, Codable, Hashable {410    case endOfTurn, maxTokens, toolCalls, stopSequence, contentFilter, cancelled, error, unknown411    public var label: String {412        switch self {413        case .endOfTurn: "Complete"414        case .maxTokens: "Reached the output limit"415        case .toolCalls: "Called tools"416        case .stopSequence: "Stop sequence"417        case .contentFilter: "Stopped by the provider's filter"418        case .cancelled: "Stopped"419        case .error: "Failed"420        case .unknown: "Ended"421        }422    }423}424425/// Token counts as reported by the provider or measured by the local runtime. A nil field was not reported.426public struct TokenUsage: Sendable, Codable, Hashable {427    public var inputTokens: Int?428    public var outputTokens: Int?429    public var cachedInputTokens: Int?430    public var cacheWriteTokens: Int?431    public var reasoningTokens: Int?432    /// Cost reported by the provider itself (OpenRouter), in US dollars.433    public var reportedCostUSD: Double?434    public init(inputTokens: Int? = nil, outputTokens: Int? = nil, cachedInputTokens: Int? = nil, cacheWriteTokens: Int? = nil,435                reasoningTokens: Int? = nil, reportedCostUSD: Double? = nil) {436        self.inputTokens = Self.sane(inputTokens); self.outputTokens = Self.sane(outputTokens); self.cachedInputTokens = Self.sane(cachedInputTokens)437        self.cacheWriteTokens = Self.sane(cacheWriteTokens); self.reasoningTokens = Self.sane(reasoningTokens)438        self.reportedCostUSD = reportedCostUSD.flatMap { $0.isFinite && $0 >= 0 ? $0 : nil }439    }440441    /// Largest count accepted from a server. Far above any real request, far below anything that could overflow a sum.442    public static let maxCount = 1_000_000_000_000443444    /// A count as reported by a server: negative values are discarded as "not reported", absurd ones are capped.445    public static func sane(_ count: Int?) -> Int? {446        guard let count, count >= 0 else { return nil }447        return min(count, maxCount)448    }449450    /// Adds counts from a server without ever overflowing. Nil when none was reported.451    public static func sum(_ parts: Int?...) -> Int? {452        let present = parts.compactMap(sane)453        guard !present.isEmpty else { return nil }454        return min(maxCount, present.reduce(0) { $0 + $1 })   // at most a few terms of 1e12 each455    }456    public var totalTokens: Int? {457        guard inputTokens != nil || outputTokens != nil else { return nil }458        // Counts come from a server: the sum saturates instead of trapping on absurd values.459        let (sum, overflow) = max(0, inputTokens ?? 0).addingReportingOverflow(max(0, outputTokens ?? 0))460        return overflow ? Int.max : sum461    }462    /// Later reports override earlier ones field by field (providers send partial usage at start and totals at the end).463    public func merged(with other: TokenUsage) -> TokenUsage {464        TokenUsage(inputTokens: other.inputTokens ?? inputTokens, outputTokens: other.outputTokens ?? outputTokens,465                   cachedInputTokens: other.cachedInputTokens ?? cachedInputTokens, cacheWriteTokens: other.cacheWriteTokens ?? cacheWriteTokens,466                   reasoningTokens: other.reasoningTokens ?? reasoningTokens, reportedCostUSD: other.reportedCostUSD ?? reportedCostUSD)467    }468}469470/// Identity of the answer as the provider reports it: this is what the UI shows, never the id that was merely requested.471public struct MessageStart: Sendable, Codable, Hashable {472    public var responseID: String?473    public var reportedModel: String?474    /// Upstream provider that actually served the request (OpenRouter).475    public var servedBy: String?476    public init(responseID: String? = nil, reportedModel: String? = nil, servedBy: String? = nil) {477        self.responseID = responseID; self.reportedModel = reportedModel; self.servedBy = servedBy478    }479}480481/// Typed events every adapter (cloud or local) emits. Transport formats never leave the adapters.482public enum StreamEvent: Sendable, Hashable {483    case messageStarted(MessageStart)484    case textDelta(String)485    /// Only a summary the provider legitimately exposes, or a local model's own visible thinking block. Never reconstructed.486    case reasoningSummaryDelta(String)487    case toolCallStarted(id: String, name: String)488    case toolCallDelta(id: String, argumentsFragment: String)489    case toolCallCompleted(ToolCall)490    case usage(TokenUsage)491    case messageCompleted(StopReason)492    case error(AstraError)493494    public var isTerminal: Bool {495        switch self { case .messageCompleted, .error: true; default: false }496    }497}498
Files main
Menu

Theme