SPB Git

Repository Public MIT

AppModel.swift 13.6 KB 294 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/App/AppModel.swift10// Module           : App11// 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 Foundation89import Observation90import SwiftUI91import AstraCore92import AstraProviders93import AstraPersistence94import AstraLocal95import AstraDesign9697public enum AppTab: String, CaseIterable, Identifiable, Sendable {98    case chat, models, arena, agents, lab99    public var id: String { rawValue }100    public var title: String {101        switch self { case .chat: "Chat"; case .models: "Models"; case .arena: "Arena"; case .agents: "Agents"; case .lab: "Lab" }102    }103    public var symbol: String {104        switch self {105        case .chat: "bubble.left.and.text.bubble.right"106        case .models: "square.stack.3d.up"107        case .arena: "rectangle.split.2x1"108        case .agents: "point.3.connected.trianglepath.dotted"109        case .lab: "flask"110        }111    }112}113114/// Stores sanitized request facts for Lab. It never receives headers, keys, prompts or answers.115struct StoreDiagnosticsSink: DiagnosticsSink {116    let store: AstraStore117    func httpResponse(provider: ProviderKind, modelID: String, status: Int, requestID: String?, timeToHeaders: TimeInterval, retryCount: Int) async {118        try? await store.recordDiagnostic(RequestDiagnostic(provider: provider, modelID: modelID, httpStatus: status, requestID: requestID,119                                                            timeToHeaders: timeToHeaders, retryCount: retryCount))120    }121}122123/// Launch options. Everything except `reset` exists only in DEBUG builds, for screenshots and UI tests.124public struct LaunchOptions: Sendable {125    public var reset = false126    public var inMemory = false127    public var skipOnboarding = false128    public var tab: AppTab?129    public var autoSend: String?130    public var autoModel: String?131    public var appearance: ColorScheme?132    /// Keys injected from the process environment for automated runs. They go to an in-memory store, never to the Keychain.133    public var environmentKeys: [ProviderKind: String] = [:]134    public var screen: String?135136    public init() {}137138    public static func fromProcess() -> LaunchOptions {139        var o = LaunchOptions()140        #if DEBUG141        let d = UserDefaults.standard142        o.reset = d.bool(forKey: "ORIXReset")143        o.inMemory = d.bool(forKey: "ORIXInMemory")144        o.skipOnboarding = d.bool(forKey: "ORIXSkipOnboarding")145        o.tab = d.string(forKey: "ORIXTab").flatMap(AppTab.init(rawValue:))146        o.autoSend = d.string(forKey: "ORIXAutoSend")147        o.autoModel = d.string(forKey: "ORIXModel")148        o.screen = d.string(forKey: "ORIXScreen")149        switch d.string(forKey: "ORIXAppearance") { case "dark": o.appearance = .dark; case "light": o.appearance = .light; default: break }150        let env = ProcessInfo.processInfo.environment151        for (kind, name) in [(ProviderKind.openAI, "OPENAI_API_KEY"), (.anthropic, "ANTHROPIC_API_KEY"), (.google, "GEMINI_API_KEY"),152                             (.xAI, "XAI_API_KEY"), (.openRouter, "OPENROUTER_API_KEY")] {153            if let v = env[name], !v.isEmpty { o.environmentKeys[kind] = v }154        }155        #endif156        return o157    }158}159160/// The app's dependency container and top-level state. Created once at launch.161@MainActor @Observable public final class AppModel {162    public let store: AstraStore163    public let credentials: any CredentialStore164    public let transport: any HTTPTransport165    public let library: ModelLibrary166    public let local: LocalModels167    public let orchestrator: InferenceOrchestrator168    public let options: LaunchOptions169170    public var tab: AppTab = .chat171    public var toast: Toast?172    public var onboardingDone: Bool173    public var appearance: ColorScheme?174    public var isLocked = false175    public var appLockEnabled = false176    var uploadConsent: Set<String> = []177178    /// Conversations list, refreshed from the store.179    public private(set) var conversations: [ConversationRecord] = []180    public var activeChat: ChatController?181182    private init(store: AstraStore, credentials: any CredentialStore, transport: any HTTPTransport, local: LocalModels, options: LaunchOptions, onboardingDone: Bool) {183        self.store = store; self.credentials = credentials; self.transport = transport; self.local = local; self.options = options184        self.onboardingDone = onboardingDone185        let sink = StoreDiagnosticsSink(store: store)186        let engine = local.engine187        let resolve: @Sendable (ModelRef) async throws -> any ChatProvider = { ref in188            switch ref.provider {189            case .mlx: return MLXProvider(engine: engine)190            case .appleFoundation: return AppleFoundationProvider()191            default:192                let endpoints = (try? await store.endpoints()) ?? []193                return try makeProvider(for: ref, credentials: credentials, endpoints: endpoints, transport: transport, diagnostics: sink)194            }195        }196        orchestrator = InferenceOrchestrator(resolve: resolve)197        library = ModelLibrary(store: store, credentials: credentials, resolve: resolve)198        if let tab = options.tab { self.tab = tab }199        appearance = options.appearance200    }201202    /// Opens the database and the model store, recovers interrupted answers, loads cached state. No network.203    public static func bootstrap(options: LaunchOptions = .fromProcess()) async throws -> AppModel {204        let fm = FileManager.default205        let support = try fm.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("Astra", isDirectory: true)206        if options.reset { try? fm.removeItem(at: support) }207        try fm.createDirectory(at: support, withIntermediateDirectories: true)208209        let store: AstraStore = options.inMemory210            ? try AstraStore(inMemory: AstraStore.Options(), attachmentsDirectory: fm.temporaryDirectory.appendingPathComponent("astra-attachments-\(UUID().uuidString)"))211            : try await AstraStore.open(url: support.appendingPathComponent("astra.sqlite"), attachmentsDirectory: support.appendingPathComponent("Attachments", isDirectory: true))212        _ = try? await store.recoverInterruptedMessages()213214        let credentials: any CredentialStore215        if options.environmentKeys.isEmpty { credentials = KeychainCredentialStore() }216        else {217            // Automated runs only: keys handed in through the environment stay in memory for the life of the process.218            let memory = InMemoryCredentialStore()219            for (kind, key) in options.environmentKeys { try? memory.setSecret(key, for: CredentialAccount.provider(kind)) }220            credentials = memory221        }222        if options.reset, let keychain = credentials as? KeychainCredentialStore { try? keychain.removeAll() }223224        let transport = URLSessionTransport()225        let local = try LocalModels(transport: transport, settings: store)226        let done = options.skipOnboarding ? true : ((try? await store.setting("onboarding.done", default: false)) ?? false)227        let model = AppModel(store: store, credentials: credentials, transport: transport, local: local, options: options, onboardingDone: done)228        model.appLockEnabled = (try? await store.setting("privacy.appLock", default: false)) ?? false229        model.isLocked = model.appLockEnabled230        model.uploadConsent = Set((try? await store.setting("privacy.uploadConsent", default: [String]())) ?? [])231        if options.appearance == nil, let raw: String = try? await store.setting("appearance") { model.appearance = raw == "dark" ? .dark : raw == "light" ? .light : nil }232        await model.library.load()233        await local.start(library: model.library)234        await model.reloadConversations()235        // Refresh provider model lists in the background when a key exists and the cached list is missing or a day old.236        let library = model.library237        Task {238            for kind in ProviderKind.cloudKeyed {239                guard let state = library.providers[kind], state.hasKey else { continue }240                if state.models.isEmpty || (state.modelsFetchedAt.map { Date().timeIntervalSince($0) > 86_400 } ?? true) { await library.refresh(kind) }241            }242            for endpoint in library.endpoints where library.endpointModels[endpoint.id] == nil { await library.refreshEndpoint(endpoint.id) }243        }244        return model245    }246247    // MARK: Conversations248249    public func reloadConversations() async {250        conversations = (try? await store.conversations(.active)) ?? []251    }252253    public func finishOnboarding() async {254        onboardingDone = true255        try? await store.setSetting("onboarding.done", true)256    }257258    public func setAppearance(_ scheme: ColorScheme?) async {259        appearance = scheme260        try? await store.setSetting("appearance", scheme == .dark ? "dark" : scheme == .light ? "light" : "system")261    }262263    /// Opens a conversation in the chat tab.264    public func open(_ conversation: ConversationRecord) async {265        activeChat?.stop()266        let chat = ChatController(conversation: conversation, store: store, library: library, orchestrator: orchestrator) { [weak self] _ in267            Task { await self?.reloadConversations() }268        }269        await chat.reload()270        activeChat = chat271        tab = .chat272    }273274    /// Starts a new conversation with the given model (or the best default).275    @discardableResult public func newConversation(model: ModelRef? = nil, systemPrompt: String = "") async -> ChatController? {276        guard let ref = model ?? library.defaultModel() else { return nil }277        let defaults: GenerationParameters = (try? await store.setting("chat.defaultParameters", default: GenerationParameters())) ?? .default278        guard let record = try? await store.createConversation(model: ref, systemPrompt: systemPrompt, parameters: defaults) else { return nil }279        await reloadConversations()280        await open(record)281        return activeChat282    }283284    public func closeChat() { activeChat?.stop(); activeChat = nil }285286    public func delete(_ conversation: ConversationRecord) async {287        if activeChat?.conversation.id == conversation.id { closeChat() }288        _ = try? await store.deleteConversation(id: conversation.id)289        await reloadConversations()290    }291292    public func show(_ text: String, _ kind: Toast.Kind = .info) { toast = Toast(text, kind: kind) }293}294
Files main
Menu

Theme