import Foundation import SprachmittlerEngines import SprachmittlerOllama import SprachmittlerText /// The documented prompt policy. `contentAware` is reserved for M7. public enum PromptVariantPolicy: String, Codable, Sendable, Equatable { /// Default Translation only (v1). case defaultOnly /// Content-aware prompt selection (reserved for M7). case contentAware } /// The versioned, text-free application settings from `docs/ARCHITECTURE.md` §12. public struct AppSettings: Codable, Sendable, Equatable { /// The loopback default endpoint; a compile-time constant. public static let defaultEndpoint = URL(string: "http://127.0.0.1:11434")! /// The current settings schema version. public static let currentVersion = 1 /// Ollama base URL. public var endpoint: URL /// Whether a non-loopback endpoint is allowed (HTTPS only). public var allowRemoteEndpoint: Bool /// The selected Hy-MT3 model tag. public var model: String /// The optional Fast model tag. public var fastModel: String? /// The mother tongue BCP-47 code; the default target when no rule matches. public var targetLanguage: String /// Source-language to target-language rules. Empty means everything goes to the mother tongue. public var languageRoutes: [LanguageRoute] /// Up to three recent target codes, most recent first. public var recentTargetLanguages: [String] /// The double-copy window in milliseconds (300–1000). public var doubleCopyWindowMs: Int /// The Latin/Cyrillic/Greek chunk limit. public var maxCharactersLatin: Int /// The dense-script chunk limit. public var maxCharactersCJK: Int /// `num_ctx`. public var numCtx: Int /// `num_predict`. public var numPredict: Int /// `temperature`. public var temperature: Double /// `top_p`. public var topP: Double /// `top_k`. public var topK: Int /// `repeat_penalty`. public var repeatPenalty: Double /// `keep_alive` value: `5m`, `30m`, `1h` or `0`. public var keepModelLoaded: String /// Warm the model after launch (loopback only). public var warmUpOnLaunch: Bool /// Prompt policy; `defaultOnly` in v1. public var promptVariantPolicy: PromptVariantPolicy /// Always false; never copy automatically. public var autoCopy: Bool /// Show the source preview in the panel. public var showSourcePreview: Bool /// Translation text size in points (12–28). public var translationFontSize: Int /// Render Markdown formatting in the translation panel. public var renderMarkdown: Bool /// Make the panel key when shown so Esc and the shortcuts work without a click. public var closeWithEscape: Bool /// Reflect the login-item setting. public var launchAtLogin: Bool /// Keep the last translation in memory for the panel. public var keepRecentTranslationInMemory: Bool /// Whether first-run onboarding has been completed. public var hasCompletedOnboarding: Bool /// The settings schema version. public var settingsVersion: Int /// Creates the defaults. The system language becomes the target when supported. public init() { let systemCode = Locale.preferredLanguages.first.flatMap { HyMT3Languages.resolve($0)?.code } endpoint = Self.defaultEndpoint allowRemoteEndpoint = false model = HyMT3ModelPreset.defaultModel fastModel = HyMT3ModelPreset.fastModel targetLanguage = systemCode ?? HyMT3Languages.english.code languageRoutes = [] recentTargetLanguages = [] doubleCopyWindowMs = 500 maxCharactersLatin = 4000 maxCharactersCJK = 2000 numCtx = 8192 numPredict = 4096 temperature = 0.7 topP = 0.6 topK = 20 repeatPenalty = 1.05 keepModelLoaded = HyMT3ModelPreset.defaultKeepAlive warmUpOnLaunch = true promptVariantPolicy = .defaultOnly autoCopy = false showSourcePreview = true translationFontSize = 17 renderMarkdown = true closeWithEscape = true launchAtLogin = false keepRecentTranslationInMemory = true hasCompletedOnboarding = false settingsVersion = Self.currentVersion } /// The target language value, always a catalogue entry. public var targetLanguageModel: ModelLanguage { HyMT3Languages.resolve(targetLanguage) ?? HyMT3Languages.english } /// The recent targets that still exist in the catalogue. public var recentTargets: [ModelLanguage] { recentTargetLanguages.compactMap(HyMT3Languages.resolve) } /// Validates the configured endpoint against the remote policy. public func validatedEndpoint() throws -> URL { try EndpointPolicy.validate(endpoint, allowRemote: allowRemoteEndpoint) } /// Records a target as recent, keeping at most three unique codes. public mutating func noteTarget(_ language: ModelLanguage) { targetLanguage = language.code recentTargetLanguages.removeAll { $0 == language.code } recentTargetLanguages.insert(language.code, at: 0) recentTargetLanguages = Array(recentTargetLanguages.prefix(3)) } /// Clamps values edited outside the decoder (Settings UI) to the safe ranges. public mutating func sanitize() { targetLanguage = HyMT3Languages.resolve(targetLanguage)?.code ?? HyMT3Languages.english.code languageRoutes = Self.normalizedRoutes(languageRoutes) doubleCopyWindowMs = Self.clamp(doubleCopyWindowMs, to: 300 ... 1000) maxCharactersLatin = Self.clamp(maxCharactersLatin, to: 500 ... 10000) maxCharactersCJK = Self.clamp(maxCharactersCJK, to: 500 ... 5000) numCtx = Self.clamp(numCtx, to: 1024 ... 32768) numPredict = Self.clamp(numPredict, to: 1 ... 8192) temperature = min(max(temperature, 0), 2) topP = min(max(topP, 0), 1) topK = Self.clamp(topK, to: 1 ... 100) repeatPenalty = min(max(repeatPenalty, 0.5), 2) translationFontSize = Self.clamp(translationFontSize, to: 12 ... 28) if !["5m", "30m", "1h", "0"].contains(keepModelLoaded) { keepModelLoaded = HyMT3ModelPreset.defaultKeepAlive } autoCopy = false } /// The documented sampling values as an options value. public var samplingOptions: SamplingOptions { SamplingOptions( temperature: temperature, topP: topP, topK: topK, repeatPenalty: repeatPenalty, numPredict: numPredict, numCtx: numCtx ) } /// The chunker limits. public var chunker: Chunker { Chunker(latinLimit: maxCharactersLatin, denseLimit: maxCharactersCJK) } struct DecodedLimits { let window: Int let latin: Int let cjk: Int let numCtx: Int let numPredict: Int let fontSize: Int } struct DecodedSampling { let temperature: Double let topP: Double let topK: Int let repeatPenalty: Double } static func decodeLimits( from container: KeyedDecodingContainer, defaults: AppSettings ) throws -> DecodedLimits { try DecodedLimits( window: clamp( container.decodeIfPresent(Int.self, forKey: .doubleCopyWindowMs) ?? defaults.doubleCopyWindowMs, to: 300 ... 1000 ), latin: clamp( container.decodeIfPresent(Int.self, forKey: .maxCharactersLatin) ?? defaults.maxCharactersLatin, to: 500 ... 10000 ), cjk: clamp( container.decodeIfPresent(Int.self, forKey: .maxCharactersCJK) ?? defaults.maxCharactersCJK, to: 500 ... 5000 ), numCtx: clamp( container.decodeIfPresent(Int.self, forKey: .numCtx) ?? defaults.numCtx, to: 1024 ... 32768 ), numPredict: clamp( container.decodeIfPresent(Int.self, forKey: .numPredict) ?? defaults.numPredict, to: 1 ... 8192 ), fontSize: clamp( container.decodeIfPresent(Int.self, forKey: .translationFontSize) ?? defaults.translationFontSize, to: 12 ... 28 ) ) } static func decodeSampling( from container: KeyedDecodingContainer, defaults: AppSettings ) throws -> DecodedSampling { let temperature = try container.decodeIfPresent(Double.self, forKey: .temperature) ?? defaults.temperature let topP = try container.decodeIfPresent(Double.self, forKey: .topP) ?? defaults.topP let repeatPenalty = try container.decodeIfPresent(Double.self, forKey: .repeatPenalty) ?? defaults.repeatPenalty return try DecodedSampling( temperature: min(max(temperature, 0), 2), topP: min(max(topP, 0), 1), topK: clamp( container.decodeIfPresent(Int.self, forKey: .topK) ?? defaults.topK, to: 1 ... 100 ), repeatPenalty: min(max(repeatPenalty, 0.5), 2) ) } enum CodingKeys: String, CodingKey { case endpoint, allowRemoteEndpoint, model, fastModel, targetLanguage, languageRoutes case recentTargetLanguages case doubleCopyWindowMs, maxCharactersLatin, maxCharactersCJK, numCtx, numPredict case temperature, topP, topK, repeatPenalty, keepModelLoaded, warmUpOnLaunch case promptVariantPolicy, autoCopy, showSourcePreview, translationFontSize, renderMarkdown case closeWithEscape, launchAtLogin, keepRecentTranslationInMemory, hasCompletedOnboarding case settingsVersion } static func normalizedRoutes(_ routes: [LanguageRoute]) -> [LanguageRoute] { var seen = Set() return routes.compactMap { route in guard let source = HyMT3Languages.resolve(route.source)?.code, let target = HyMT3Languages.resolve(route.target)?.code, source.caseInsensitiveCompare(target) != .orderedSame, seen.insert(source.lowercased()).inserted else { return nil } return LanguageRoute(source: source, target: target) } } static func clamp(_ value: Int, to range: ClosedRange) -> Int { min(max(value, range.lowerBound), range.upperBound) } }