Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Sources/DocLocalModels/LocalModelLibrary.swift10// Description : The on-device model library of ORIX Docs on a Mac: one11// façade over ORIX Astra's local stack. Catalogue (bundled12// copy of Astra's catalogue, refreshed from13// www.orixlab.dev), per-model metadata and compatibility14// with this Mac, downloads with progress / pause / resume /15// cancel / retry, SHA-256 verification and atomic install16// (Astra's `DownloadCoordinator`), repair, removal, load /17// unload under the editor-aware memory governor, streaming18// generation and cancellation (Astra's `LocalEngine` on19// MLX). Models live under `~/Library/Application20// Support/ORIX Docs/Models`. Only weight, tokenizer and21// configuration files listed in the catalogue are22// downloaded, each pinned by SHA-256; nothing downloaded is23// ever executed (MLX reads tensors and JSON; no repository24// code is loaded or run).25// Module : DocLocalModels26// Repository : https://git.spboucher.ai/orix-docs27// Created : 2026-11-2228// Last Modified : 2026-11-2229//30// =============================================================================31// AUTHOR & PROFESSIONAL AFFILIATION32// =============================================================================33//34// Author : Simon-Pierre Boucher35// Position : Professor of Finance36// Institution : Université du Québec en Outaouais (UQO)37// Department : Département des sciences administratives38// Organization : SP Boucher39//40// Website : https://spboucher.ai41// Git : https://git.spboucher.ai42//43// =============================================================================44// OFFICIAL CONTACT DIRECTORY45// =============================================================================46//47// General : info@spboucher.ai48// Professional : contact@spboucher.ai49// Direct : simon@spboucher.ai50// Research : research@spboucher.ai51// Development : dev@spboucher.ai52// Support : support@spboucher.ai53// Security/Admin : admin@spboucher.ai54// Notifications : notifications@spboucher.ai55//56// Preferred Contact: support@spboucher.ai57//58// =============================================================================59// COPYRIGHT & INTELLECTUAL PROPERTY60// =============================================================================61//62// Copyright (c) 202663// Simon-Pierre Boucher64//65// All rights reserved where applicable.66//67// This file is governed by the applicable project license,68// copyright notices, institutional agreements and relevant law.69//70// Unless expressly authorized by the applicable license or71// rights holder, copying, redistribution, sublicensing,72// publication and commercial exploitation are not permitted.73//74// Existing third-party rights and notices remain unaffected.75//76// =============================================================================77// CONFIDENTIALITY & SECURITY78// =============================================================================79//80// Classification : Public81// Distribution : Public repository; use is governed by the project license82// Security Contact : admin@spboucher.ai83//84// Access to this source does not independently grant permission85// to redistribute or disclose confidential materials.86//87// Do not embed credentials, private keys, access tokens,88// certificates or confidential personal information.89//90// =============================================================================91// LICENSE & MAINTENANCE92// =============================================================================93//94// License : None specified (no license file in this repository)95// Maintainer : Simon-Pierre Boucher96// Technical Contact: dev@spboucher.ai97//98// =============================================================================99// END OF SP BOUCHER SOURCE HEADER100// =============================================================================101102import AstraCore103import AstraLocal104import DocAI105import Foundation106107/// Categories the model browser offers. Derived from the catalogue's tags and status; a model can be in several.108public enum LocalModelCategory: String, Sendable, Hashable, Codable, CaseIterable, Identifiable {109 case lightweight, writing, reasoning, coding, mathematics, multilingual, vision, experimental110 public var id: String { rawValue }111 public var title: String {112 switch self {113 case .lightweight: "Lightweight"114 case .writing: "Writing"115 case .reasoning: "Reasoning"116 case .coding: "Coding"117 case .mathematics: "Mathematics"118 case .multilingual: "Multilingual"119 case .vision: "Vision"120 case .experimental: "Experimental"121 }122 }123 /// The catalogue tag behind the category; `experimental` is a status, not a tag.124 var tag: String? {125 switch self {126 case .lightweight: ModelTag.lightweight127 case .writing: ModelTag.general // general-purpose chat models are the ones suited to drafting and rewriting128 case .reasoning: ModelTag.reasoning129 case .coding: ModelTag.coding130 case .mathematics: ModelTag.math131 case .multilingual: ModelTag.multilingual132 case .vision: ModelTag.vision133 case .experimental: nil134 }135 }136 /// The advisor goal used to recommend a model of this category.137 var goal: AdvisorGoal? {138 switch self {139 case .lightweight: .lowestMemory140 case .writing: .everydayChat141 case .reasoning: .advancedReasoning142 case .coding: .programming143 case .mathematics: .mathematics144 case .multilingual: .multilingual145 case .vision: .imageAnalysis146 case .experimental: nil147 }148 }149 public static func categories(of card: LocalModelCard) -> [LocalModelCategory] {150 allCases.filter { category in151 if category == .experimental { return card.status == .experimental }152 return category.tag.map(card.hasTag) ?? false153 }154 }155}156157/// One model as the browser shows it: the catalogue card plus what is true on this Mac right now.158public struct LocalModelEntry: Sendable, Hashable, Identifiable {159 public var card: LocalModelCard160 public var id: String { card.id }161 public var categories: [LocalModelCategory]162 public var isInstalled: Bool163 public var isLoaded: Bool164 /// The catalogue pins other bytes than the installed ones. Nothing is replaced until the user asks.165 public var updateAvailable: Bool166 /// The advisor recommends it on this Mac for at least one category (see `recommendedFor`).167 public var isRecommended: Bool168 public var recommendedFor: [LocalModelCategory]169 /// ORIX Astra's compatibility judgement for this Mac: class, numbers, reasons, and whether it is measured or estimated.170 public var compatibility: CompatibilityReport171 /// The editor-aware verdict: may it be loaded now, next to an open document?172 public var loadDecision: ModelLoadDecision173 /// Download in progress, paused or failed; nil when there is none.174 public var download: DownloadStatus?175 public var bytesOnDisk: Int64176 /// Speed measured on this Mac in this session, or recorded in the catalogue for this very machine model; nil otherwise.177 public var measurement: ModelMeasurement?178179 // Metadata, straight from the card.180 public var displayName: String { card.displayName }181 public var publisher: String { card.publisher }182 public var parameterCount: Int64? { card.parameterCount }183 public var quantization: String { card.quantization }184 public var contextLength: Int { card.contextLength }185 public var downloadBytes: Int64 { card.totalBytes }186 /// Estimated memory needed to run it at the governor's default context (weights + context cache + runtime).187 public var estimatedMemoryBytes: Int64 { loadDecision.fit.estimatedNeedBytes }188 public var capabilities: Set<Capability> { Set(card.capabilities) }189 public var licenseID: String { card.licenseID }190 public var licenseURL: String { card.licenseURL }191 public var status: ModelStatus { card.status }192 public var ref: ModelRef { ModelRef(provider: .mlx, modelID: card.id) }193}194195public enum LocalModelLibraryError: Error, Sendable, Hashable, LocalizedError {196 case unknownModel(String)197 case notInstalled(String)198 case memory(ModelLoadDecision)199 case bundledCatalogUnreadable(String)200 public var errorDescription: String? {201 switch self {202 case .unknownModel(let id): "“\(id)” is not in the model catalogue."203 case .notInstalled(let id): "“\(id)” is not downloaded."204 case .memory(let decision): decision.reason205 case .bundledCatalogUnreadable(let why): "The built-in model catalogue could not be read: \(why)"206 }207 }208}209210public actor LocalModelLibrary {211 public struct Configuration: Sendable {212 /// Folder of the models. Default: `~/Library/Application Support/ORIX Docs/Models`.213 public var root: URL214 /// Where the online catalogue lives (ORIX Astra's mirror).215 public var catalogBase: URL = ModelCatalog.defaultBase216 public var http: any HTTPTransport = URLSessionTransport()217 /// nil = ORIX Astra's URLSession transport with HTTP Range resume.218 public var downloadTransport: (any DownloadTransport)?219 public var download = DownloadCoordinator.Configuration()220 /// Readings and loader of the engine; tests script them.221 public var environment = LocalEngine.Environment()222 public var device: DeviceFacts = .current()223 /// nil = the bundled copy of the catalogue.224 public var catalog: ModelCatalog?225 public init(root: URL) {226 self.root = root227 // ORIX Astra's reading has no "available now" figure on macOS; the governor's reading adds one.228 environment.memory = { EditorMemoryGovernor.systemReading() }229 }230231 public static func app() throws -> Configuration { Configuration(root: try LocalModelLibrary.defaultRoot()) }232 }233234 public struct CatalogRefresh: Sendable, Hashable {235 public var modelCount: Int236 /// Online entries refused because they pin other bytes than the built-in entry of the same id.237 public var rejected: [ModelCatalog.Rejection]238 /// Why the online catalogue could not be used; the built-in one stays in force.239 public var failure: AstraError?240 }241242 public struct Storage: Sendable, Hashable {243 public var root: URL244 public var usedBytes: Int64245 public var availableBytes: Int64?246 public var installedCount: Int247 }248249 /// `~/Library/Application Support/ORIX Docs/Models`.250 public static func defaultRoot() throws -> URL {251 try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)252 .appendingPathComponent("ORIX Docs", isDirectory: true).appendingPathComponent("Models", isDirectory: true)253 }254255 /// The catalogue shipped inside the app: a byte-for-byte copy of ORIX Astra's `docs/catalog/catalog.json` at the vendored revision.256 public static func bundledCatalog() throws -> ModelCatalog {257 guard let url = Bundle.module.url(forResource: "catalog", withExtension: "json") else { throw LocalModelLibraryError.bundledCatalogUnreadable("the file is missing from the bundle") }258 do { return try ModelCatalog.decode(try Data(contentsOf: url), origin: .bundled) }259 catch { throw LocalModelLibraryError.bundledCatalogUnreadable((error as? LocalizedError)?.errorDescription ?? "\(error)") }260 }261262 public nonisolated let store: ModelStore263 public nonisolated let downloads: DownloadCoordinator264 public nonisolated let engine: LocalEngine265 public nonisolated let governor: EditorMemoryGovernor266 public nonisolated let device: DeviceFacts267 private let bundled: ModelCatalog268 private var catalog: ModelCatalog269 private let client: CatalogClient270 private let readMemory: @Sendable () -> MemoryReading271 private let readThermal: @Sendable () -> ThermalLevel272 private var started = false273274 public init(configuration: Configuration, governor: EditorMemoryGovernor? = nil) throws {275 let store = ModelStore(root: configuration.root)276 try store.prepare()277 self.store = store278 bundled = try configuration.catalog ?? Self.bundledCatalog()279 catalog = bundled280 client = CatalogClient(base: configuration.catalogBase, transport: configuration.http)281 downloads = DownloadCoordinator(store: store, transport: configuration.downloadTransport, configuration: configuration.download)282 let memory = configuration.environment.memory283 self.governor = governor ?? EditorMemoryGovernor(memory: memory)284 // One model in memory at a time: the editor shares this Mac's memory with it.285 engine = LocalEngine(store: store, configuration: LocalEngine.Configuration(maxLoadedModels: 1), memoryGovernor: MemoryGovernor(platform: .macOS),286 environment: configuration.environment)287 device = configuration.device288 readMemory = memory289 readThermal = configuration.environment.thermal290 }291292 /// Call once at launch: finds interrupted downloads (they come back paused, or resume when they were cut by a crash), starts293 /// thermal and memory monitoring, and connects the memory governor to the engine. Idempotent.294 public func start() async {295 guard !started else { return }296 started = true297 await downloads.restore()298 await downloads.continueInterrupted()299 await engine.startMonitoring()300 let engine = engine301 await governor.onPressure { critical in302 await engine.handleMemoryPressure(critical: critical)303 if critical { await engine.unloadAll() }304 }305 await governor.startMonitoring()306 }307308 // MARK: Catalogue309310 /// Refreshes the catalogue from the site. An online entry for a built-in model is accepted only when its commit and every file311 /// hash equal the built-in ones (ORIX Astra's rule); on any failure the built-in catalogue stays in force.312 @discardableResult313 public func refreshCatalog() async -> CatalogRefresh {314 let result = await client.refreshed(bundled: bundled)315 catalog = result.catalog316 return CatalogRefresh(modelCount: catalog.models.count, rejected: result.rejected, failure: result.failure)317 }318319 public func currentCatalog() -> ModelCatalog { catalog }320321 /// ORIX Astra's typed view over the catalogue and what is installed (search, sort, filters).322 public func registry() -> ModelRegistry { ModelRegistry(catalog: catalog, installed: store.models()) }323324 private func measurements(loadedMetrics: [LocalGenerationMetrics]) -> [ModelMeasurement] {325 var byModel: [String: ModelMeasurement] = [:]326 // The catalogue's own record counts only when it was taken on this very machine model.327 for card in catalog.models { if let m = ModelMeasurement(card: card), m.wasTaken(on: device) { byModel[card.id] = m } }328 // What this session measured takes precedence.329 for metrics in loadedMetrics {330 guard let speed = metrics.decodeTokensPerSecond, speed > 0 else { continue }331 byModel[metrics.modelID] = ModelMeasurement(modelID: metrics.modelID, on: device, tokensPerSecond: speed, timeToFirstToken: metrics.timeToFirstToken,332 peakMemoryBytes: metrics.peakMemoryBytes)333 }334 return byModel.values.sorted { $0.modelID < $1.modelID }335 }336337 /// Every model of the catalogue (and any installed model that left it), installed first, with its state on this Mac.338 /// - Parameters:339 /// - category: keep one category only.340 /// - search: matches name, id, publisher, family, repository and tags (ORIX Astra's registry search).341 /// - installedOnly: keep what is on disk.342 public func entries(category: LocalModelCategory? = nil, search: String = "", installedOnly: Bool = false) async -> [LocalModelEntry] {343 let registry = registry()344 let snapshot = await engine.snapshot()345 let statuses = Dictionary(uniqueKeysWithValues: await downloads.statuses().map { ($0.id, $0) })346 let measured = measurements(loadedMetrics: engine.monitor.history)347 let reading = readMemory(), thermal = readThermal()348 let recommended = recommendations(registry: registry, installed: Set(registry.installed.map(\.id)), measured: measured, reading: reading, thermal: thermal)349 var rows = search.trimmingCharacters(in: .whitespaces).isEmpty ? registry.installedFirst : registry.search(search)350 if installedOnly { rows = rows.filter(\.isInstalled) }351 var out: [LocalModelEntry] = []352 for row in rows {353 let categories = LocalModelCategory.categories(of: row.card)354 if let category, !categories.contains(category) { continue }355 let compatibility = CompatibilityEngine.assess(card: row.card, device: device, memory: reading, thermal: thermal, measured: measured)356 let status = statuses[row.id].flatMap { $0.phase == .completed || $0.phase == .cancelled ? nil : $0 }357 let goals = recommended[row.id] ?? []358 out.append(LocalModelEntry(card: row.card, categories: categories, isInstalled: row.isInstalled, isLoaded: snapshot.isLoaded(row.id),359 updateAvailable: row.updateAvailable, isRecommended: !goals.isEmpty, recommendedFor: goals, compatibility: compatibility,360 loadDecision: await governor.decision(for: row.card), download: status, bytesOnDisk: store.bytesOnDisk(id: row.id),361 measurement: measured.first { $0.modelID == row.id }))362 }363 return out364 }365366 public func entry(id: String) async -> LocalModelEntry? { await entries().first { $0.id == id } }367368 public func installed() async -> [LocalModelEntry] { await entries(installedOnly: true) }369370 /// The models ORIX Astra's advisor picks for this Mac, one per category that has a suitable model, in category order.371 public func recommended() async -> [LocalModelEntry] {372 let all = await entries()373 return all.filter(\.isRecommended).sorted { ($0.recommendedFor.first?.rawValue ?? "", $0.id) < ($1.recommendedFor.first?.rawValue ?? "", $1.id) }374 }375376 /// The advisor's full answer for one category on this Mac: the pick, the alternatives, the score components and the exclusions.377 public func recommendation(for category: LocalModelCategory) async -> Recommendation? {378 guard let goal = category.goal else { return nil }379 let registry = registry()380 return ModelAdvisor.recommend(goal: goal, candidates: registry.models, installed: Set(registry.installed.map(\.id)), device: device,381 measurements: measurements(loadedMetrics: engine.monitor.history), memory: readMemory(), thermal: readThermal())382 }383384 private func recommendations(registry: ModelRegistry, installed: Set<String>, measured: [ModelMeasurement], reading: MemoryReading,385 thermal: ThermalLevel) -> [String: [LocalModelCategory]] {386 var out: [String: [LocalModelCategory]] = [:]387 for category in LocalModelCategory.allCases {388 guard let goal = category.goal else { continue }389 let answer = ModelAdvisor.recommend(goal: goal, candidates: registry.models, installed: installed, device: device, measurements: measured,390 memory: reading, thermal: thermal)391 if let pick = answer.primary { out[pick.id, default: []].append(category) }392 }393 return out394 }395396 // MARK: Downloads397398 private func card(_ id: String) throws -> LocalModelCard {399 guard let card = catalog.card(id: id) ?? store.card(id: id) else { throw LocalModelLibraryError.unknownModel(id) }400 return card401 }402403 /// Starts or continues the download of a catalogue model. Files land in a staging folder; each is checked against its SHA-256;404 /// the model appears as installed only when all of them matched, in one rename. Throws when the disk is too full or the405 /// model is already downloading.406 @discardableResult407 public func download(_ id: String) async throws -> DownloadStatus {408 try await downloads.start(DownloadPlan(card: try card(id)))409 }410 public func pauseDownload(_ id: String) async { await downloads.pause(id: id) }411 public func resumeDownload(_ id: String) async throws { try await downloads.resume(id: id) }412 public func retryDownload(_ id: String) async throws { try await downloads.retry(id: id) }413 /// Stops the download and deletes what it wrote. An installed version of the model is left alone.414 public func cancelDownload(_ id: String) async { await downloads.cancel(id: id) }415 public func downloadStatus(_ id: String) async -> DownloadStatus? { await downloads.status(id: id) }416 /// Progress of every download, on each change.417 public nonisolated func downloadUpdates() async -> AsyncStream<[DownloadStatus]> { await downloads.updates() }418 /// Waits until the download is no longer active and returns its final status.419 public nonisolated func waitForDownload(_ id: String) async -> DownloadStatus? { await downloads.waitUntilSettled(id: id) }420421 // MARK: Integrity, repair, removal422423 /// Re-hashes every file of an installed model against the checksums recorded at install time. Read-only.424 public nonisolated func verifyInstalled(_ id: String) async -> InstalledVerification { await downloads.verifyInstalled(id: id) }425426 /// Downloads again whatever is damaged or missing; intact files are reused and the folder is replaced in one step.427 @discardableResult428 public func repair(_ id: String) async throws -> DownloadStatus { try await downloads.repair(id: id) }429430 /// Downloads the version the catalogue pins and swaps it in when it is completely verified.431 @discardableResult432 public func update(_ id: String) async throws -> DownloadStatus {433 try await downloads.start(DownloadPlan(card: try card(id)))434 }435436 /// Unloads the model if needed, cancels its download and deletes its files. Returns the bytes freed.437 @discardableResult438 public func remove(_ id: String) async throws -> Int64 {439 await engine.unload(id)440 await downloads.cancel(id: id)441 await downloads.forget(id: id)442 return try store.remove(id: id)443 }444445 public func storage() -> Storage {446 Storage(root: store.root, usedBytes: store.totalBytesOnDisk(), availableBytes: store.availableDiskBytes(), installedCount: store.installed().count)447 }448449 // MARK: Load, unload450451 public enum BusyPolicy: Sendable, Hashable {452 /// Throw `LocalModelLibraryError.memory` with the decision when heavy document work defers the load.453 case fail454 /// Wait for the document work to end, then decide again.455 case waitForDocumentWork456 }457458 /// Loads an installed model into memory. The editor-aware governor decides first: a model that would take memory the document459 /// needs is refused with the numbers (`LocalModelLibraryError.memory`); `force` skips that check and ORIX Astra's own.460 @discardableResult461 public func load(_ id: String, whenBusy: BusyPolicy = .waitForDocumentWork, force: Bool = false) async throws -> LoadedModelInfo {462 guard store.isInstalled(id), let card = store.installedCard(id: id) else { throw LocalModelLibraryError.notInstalled(id) }463 if let info = await engine.loadedInfo(id) { return info }464 if !force {465 var decision = await governor.decision(for: card)466 if decision.verdict == .deferUntilDocumentWorkEnds, whenBusy == .waitForDocumentWork {467 await governor.waitForDocumentWork()468 try Task.checkCancellation()469 decision = await governor.decision(for: card)470 }471 guard decision.mayLoadNow else { throw LocalModelLibraryError.memory(decision) }472 }473 return try await engine.load(id, force: force)474 }475476 public func unload(_ id: String) async { await engine.unload(id) }477 public func unloadAll() async { await engine.unloadAll() }478 public func loadedModels() async -> [LoadedModelInfo] { await engine.snapshot().loaded }479 /// The engine's state (phase, loaded models, running generation, memory, thermal level), now and on each change.480 public nonisolated func engineSnapshots() async -> AsyncStream<LocalEngine.Snapshot> { await engine.snapshots() }481482 // MARK: Generation483484 /// Streams one answer from an on-device model (`request.model.provider == .mlx`). The model is loaded on first use through485 /// `load`, so the memory governor is always consulted. Cancelling the consuming task stops the generation; the stream then486 /// ends by throwing `AstraError.cancelled` (ORIX Astra's contract). Nothing here can reach a cloud provider.487 public nonisolated func generate(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> {488 guard request.model.provider == .mlx else {489 return AsyncThrowingStream { $0.finish(throwing: AstraError.invalidRequest("This request is not for an on-device MLX model.")) }490 }491 return AsyncThrowingStream { continuation in492 let task = Task {493 do {494 try await self.load(request.model.modelID)495 for try await event in self.engine.generate(request) { continuation.yield(event) }496 continuation.finish()497 } catch let error as LocalModelLibraryError {498 continuation.finish(throwing: AstraError.local(error.errorDescription ?? "The model could not be loaded."))499 } catch {500 continuation.finish(throwing: Task.isCancelled ? AstraError.cancelled : error)501 }502 }503 continuation.onTermination = { _ in task.cancel() }504 }505 }506507 /// Stops the running generation, if any, and waits until it has really stopped.508 public func cancelGeneration() async { await engine.cancelActiveGeneration() }509510 /// Figures measured during the generations of this session (tokens per second, time to first token, peak memory).511 public nonisolated var generationMetrics: [LocalGenerationMetrics] { engine.monitor.history }512513 // MARK: Hub and router514515 /// The `ChatProvider` to register in `ProviderHub`: lists installed models, generates through this library.516 public nonisolated var chatProvider: any ChatProvider { LibraryMLXProvider(library: self) }517518 /// Installed models as router candidates: memory need from the governor, loaded state, size class, languages, measured speed.519 public func routeCandidates() async -> [RouteCandidate] {520 await entries(installedOnly: true).map { entry in521 RouteCandidate(model: entry.card.modelInfo(source: .runtime), providerName: ProviderKind.mlx.displayName,522 unavailableReason: entry.compatibility.compatibility == .unsupported ? entry.compatibility.headline : nil,523 tokensPerSecond: entry.measurement?.tokensPerSecond, timeToFirstToken: entry.measurement?.timeToFirstToken,524 requiredMemoryBytes: entry.estimatedMemoryBytes, isLoaded: entry.isLoaded, tier: ModelTier.forParameters(entry.parameterCount),525 languages: entry.card.hasTag(ModelTag.multilingual) ? nil : ["en"])526 }527 }528}529530/// MLX provider for the hub. Same listing and availability rules as ORIX Astra's `MLXProvider`, but generation goes through the531/// library so that every implicit load passes the editor-aware memory governor.532struct LibraryMLXProvider: ChatProvider {533 let kind: ProviderKind = .mlx534 let library: LocalModelLibrary535 private var astra: MLXProvider { MLXProvider(engine: library.engine) }536537 func listModels() async throws -> [ModelInfo] { try await astra.listModels() }538 func verify() async throws -> ConnectionStatus { try await astra.verify() }539 func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> {540 if let reason = MLXAvailability.unavailableReason { return AsyncThrowingStream { $0.finish(throwing: AstraError.unsupported(reason)) } }541 return library.generate(request)542 }543}544