Repository Public License
1import Foundation2import NavigatorCore34// MARK: - Secrets56/// Where API keys live. The app backs this with the Keychain; ProviderKit never stores a key anywhere else and never7/// includes one in a configuration, a log line, an error or a `description`.8public protocol ProviderSecretSource: Sendable {9 func secret(for account: String) async throws -> String?10 func setSecret(_ value: String, for account: String) async throws11 func deleteSecret(for account: String) async throws12}1314/// Adapts NavigatorCore's `SecretStore` (implemented over the Keychain by the Persistence module) to15/// `ProviderSecretSource`, so the app can pass its store without ProviderKit importing Persistence.16public struct SecretStoreSecretSource: ProviderSecretSource {17 private let store: any SecretStore1819 public init(_ store: any SecretStore) { self.store = store }2021 public func secret(for account: String) async throws -> String? { try await store.secretString(for: account) }22 public func setSecret(_ value: String, for account: String) async throws { try await store.setSecret(value, for: account) }23 public func deleteSecret(for account: String) async throws { try await store.removeSecret(for: account) }24}2526// MARK: - Configuration2728/// Limits the user sets on one configured provider. Enforced by the registry before a request is sent.29public struct ProviderLimits: Sendable, Hashable, Codable {30 /// Cap on generated tokens per response. A request asking for more is lowered to this.31 public var maxOutputTokens: Int?32 /// Requests allowed in any 60-second window. One more is refused, not queued.33 public var maxRequestsPerMinute: Int?34 /// Calendar-month budget in US dollars, compared with the *estimated* cost recorded in the usage ledger.35 /// Requests whose cost is unknown do not count, so this is a guard rail, not a guarantee.36 public var monthlyBudgetUSD: Double?3738 public init(maxOutputTokens: Int? = nil, maxRequestsPerMinute: Int? = nil, monthlyBudgetUSD: Double? = nil) {39 self.maxOutputTokens = maxOutputTokens; self.maxRequestsPerMinute = maxRequestsPerMinute; self.monthlyBudgetUSD = monthlyBudgetUSD40 }41}4243/// One provider the user configured. Non-secret by construction: it has no field for a key.44public struct ProviderConfiguration: Sendable, Hashable, Codable, Identifiable, CustomStringConvertible {45 public var id: String46 public var family: ProviderFamily47 public var displayName: String48 /// Required for `.compatible`; optional override for the hosted families (a corporate gateway); unused for `.local`.49 public var baseURL: String?50 /// The provider's own model id, free-form. For `.local`, a model id of the selected runtime.51 public var model: String52 public var limits: ProviderLimits53 /// `.compatible` only: the user's explicit opt-in to plain HTTP for a host that is not local or private.54 public var allowInsecureHTTP: Bool55 /// `.compatible` only: extra non-credential headers.56 public var headers: [String: String]57 /// `.local` only: `LocalModelRuntime.id`.58 public var localRuntimeID: String?5960 public init(id: String = UUID().uuidString, family: ProviderFamily, displayName: String? = nil, baseURL: String? = nil, model: String,61 limits: ProviderLimits = ProviderLimits(), allowInsecureHTTP: Bool = false, headers: [String: String] = [:], localRuntimeID: String? = nil) {62 self.id = id; self.family = family; self.displayName = displayName ?? family.displayName; self.baseURL = baseURL; self.model = model63 self.limits = limits; self.allowInsecureHTTP = allowInsecureHTTP; self.headers = headers; self.localRuntimeID = localRuntimeID64 }6566 /// The account under which this configuration's key is kept in the `ProviderSecretSource`.67 public var secretAccount: String { "provider.\(id).api-key" }6869 public var description: String { "\(displayName) [\(family.rawValue)] model=\(model)" }7071 /// Checks everything that can be checked without the network.72 public func validate() throws {73 guard !id.isEmpty else { throw ProviderError.configuration("The provider has no identifier.") }74 guard !displayName.trimmingCharacters(in: .whitespaces).isEmpty else { throw ProviderError.configuration("Give the provider a name.") }75 if let limit = limits.maxOutputTokens, limit < 1 { throw ProviderError.configuration("The output token limit must be at least 1.") }76 if let limit = limits.maxRequestsPerMinute, limit < 1 { throw ProviderError.configuration("The requests-per-minute limit must be at least 1.") }77 if let budget = limits.monthlyBudgetUSD, budget < 0 || !budget.isFinite { throw ProviderError.configuration("The monthly budget cannot be negative.") }78 switch family {79 case .compatible:80 guard let baseURL, !baseURL.trimmingCharacters(in: .whitespaces).isEmpty else { throw ProviderError.configuration("Enter the base URL of the endpoint.") }81 _ = try CompatibleProvider.Endpoint(baseURL: baseURL, allowInsecureHTTP: allowInsecureHTTP, headers: headers).validated()82 case .anthropic, .openAI, .openRouter:83 // A key for a hosted service is never sent over plain HTTP, whatever the host.84 if let baseURL, !baseURL.isEmpty {85 let url = try EndpointPolicy.validate(baseURL, allowInsecureHTTP: false)86 guard url.scheme?.lowercased() == "https" else { throw ProviderError.insecureEndpoint("\(family.displayName) must be reached over https.") }87 }88 case .local:89 guard let localRuntimeID, !localRuntimeID.isEmpty else { throw ProviderError.configuration("Choose an on-device runtime.") }90 }91 }92}9394/// Persistence of the registry's non-secret state, implemented by the app (a file, a database row). The payload is95/// JSON and contains no secret.96public protocol ProviderConfigurationStore: Sendable {97 /// The last saved payload, or `nil` when nothing was saved yet.98 func loadProviderConfigurations() async throws -> Data?99 func saveProviderConfigurations(_ data: Data) async throws100}101102/// Volatile store for tests and previews.103public actor InMemoryProviderConfigurationStore: ProviderConfigurationStore {104 private var data: Data?105 public init(data: Data? = nil) { self.data = data }106 public func loadProviderConfigurations() -> Data? { data }107 public func saveProviderConfigurations(_ data: Data) { self.data = data }108}109110// MARK: - Registry111112/// The configured providers: their settings, keys (through `ProviderSecretSource`), limits, prices and usage.113public actor ProviderRegistry {114 /// What is persisted. Versioned so a later build can migrate it.115 struct Document: Codable {116 var version = 1117 var configurations: [ProviderConfiguration] = []118 var defaultProviderID: String?119 /// Prices the user edited; built-in and live prices are not persisted.120 var userPrices: [String: [String: ModelPrice]] = [:]121 }122123 private let store: any ProviderConfigurationStore124 private let secrets: any ProviderSecretSource125 private let environment: ProviderEnvironment126 public nonisolated let ledger: any UsageLedger127 private let localRuntimes: [any LocalModelRuntime]128 private let device: DeviceCapability129 private let now: @Sendable () -> Date130131 private var document = Document()132 private var prices = PriceTable.builtIn133 private var limiters: [String: RequestRateLimiter] = [:]134135 /// - Parameters:136 /// - localRuntimes: the on-device runtimes linked into the app. Pass `AppleOnDeviceModel.makeRuntime()` when it137 /// is not `nil`, and an MLX runtime if the optional package is present.138 public init(store: any ProviderConfigurationStore, secrets: any ProviderSecretSource, environment: ProviderEnvironment = ProviderEnvironment(),139 ledger: any UsageLedger = InMemoryUsageLedger(), localRuntimes: [any LocalModelRuntime] = [],140 device: DeviceCapability = .current, now: @escaping @Sendable () -> Date = { Date() }) {141 self.store = store; self.secrets = secrets; self.environment = environment; self.ledger = ledger142 self.localRuntimes = localRuntimes; self.device = device; self.now = now143 }144145 // MARK: Persistence146147 /// Reads the saved configurations. Call once at launch; until then the registry is empty.148 public func load() async throws {149 guard let data = try await store.loadProviderConfigurations() else { return }150 do { document = try JSONDecoder().decode(Document.self, from: data) } catch {151 throw ProviderError.configuration("The saved provider settings could not be read.")152 }153 for (family, models) in document.userPrices {154 guard let family = ProviderFamily(rawValue: family) else { continue }155 for (model, price) in models { prices.setPrice(price, family: family, model: model) }156 }157 }158159 private func save() async throws {160 let encoder = JSONEncoder()161 encoder.outputFormatting = [.sortedKeys]162 try await store.saveProviderConfigurations(try encoder.encode(document))163 }164165 // MARK: Configurations166167 public var configurations: [ProviderConfiguration] { document.configurations }168169 public func configuration(id: String) -> ProviderConfiguration? { document.configurations.first { $0.id == id } }170171 /// The provider used when the caller names none. `nil` until the user picked one: AI stays off.172 public var defaultProviderID: String? { document.defaultProviderID }173174 public func setDefaultProvider(id: String?) async throws {175 if let id, configuration(id: id) == nil { throw ProviderError.configuration("That provider no longer exists.") }176 document.defaultProviderID = id177 try await save()178 }179180 /// Adds a configuration or replaces the one with the same id, after validating it.181 public func upsert(_ configuration: ProviderConfiguration) async throws {182 try configuration.validate()183 if let index = document.configurations.firstIndex(where: { $0.id == configuration.id }) {184 document.configurations[index] = configuration185 } else {186 document.configurations.append(configuration)187 }188 limiters[configuration.id] = nil // a changed rate limit starts a fresh window189 try await save()190 }191192 /// Removes a configuration and deletes its key.193 public func remove(id: String) async throws {194 guard let configuration = configuration(id: id) else { return }195 try await secrets.deleteSecret(for: configuration.secretAccount)196 document.configurations.removeAll { $0.id == id }197 if document.defaultProviderID == id { document.defaultProviderID = nil }198 limiters[id] = nil199 try await save()200 }201202 // MARK: Keys203204 private func require(_ id: String) throws -> ProviderConfiguration {205 guard let configuration = configuration(id: id) else { throw ProviderError.configuration("That provider is not configured.") }206 return configuration207 }208209 /// Stores the key in the secret source. An empty key deletes it.210 public func setAPIKey(_ key: String, for id: String) async throws {211 let configuration = try require(id)212 let trimmed = key.trimmingCharacters(in: .whitespacesAndNewlines)213 if trimmed.isEmpty { try await secrets.deleteSecret(for: configuration.secretAccount) }214 else { try await secrets.setSecret(trimmed, for: configuration.secretAccount) }215 }216217 public func removeAPIKey(for id: String) async throws {218 try await secrets.deleteSecret(for: try require(id).secretAccount)219 }220221 /// Whether a key is stored. The key itself is never returned by the registry.222 public func hasAPIKey(for id: String) async throws -> Bool {223 let key = try await secrets.secret(for: try require(id).secretAccount)224 return !(key ?? "").isEmpty225 }226227 // MARK: Providers228229 /// The provider for a configuration, without limits or accounting. For the settings screen ("Test connection",230 /// model list). The agent runtime uses `provider(for:space:)`.231 public func unmeteredProvider(for id: String) throws -> any ChatProvider {232 try Self.makeProvider(try require(id), secrets: secrets, environment: environment, localRuntimes: localRuntimes, device: device)233 }234235 /// Builds the adapter of a configuration. `nonisolated` and static so it can be tested without a registry.236 static func makeProvider(_ configuration: ProviderConfiguration, secrets: any ProviderSecretSource, environment: ProviderEnvironment,237 localRuntimes: [any LocalModelRuntime], device: DeviceCapability) throws -> any ChatProvider {238 try configuration.validate()239 let account = configuration.secretAccount240 let key: KeySource = { try await secrets.secret(for: account) }241 let baseURL = configuration.baseURL.flatMap { $0.isEmpty ? nil : URL(string: $0.trimmingCharacters(in: .whitespacesAndNewlines)) }242 switch configuration.family {243 case .anthropic: return AnthropicProvider(apiKey: key, baseURL: baseURL, environment: environment)244 case .openAI: return OpenAIProvider(apiKey: key, baseURL: baseURL, environment: environment)245 case .openRouter: return OpenRouterProvider(apiKey: key, baseURL: baseURL, environment: environment)246 case .compatible:247 let endpoint = CompatibleProvider.Endpoint(baseURL: configuration.baseURL ?? "", allowInsecureHTTP: configuration.allowInsecureHTTP, headers: configuration.headers)248 return CompatibleProvider(endpoint: endpoint, apiKey: key, environment: environment)249 case .local:250 guard let runtime = localRuntimes.first(where: { $0.id == configuration.localRuntimeID }) else {251 let missing = configuration.localRuntimeID == LocalRuntimeIdentifier.mlx ? LocalCapabilityReport.mlxNotInstalledMessage + "."252 : (AppleOnDeviceModel.unavailableReason ?? "That on-device runtime is not installed.")253 throw ProviderError.local(missing)254 }255 return LocalProvider(runtime: runtime, device: device)256 }257 }258259 /// The provider the agent runtime and the assistant use: the configuration's limits are enforced and every260 /// response is recorded in the usage ledger, attributed to `space` when given.261 public func provider(for id: String, space: SpaceID? = nil) throws -> MeteredProvider {262 let configuration = try require(id)263 let base = try unmeteredProvider(for: id)264 let limiter: RequestRateLimiter265 if let existing = limiters[id] { limiter = existing } else {266 limiter = RequestRateLimiter(now: now)267 limiters[id] = limiter268 }269 return MeteredProvider(base: base, configuration: configuration, space: space, limiter: limiter, ledger: ledger, registry: self, now: now)270 }271272 /// `provider(for:space:)` for the default provider. Throws when the user has not chosen one.273 public func defaultProvider(space: SpaceID? = nil) throws -> MeteredProvider {274 guard let id = document.defaultProviderID else { throw ProviderError.configuration("No AI provider is selected. Add one in Settings.") }275 return try provider(for: id, space: space)276 }277278 // MARK: Local models279280 public func localCapabilityReport() async -> LocalCapabilityReport {281 await LocalCapabilityReport.make(runtimes: localRuntimes, device: device)282 }283284 // MARK: Prices and usage285286 public var priceTable: PriceTable { prices }287288 /// Sets (or with `nil` removes) a user price. Persisted with the configurations.289 public func setUserPrice(_ price: ModelPrice?, family: ProviderFamily, model: String) async throws {290 var edited = price291 edited?.source = .user292 prices.setPrice(edited ?? PriceTable.builtIn.price(family: family, model: model), family: family, model: model)293 document.userPrices[family.rawValue, default: [:]][model.lowercased()] = edited294 try await save()295 }296297 /// Fetches the configuration's model list and, where it publishes prices (OpenRouter), keeps them for estimates.298 @discardableResult299 public func refreshModels(for id: String) async throws -> [ModelInfo] {300 let configuration = try require(id)301 let models = try await unmeteredProvider(for: id).listModels()302 prices.merge(liveModels: models, family: configuration.family)303 return models304 }305306 public func price(family: ProviderFamily, model: String) -> ModelPrice? { prices.price(family: family, model: model) }307308 /// An estimate of what `usage` cost, or `nil` when it cannot be estimated (see `CostEstimator`).309 public func estimateCost(usage: ProviderUsage?, family: ProviderFamily, model: String) -> CostEstimate? {310 CostEstimator.estimate(usage: usage, price: prices.price(family: family, model: model))311 }312313 /// Totals of the current calendar month for one provider.314 public func monthToDate(for id: String) async -> UsageTotals {315 await ledger.totals(providerID: id, spaceID: nil, since: Self.startOfMonth(now()))316 }317318 static func startOfMonth(_ date: Date) -> Date {319 let calendar = Calendar.current320 return calendar.date(from: calendar.dateComponents([.year, .month], from: date)) ?? date321 }322}323324// MARK: - Rate limiting325326/// A sliding 60-second window. A request over the limit is refused with the wait until a slot frees.327actor RequestRateLimiter {328 private var sent: [Date] = []329 private let now: @Sendable () -> Date330331 init(now: @escaping @Sendable () -> Date) { self.now = now }332333 /// Registers a request, or returns the seconds to wait when the window is full.334 func admit(limit: Int) -> TimeInterval? {335 let current = now()336 sent.removeAll { current.timeIntervalSince($0) >= 60 }337 if sent.count >= limit, let oldest = sent.first { return max(1, 60 - current.timeIntervalSince(oldest)) }338 sent.append(current)339 return nil340 }341}342343// MARK: - Metered provider344345/// A provider with its configuration's limits enforced and its usage recorded. Returned by346/// `ProviderRegistry.provider(for:space:)`.347public struct MeteredProvider: ChatProvider {348 public var family: ProviderFamily { configuration.family }349 public let configuration: ProviderConfiguration350 public let space: SpaceID?351352 private let base: any ChatProvider353 private let limiter: RequestRateLimiter354 private let ledger: any UsageLedger355 private let registry: ProviderRegistry356 private let now: @Sendable () -> Date357358 init(base: any ChatProvider, configuration: ProviderConfiguration, space: SpaceID?, limiter: RequestRateLimiter, ledger: any UsageLedger,359 registry: ProviderRegistry, now: @escaping @Sendable () -> Date) {360 self.base = base; self.configuration = configuration; self.space = space; self.limiter = limiter361 self.ledger = ledger; self.registry = registry; self.now = now362 }363364 /// A request for the configured model.365 public func request(system: String? = nil, messages: [ChatMessage], tools: [ToolDefinition] = [], options: GenerationOptions = GenerationOptions()) -> ChatRequest {366 ChatRequest(model: configuration.model, system: system, messages: messages, tools: tools, options: options)367 }368369 public func listModels() async throws -> [ModelInfo] { try await registry.refreshModels(for: configuration.id) }370 public func testConnection() async throws -> ConnectionReport { try await base.testConnection() }371372 public func stream(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, Error> {373 let base = base, configuration = configuration, space = space, limiter = limiter, ledger = ledger, registry = registry, now = now374 return AsyncThrowingStream(bufferingPolicy: .unbounded) { continuation in375 let task = Task {376 var request = request377 if request.model.isEmpty { request.model = configuration.model }378 var sent = false379 var usage: ProviderUsage?380 do {381 // Limits are checked before anything leaves the device.382 if let cap = configuration.limits.maxOutputTokens {383 request.options.maxOutputTokens = min(request.options.maxOutputTokens ?? cap, cap)384 }385 if let budget = configuration.limits.monthlyBudgetUSD {386 let spent = await registry.monthToDate(for: configuration.id).estimatedCostUSD387 if spent >= budget {388 throw ProviderError.limitExceeded(String(format: "The monthly budget of $%.2f for “%@” is used up (estimated $%.2f spent). Raise it in Settings to continue.",389 budget, configuration.displayName, spent))390 }391 }392 if let limit = configuration.limits.maxRequestsPerMinute, let wait = await limiter.admit(limit: limit) {393 throw ProviderError.limitExceeded("“\(configuration.displayName)” is limited to \(limit) requests per minute. Try again in \(Int(wait.rounded(.up))) s.")394 }395 sent = true396 for try await event in base.stream(request) {397 if case .usage(let reported) = event { usage = usage?.merged(with: reported) ?? reported }398 continuation.yield(event)399 }400 if Task.isCancelled { throw ProviderError.cancelled }401 continuation.finish()402 } catch {403 continuation.finish(throwing: Task.isCancelled ? ProviderError.cancelled : ProviderError.wrap(error))404 }405 // A request that reached the provider is recorded even when it failed or was stopped: tokens reported406 // before the interruption were consumed. Usage stays `nil` (unknown) when none was reported.407 if sent {408 let cost = await registry.estimateCost(usage: usage, family: configuration.family, model: request.model)409 await ledger.record(UsageRecord(date: now(), providerID: configuration.id, family: configuration.family, model: request.model,410 spaceID: space, usage: usage, cost: cost))411 }412 }413 continuation.onTermination = { _ in task.cancel() }414 }415 }416}417