Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Sources/DocAI/ProviderHub.swift10// Description : The one door the app (and the local HTTP API) uses to11// reach language models. Lists providers with their status,12// manages API keys and custom OpenAI-compatible endpoints,13// tests connections, serves the model catalogue with14// capabilities, streams generations as ORIX Astra15// `StreamEvent`s and accounts usage and cost. Wire formats,16// retries and stream validation are ORIX Astra's17// (`ProviderRegistry`, `InferenceOrchestrator`); nothing of18// them is reimplemented here.19// Module : DocAI20// Repository : https://git.spboucher.ai/orix-docs21// Created : 2026-11-2222// Last Modified : 2026-11-2223//24// =============================================================================25// AUTHOR & PROFESSIONAL AFFILIATION26// =============================================================================27//28// Author : Simon-Pierre Boucher29// Position : Professor of Finance30// Institution : Université du Québec en Outaouais (UQO)31// Department : Département des sciences administratives32// Organization : SP Boucher33//34// Website : https://spboucher.ai35// Git : https://git.spboucher.ai36//37// =============================================================================38// OFFICIAL CONTACT DIRECTORY39// =============================================================================40//41// General : info@spboucher.ai42// Professional : contact@spboucher.ai43// Direct : simon@spboucher.ai44// Research : research@spboucher.ai45// Development : dev@spboucher.ai46// Support : support@spboucher.ai47// Security/Admin : admin@spboucher.ai48// Notifications : notifications@spboucher.ai49//50// Preferred Contact: support@spboucher.ai51//52// =============================================================================53// COPYRIGHT & INTELLECTUAL PROPERTY54// =============================================================================55//56// Copyright (c) 202657// Simon-Pierre Boucher58//59// All rights reserved where applicable.60//61// This file is governed by the applicable project license,62// copyright notices, institutional agreements and relevant law.63//64// Unless expressly authorized by the applicable license or65// rights holder, copying, redistribution, sublicensing,66// publication and commercial exploitation are not permitted.67//68// Existing third-party rights and notices remain unaffected.69//70// =============================================================================71// CONFIDENTIALITY & SECURITY72// =============================================================================73//74// Classification : Public75// Distribution : Public repository; use is governed by the project license76// Security Contact : admin@spboucher.ai77//78// Access to this source does not independently grant permission79// to redistribute or disclose confidential materials.80//81// Do not embed credentials, private keys, access tokens,82// certificates or confidential personal information.83//84// =============================================================================85// LICENSE & MAINTENANCE86// =============================================================================87//88// License : None specified (no license file in this repository)89// Maintainer : Simon-Pierre Boucher90// Technical Contact: dev@spboucher.ai91//92// =============================================================================93// END OF SP BOUCHER SOURCE HEADER94// =============================================================================9596import AstraCore97import AstraProviders98import Foundation99100// MARK: - Identity and status101102/// Identity of a provider as the hub lists it: a kind, plus the profile id for a custom endpoint.103public struct ProviderID: Sendable, Hashable, Codable, Identifiable, CustomStringConvertible {104 public var kind: ProviderKind105 public var endpointID: String?106 public init(kind: ProviderKind, endpointID: String? = nil) { self.kind = kind; self.endpointID = kind == .custom ? endpointID : nil }107 public init(_ kind: ProviderKind) { self.init(kind: kind) }108 public init(model: ModelRef) { self.init(kind: model.provider, endpointID: model.endpointID) }109 /// "openAI", "custom:<profile id>": stable, usable as a dictionary key and in URLs of the local API.110 public var rawValue: String { endpointID.map { "\(kind.rawValue):\($0)" } ?? kind.rawValue }111 public init?(rawValue: String) {112 let parts = rawValue.split(separator: ":", maxSplits: 1).map(String.init)113 guard let first = parts.first, let kind = ProviderKind(rawValue: first) else { return nil }114 if kind == .custom { guard parts.count == 2, !parts[1].isEmpty else { return nil }; self.init(kind: kind, endpointID: parts[1]) }115 else { guard parts.count == 1 else { return nil }; self.init(kind: kind) }116 }117 public var id: String { rawValue }118 public var description: String { rawValue }119 /// Account of this provider's key in the credential store (ORIX Astra's naming).120 public var credentialAccount: String? {121 if kind.isLocal { return nil }122 if kind == .custom { return endpointID.map(CredentialAccount.endpoint) }123 return CredentialAccount.provider(kind)124 }125}126127public enum ProviderState: String, Sendable, Hashable, Codable, CaseIterable {128 /// A cloud provider without a key.129 case notConfigured130 /// A key is stored; the connection has not been tested since it was set.131 case configured132 /// The last connection test succeeded.133 case verified134 /// The last connection test failed (rejected key, network, provider error). `detail` says why.135 case error136 /// An on-device provider that cannot be used on this Mac right now. `detail` says why.137 case unavailable138}139140/// One row of the provider list. Never contains a key: `keyHint` is a masked form ("sk-••••••••abcd").141public struct ProviderSummary: Sendable, Hashable, Identifiable {142 public var id: ProviderID143 public var displayName: String144 /// True for providers that run on this Mac (MLX, Apple Intelligence): no key, no network.145 public var isOnDevice: Bool146 public var hasKey: Bool147 public var keyHint: String?148 public var state: ProviderState149 /// Sentence for the UI: result of the last test, or why the provider is unavailable.150 public var detail: String?151 /// Short title of the failure ("Key rejected", "Network problem") when `state == .error`.152 public var errorTitle: String?153 public var lastCheckedAt: Date?154 /// Models known for this provider (from the last catalogue fetch or connection test).155 public var modelCount: Int?156 /// Remaining credit in US dollars when the provider reports it (OpenRouter).157 public var remainingCreditUSD: Double?158 /// Custom endpoints only.159 public var baseURL: String?160}161162/// What ORIX Docs needs to know about a model to offer it for a task. Derived from ORIX Astra's `ModelInfo`: a `nil` or `false`163/// means "not claimed by the provider's API or documentation", never "tested and absent".164public struct ModelCapabilities: Sendable, Hashable, Codable {165 public var contextLength: Int?166 public var maxOutputTokens: Int?167 public var toolCalling: Bool168 public var structuredOutput: Bool169 public var vision: Bool170 public var reasoning: Bool171 public var promptCaching: Bool172 public var pricing: Pricing?173 /// Where the claims come from ("Provider API", "Docs, 2026-11-21", "Measured on device"…).174 public var sourceLabel: String175 public init(_ info: ModelInfo) {176 contextLength = info.contextLength; maxOutputTokens = info.maxOutputTokens177 toolCalling = info.capabilities.contains(.tools); structuredOutput = info.capabilities.contains(.structuredOutput)178 vision = info.capabilities.contains(.vision); reasoning = info.capabilities.contains(.reasoning)179 promptCaching = info.capabilities.contains(.promptCaching); pricing = info.pricing; sourceLabel = info.source.label180 }181}182183public extension ModelInfo {184 var docCapabilities: ModelCapabilities { ModelCapabilities(self) }185}186187/// User-level limits on where text may go. Enforced by the hub itself (last line of defence) and honoured by `ModelRouter`.188public struct DataPolicy: Sendable, Hashable, Codable {189 /// False = no request leaves this Mac, whatever is asked.190 public var allowCloud: Bool191 /// False = requests flagged as carrying document content are refused for cloud providers and custom endpoints.192 public var allowDocumentContentInCloud: Bool193 public init(allowCloud: Bool = true, allowDocumentContentInCloud: Bool = true) {194 self.allowCloud = allowCloud; self.allowDocumentContentInCloud = allowDocumentContentInCloud195 }196 public static let unrestricted = DataPolicy()197 public static let onDeviceOnly = DataPolicy(allowCloud: false, allowDocumentContentInCloud: false)198199 /// nil when a request to `provider` is allowed; otherwise the sentence shown to the user.200 public func refusal(for provider: ProviderKind, containsDocumentContent: Bool) -> String? {201 if provider.isLocal { return nil }202 if !allowCloud { return "Cloud models are turned off in ORIX Docs. This request was not sent." }203 if containsDocumentContent, !allowDocumentContentInCloud {204 return "Sending document content to cloud models is turned off in ORIX Docs. This request was not sent."205 }206 return nil207 }208}209210public enum ProviderHubError: Error, Sendable, Hashable, LocalizedError {211 case unknownProvider(String)212 case noKeyNeeded(String)213 case duplicateEndpointName(String)214 public var errorDescription: String? {215 switch self {216 case .unknownProvider(let id): "“\(id)” is not a provider ORIX Docs knows."217 case .noKeyNeeded(let name): "\(name) runs on this Mac and takes no API key."218 case .duplicateEndpointName(let name): "Another custom endpoint is already called “\(name)”."219 }220 }221}222223// MARK: - Hub224225public actor ProviderHub {226 public struct Configuration: Sendable {227 public var credentials: any CredentialStore228 public var transport: any HTTPTransport229 /// Folder of `providers.json` and `usage.json`; nil keeps everything in memory (tests, previews).230 public var storageDirectory: URL?231 public var diagnostics: (any DiagnosticsSink)?232 public var now: @Sendable () -> Date233 /// Automatic retries of a request that produced nothing (ORIX Astra's orchestrator rule).234 public var maxRetries: Int235 public init(credentials: any CredentialStore, transport: any HTTPTransport = URLSessionTransport(), storageDirectory: URL?,236 diagnostics: (any DiagnosticsSink)? = nil, now: @escaping @Sendable () -> Date = { Date() }, maxRetries: Int = 1) {237 self.credentials = credentials; self.transport = transport; self.storageDirectory = storageDirectory238 self.diagnostics = diagnostics; self.now = now; self.maxRetries = maxRetries239 }240241 /// The configuration of the app: macOS Keychain, URLSession, `~/Library/Application Support/ORIX Docs/AI`.242 public static func app() throws -> Configuration {243 Configuration(credentials: DocCredentials.keychain(), storageDirectory: try ProviderHub.defaultStorageDirectory())244 }245 }246247 /// `~/Library/Application Support/ORIX Docs/AI`.248 public static func defaultStorageDirectory() throws -> URL {249 try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)250 .appendingPathComponent("ORIX Docs", isDirectory: true).appendingPathComponent("AI", isDirectory: true)251 }252253 struct StoredCheck: Codable, Hashable {254 var ok: Bool; var detail: String; var errorTitle: String?; var modelCount: Int?; var remainingCreditUSD: Double?; var checkedAt: Date255 }256 struct StoredCatalogue: Codable, Hashable { var fetchedAt: Date; var models: [ModelInfo] }257 /// What `providers.json` holds: endpoint profiles (no secret), results of connection tests, cached model lists, the data policy.258 struct State: Codable {259 var schema = 1260 var endpoints: [EndpointProfile] = []261 var checks: [String: StoredCheck] = [:]262 var catalogues: [String: StoredCatalogue] = [:]263 var policy = DataPolicy()264 }265266 public nonisolated let usage: UsageLedger267 private let configuration: Configuration268 private var state: State269 private var localProviders: [ProviderKind: any ChatProvider] = [:]270 /// Masked key per provider, read from the credential store once and refreshed when a key changes. `.some(nil)` = no key.271 private var keyHints: [String: String?] = [:]272 private var observers: [UUID: AsyncStream<[ProviderSummary]>.Continuation] = [:]273274 public init(configuration: Configuration) {275 self.configuration = configuration276 var loaded = State()277 if let url = configuration.storageDirectory?.appendingPathComponent("providers.json"), let data = try? Data(contentsOf: url),278 let decoded = try? UsageLedger.decoder.decode(State.self, from: data), decoded.schema == 1 {279 loaded = decoded280 }281 state = loaded282 usage = UsageLedger(fileURL: configuration.storageDirectory?.appendingPathComponent("usage.json"), now: configuration.now)283 }284285 private func persist() {286 guard let dir = configuration.storageDirectory else { return }287 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)288 try? UsageLedger.encoder.encode(state).write(to: dir.appendingPathComponent("providers.json"), options: .atomic)289 }290291 // MARK: Providers292293 /// Every provider the hub offers, in display order: the keyed cloud providers, the custom endpoints, then on-device providers.294 public func providerIDs() -> [ProviderID] {295 ProviderKind.cloudKeyed.map { ProviderID($0) }296 + state.endpoints.sorted { ($0.createdAt, $0.id) < ($1.createdAt, $1.id) }.map { ProviderID(kind: .custom, endpointID: $0.id) }297 + [ProviderKind.appleFoundation, .mlx].filter { localProviders[$0] != nil }.map { ProviderID($0) }298 }299300 public func providers() -> [ProviderSummary] { providerIDs().compactMap { try? summary($0) } }301302 public func provider(_ id: ProviderID) throws -> ProviderSummary { try summary(id) }303304 /// The provider list now and after every change (key, test, endpoint, catalogue).305 public func providerUpdates() -> AsyncStream<[ProviderSummary]> {306 AsyncStream(bufferingPolicy: .bufferingNewest(1)) { continuation in307 let key = UUID()308 observers[key] = continuation309 continuation.yield(providers())310 continuation.onTermination = { [weak self] _ in Task { await self?.removeObserver(key) } }311 }312 }313 private func removeObserver(_ key: UUID) { observers[key] = nil }314 private func publish() { guard !observers.isEmpty else { return }; let list = providers(); for o in observers.values { o.yield(list) } }315316 private func endpoint(_ id: ProviderID) -> EndpointProfile? { id.endpointID.flatMap { e in state.endpoints.first { $0.id == e } } }317318 private func require(_ id: ProviderID) throws {319 switch id.kind {320 case .custom: guard endpoint(id) != nil else { throw ProviderHubError.unknownProvider(id.rawValue) }321 case .mlx, .appleFoundation: guard localProviders[id.kind] != nil else { throw ProviderHubError.unknownProvider(id.rawValue) }322 default: break323 }324 }325326 private func keyHint(_ id: ProviderID) -> String? {327 guard let account = id.credentialAccount else { return nil }328 if let cached = keyHints[id.rawValue] { return cached }329 // A Keychain failure reads as "no key" here; `setKey` and `verify` report the failure itself.330 let hint = ((try? configuration.credentials.secret(for: account)) ?? nil).map(Redactor.mask(key:))331 keyHints[id.rawValue] = .some(hint)332 return hint333 }334335 private func summary(_ id: ProviderID) throws -> ProviderSummary {336 try require(id)337 let check = state.checks[id.rawValue]338 let profile = endpoint(id)339 var s = ProviderSummary(id: id, displayName: profile?.name ?? id.kind.displayName, isOnDevice: id.kind.isLocal, hasKey: false, keyHint: nil,340 state: .notConfigured, detail: check?.detail, errorTitle: check?.errorTitle, lastCheckedAt: check?.checkedAt,341 modelCount: state.catalogues[id.rawValue]?.models.count ?? check?.modelCount,342 remainingCreditUSD: check?.remainingCreditUSD, baseURL: profile?.baseURL)343 if id.kind.isLocal {344 // On-device providers: usable or not, as their own check says. Unchecked = not known yet.345 s.state = check.map { $0.ok ? .verified : .unavailable } ?? .configured346 return s347 }348 s.keyHint = keyHint(id); s.hasKey = s.keyHint != nil349 // A custom endpoint may legitimately need no key (a server on the local network): it is configured as soon as it exists.350 let configured = s.hasKey || id.kind == .custom351 if !configured { s.state = .notConfigured; s.detail = nil; s.errorTitle = nil; s.lastCheckedAt = nil; s.remainingCreditUSD = nil }352 else if let check { s.state = check.ok ? .verified : .error }353 else { s.state = .configured }354 return s355 }356357 // MARK: Keys358359 /// Stores or replaces the key of a provider. The previous test result is discarded: the provider becomes `configured` until verified.360 public func setKey(_ key: String, for id: ProviderID) throws {361 try require(id)362 guard let account = id.credentialAccount else { throw ProviderHubError.noKeyNeeded(id.kind.displayName) }363 try configuration.credentials.setSecret(key, for: account)364 keyHints[id.rawValue] = nil; state.checks[id.rawValue] = nil365 persist(); publish()366 }367368 /// Removes the key, the test result and the cached model list of a provider.369 public func removeKey(for id: ProviderID) throws {370 guard let account = id.credentialAccount else { throw ProviderHubError.noKeyNeeded(id.kind.displayName) }371 try configuration.credentials.removeSecret(for: account)372 keyHints[id.rawValue] = nil; state.checks[id.rawValue] = nil373 if id.kind != .custom { state.catalogues[id.rawValue] = nil }374 persist(); publish()375 }376377 public func hasKey(for id: ProviderID) -> Bool { keyHint(id) != nil }378379 // MARK: Custom endpoints380381 public func endpoints() -> [EndpointProfile] { state.endpoints.sorted { ($0.createdAt, $0.id) < ($1.createdAt, $1.id) } }382383 /// Adds an OpenAI-compatible endpoint. The URL policy and header hygiene are ORIX Astra's (`EndpointProfile.validated`): HTTPS, or384 /// plain HTTP only when explicitly allowed for a local host; no credential in headers. The key, when given, goes to the Keychain.385 @discardableResult386 public func addEndpoint(name: String, baseURL: String, key: String? = nil, defaultModelID: String? = nil, allowInsecureHTTP: Bool = false,387 extraHeaders: [String: String] = [:]) throws -> ProviderSummary {388 let name = name.trimmingCharacters(in: .whitespacesAndNewlines)389 guard !name.isEmpty else { throw AstraError.invalidRequest("Give the endpoint a name.") }390 guard !state.endpoints.contains(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) else { throw ProviderHubError.duplicateEndpointName(name) }391 let profile = EndpointProfile(name: name, baseURL: baseURL.trimmingCharacters(in: .whitespacesAndNewlines), defaultModelID: defaultModelID,392 allowInsecureHTTP: allowInsecureHTTP, extraHeaders: extraHeaders, createdAt: configuration.now())393 _ = try profile.validated()394 let id = ProviderID(kind: .custom, endpointID: profile.id)395 if let key, !key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {396 try configuration.credentials.setSecret(key, for: CredentialAccount.endpoint(profile.id))397 }398 state.endpoints.append(profile); keyHints[id.rawValue] = nil399 persist(); publish()400 return try summary(id)401 }402403 /// Replaces the name, URL or options of an endpoint (the id is kept). The test result and the model list are discarded.404 public func updateEndpoint(_ profile: EndpointProfile) throws {405 guard let i = state.endpoints.firstIndex(where: { $0.id == profile.id }) else { throw ProviderHubError.unknownProvider("custom:\(profile.id)") }406 guard !state.endpoints.contains(where: { $0.id != profile.id && $0.name.caseInsensitiveCompare(profile.name) == .orderedSame }) else {407 throw ProviderHubError.duplicateEndpointName(profile.name)408 }409 _ = try profile.validated()410 state.endpoints[i] = profile411 let id = ProviderID(kind: .custom, endpointID: profile.id)412 state.checks[id.rawValue] = nil; state.catalogues[id.rawValue] = nil413 persist(); publish()414 }415416 /// Removes an endpoint with its key, its test result and its model list. Its usage history stays in the ledger.417 public func removeEndpoint(id endpointID: String) throws {418 let id = ProviderID(kind: .custom, endpointID: endpointID)419 try configuration.credentials.removeSecret(for: CredentialAccount.endpoint(endpointID))420 state.endpoints.removeAll { $0.id == endpointID }421 state.checks[id.rawValue] = nil; state.catalogues[id.rawValue] = nil; keyHints[id.rawValue] = nil422 persist(); publish()423 }424425 // MARK: On-device providers426427 /// Plugs an on-device provider (MLX, Apple Intelligence) into the hub. `DocLocalModels` does this; the hub itself links no runtime.428 public func registerOnDeviceProvider(_ provider: any ChatProvider) {429 precondition(provider.kind.isLocal, "only on-device providers are registered; cloud adapters come from ORIX Astra's registry")430 localProviders[provider.kind] = provider431 publish()432 }433434 // MARK: Adapters435436 private func adapter(for id: ProviderID) throws -> any ChatProvider {437 try require(id)438 if let local = localProviders[id.kind] { return local }439 return try ProviderRegistry.makeProvider(kind: id.kind, endpointID: id.endpointID, credentials: configuration.credentials,440 endpoints: state.endpoints, transport: configuration.transport, diagnostics: configuration.diagnostics)441 }442443 // MARK: Connection test444445 /// Tests the connection with the cheapest call the provider has (ORIX Astra's `verify()`), stores the result and returns the row.446 /// Never throws for a provider failure: the failure is the result (`state == .error`, `detail`, `errorTitle`).447 @discardableResult448 public func verify(_ id: ProviderID) async throws -> ProviderSummary {449 try require(id)450 if !id.kind.isLocal, id.kind != .custom, keyHint(id) == nil { return try summary(id) }451 let check: StoredCheck452 do {453 let status = try await adapter(for: id).verify()454 check = StoredCheck(ok: status.ok, detail: Redactor.redact(status.detail), errorTitle: status.ok ? nil : "Unavailable",455 modelCount: status.modelCount, remainingCreditUSD: status.remainingCreditUSD, checkedAt: configuration.now())456 } catch {457 let mapped = AstraError.wrap(error)458 check = StoredCheck(ok: false, detail: Redactor.redact(mapped.message), errorTitle: mapped.title, checkedAt: configuration.now())459 }460 // The provider may have been removed while the test ran.461 guard (try? require(id)) != nil else { throw ProviderHubError.unknownProvider(id.rawValue) }462 state.checks[id.rawValue] = check463 persist(); publish()464 return try summary(id)465 }466467 /// Tests every provider that can be tested (a key is stored, or it runs on this Mac), concurrently.468 public func verifyAll() async -> [ProviderSummary] {469 let ids = providers().filter { $0.state != .notConfigured }.map(\.id)470 await withTaskGroup(of: Void.self) { group in471 for id in ids { group.addTask { _ = try? await self.verify(id) } }472 }473 return providers()474 }475476 // MARK: Model catalogue477478 /// Models of one provider with their metadata (context, capabilities, price when the provider or ORIX Astra's curated479 /// catalogue has it). Served from the last fetch unless `refresh` is true or nothing was fetched yet. On-device providers are480 /// always read live. The list is cached in `providers.json` (model names and limits: no secret, no content).481 public func models(for id: ProviderID, refresh: Bool = false) async throws -> [ModelInfo] {482 try require(id)483 if !id.kind.isLocal, !refresh, let cached = state.catalogues[id.rawValue] { return cached.models }484 let models = try await adapter(for: id).listModels().sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending }485 guard (try? require(id)) != nil else { throw ProviderHubError.unknownProvider(id.rawValue) }486 state.catalogues[id.rawValue] = StoredCatalogue(fetchedAt: configuration.now(), models: models)487 persist(); publish()488 return models489 }490491 /// When the cached list of a provider was fetched; nil when it never was.492 public func catalogueDate(for id: ProviderID) -> Date? { state.catalogues[id.rawValue]?.fetchedAt }493494 /// Every model the hub already knows, without any network call: the cached lists of the providers that are configured.495 public func knownModels() -> [ModelInfo] {496 providers().filter { $0.state != .notConfigured && $0.state != .unavailable }.flatMap { state.catalogues[$0.id.rawValue]?.models ?? [] }497 }498499 /// Metadata of one model: the cached list first, then ORIX Astra's curated catalogue (documentation figures).500 public func modelInfo(_ ref: ModelRef) -> ModelInfo? {501 state.catalogues[ProviderID(model: ref).rawValue]?.models.first { $0.ref == ref } ?? CuratedCatalog.info(for: ref)502 }503504 public func capabilities(of ref: ModelRef) -> ModelCapabilities? { modelInfo(ref).map(ModelCapabilities.init) }505506 // MARK: Data policy507508 public var dataPolicy: DataPolicy { state.policy }509 public func setDataPolicy(_ policy: DataPolicy) { state.policy = policy; persist() }510511 // MARK: Generation512513 /// Streams one answer as normalized `StreamEvent`s. Never throws: a failure is the terminal `.error` event, so text already514 /// delivered stays valid. Exactly one start and one terminal event are guaranteed by ORIX Astra's orchestrator, which also515 /// retries a transient failure that produced nothing. Cancelling the consuming task (or dropping the stream) cancels the request.516 ///517 /// - Parameter containsDocumentContent: true when the prompt carries text of the user's document. The data policy then decides518 /// whether a cloud provider may receive it; a refused request is never sent and ends with `.error(.forbidden)`.519 /// An on-device request is never rerouted to the cloud, and a cloud request is never rerouted to another provider.520 public nonisolated func stream(_ request: GenerationRequest, containsDocumentContent: Bool = true, recordUsage: Bool = true) -> AsyncStream<StreamEvent> {521 AsyncStream(bufferingPolicy: .unbounded) { continuation in522 let task = Task {523 var outcome = GenerationOutcome()524 outcome.timing.startedAt = Date()525 if let refusal = await self.dataPolicy.refusal(for: request.model.provider, containsDocumentContent: containsDocumentContent) {526 continuation.yield(.messageStarted(MessageStart()))527 continuation.yield(.error(.forbidden(refusal)))528 continuation.finish(); return529 }530 let orchestrator = InferenceOrchestrator(maxRetries: await self.maxRetries) { ref in try await self.adapter(for: ProviderID(model: ref)) }531 for await event in orchestrator.stream(request) {532 outcome.apply(event)533 continuation.yield(event)534 }535 outcome.closeIfUnterminated(cancelled: Task.isCancelled)536 if recordUsage { await self.record(request.model, outcome) }537 continuation.finish()538 }539 continuation.onTermination = { _ in task.cancel() }540 }541 }542543 /// Runs one generation to its end and returns the folded result (text, tool calls, usage, stop reason, timing, error).544 public nonisolated func generate(_ request: GenerationRequest, containsDocumentContent: Bool = true, recordUsage: Bool = true) async -> GenerationOutcome {545 var outcome = GenerationOutcome()546 for await event in stream(request, containsDocumentContent: containsDocumentContent, recordUsage: recordUsage) { outcome.apply(event) }547 outcome.closeIfUnterminated(cancelled: Task.isCancelled)548 return outcome549 }550551 private var maxRetries: Int { configuration.maxRetries }552553 private func record(_ model: ModelRef, _ outcome: GenerationOutcome) async {554 await usage.record(UsageRecord(model: model, outcome: outcome, pricing: modelInfo(model)?.pricing, at: configuration.now()))555 }556557 /// Cost of a finished generation: reported by the provider, or usage × published price, or unavailable. Never guessed.558 public func cost(of outcome: GenerationOutcome, model: ModelRef) -> CostEstimate {559 UsageAccounting.cost(usage: outcome.usage, pricing: modelInfo(model)?.pricing, provider: model.provider)560 }561562 /// Upper bound before sending: estimated prompt tokens plus the whole output allowance, at the published price.563 public func preflightCost(inputTokens: Int, maxOutputTokens: Int, model: ModelRef) -> CostEstimate {564 UsageAccounting.preflight(inputTokens: inputTokens, maxOutputTokens: maxOutputTokens, pricing: modelInfo(model)?.pricing, provider: model.provider)565 }566567 public func usageSnapshot() async -> UsageSnapshot { await usage.snapshot() }568569 // MARK: Routing input570571 /// The candidates `ModelRouter` chooses from: every known model of every usable provider, with the speed measured so far.572 /// On-device details the hub cannot know (memory need, loaded state) are filled in by `DocLocalModels`.573 public func routeCandidates() async -> [RouteCandidate] {574 let snapshot = await usage.snapshot()575 let usable = Dictionary(uniqueKeysWithValues: providers().map { ($0.id, $0) })576 var out: [RouteCandidate] = []577 for (key, catalogue) in state.catalogues.sorted(by: { $0.key < $1.key }) {578 guard let id = ProviderID(rawValue: key), let provider = usable[id] else { continue }579 let unavailable: String? = switch provider.state {580 case .notConfigured: "\(provider.displayName) has no API key."581 case .unavailable: provider.detail ?? "\(provider.displayName) is unavailable on this Mac."582 case .error: "\(provider.displayName) failed its last connection test: \(provider.errorTitle ?? "error")."583 case .configured, .verified: nil584 }585 for model in catalogue.models {586 let totals = snapshot.usage(for: model.ref)587 out.append(RouteCandidate(model: model, providerName: provider.displayName, unavailableReason: unavailable,588 tokensPerSecond: totals?.meanTokensPerSecond, timeToFirstToken: totals?.meanTimeToFirstToken))589 }590 }591 return out592 }593}594