// // SettingsModel.swift // Museion // // #135 (Profiles S2): the Settings page's in-memory model + the injectable // write-path protocol. Per ADR-0014 the per-surface model block IS each // Hermes profile's `model:` block and provider keys fan out to every // profile on that provider — persistence lands with S3 over this seam; // S2 ships a no-op writer. // import Foundation import Observation /// The three providers Settings offers (#135). Raw values are Hermes' own /// provider slugs (`CANONICAL_PROVIDERS`) — the same ids key the registry /// cache; OpenAI's slug is `openai-api`. nonisolated enum ModelProvider: String, CaseIterable, Sendable { case zai case anthropic case openaiAPI = "openai-api" var label: String { switch self { case .zai: "z.ai" case .anthropic: "Anthropic" case .openaiAPI: "OpenAI" } } /// #128: the per-provider ladders Hermes clamps per route — one /// `model.reasoning_effort` key, surfaced per provider. var effortOptions: [ReasoningEffort] { switch self { case .zai: [.low, .high, .max] case .anthropic, .openaiAPI: [.low, .medium, .high, .xhigh, .max] } } /// The model a provider switch lands on (prototype #130's pinned /// flagships — registry order is capability-sorted, not default-sorted). var switchDefaultModel: String { switch self { case .zai: "glm-5.3" case .anthropic: "claude-sonnet-5" case .openaiAPI: "gpt-5.6-sol" } } /// Default endpoint families (factsheet §1; z.ai's is key-type keyed). var defaultEndpoint: String { switch self { case .zai: ZaiKeyType.standard.endpoint case .anthropic: "https://api.anthropic.com" case .openaiAPI: "https://api.openai.com/v1" } } } nonisolated enum ReasoningEffort: String, CaseIterable, Sendable, Equatable { case low case medium case high case xhigh case max } /// z.ai's two key types pick the endpoint family (factsheet §1.1) — coding /// plan keys are distribution-restricted; shipped Museion uses standard. nonisolated enum ZaiKeyType: String, CaseIterable, Sendable { case standard case coding var endpoint: String { switch self { case .standard: "https://api.z.ai/api/paas/v4" case .coding: "https://api.z.ai/api/coding/paas/v4" } } var label: String { switch self { case .standard: "Standard (pay-as-you-go)" case .coding: "Coding plan" } } } /// One surface's model block — what Settings edits and S3 persists via the /// write path (the profile's `model:` block). nonisolated struct SurfaceModelConfig: Equatable, Sendable { var provider: ModelProvider var model: String /// nil = unset · provider default (the key is simply not written). var effort: ReasoningEffort? /// The #132 fresh-seed posture: sonnet on all three surfaces, effort /// unset. Never copied from the live museion profile. static let surfaceDefault = SurfaceModelConfig( provider: .anthropic, model: ProfileSurface.defaultModelID, effort: nil, ) } /// One provider's key block — endpoint (base URL) + API key. One key per /// provider fans out to every profile on that provider (#131: no Keychain). nonisolated struct ProviderKeyConfig: Equatable, Sendable { var endpoint: String var apiKey: String = "" } /// Hermes' own picker cache (`~/.hermes/provider_models_cache.json`) — zero /// HTTP, exactly what Hermes accepts (ADR-0014). Lenient by design: a /// missing, unreadable, or foreign-shaped file leaves every model free-text /// (all custom), which is the picker's first-class mode anyway. nonisolated struct ModelRegistry: Sendable { var models: [ModelProvider: [String]] = [:] func list(for provider: ModelProvider) -> [String] { models[provider] ?? [] } /// Cache shape: `{provider: {fp, at, models: [ids]}}`. Lenient per the /// DECODE, not per entry: unknown provider slugs are skipped, but any /// foreign shape inside a known provider's entry (a non-string models /// element) fails the whole decode and the registry degrades to /// free-text-only — the picker's first-class mode anyway. static func load(path: String = ("~/.hermes/provider_models_cache.json" as NSString).expandingTildeInPath) -> ModelRegistry { guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { return ModelRegistry() } struct Entry: Decodable { let models: [String]? } guard let parsed = try? JSONDecoder().decode([String: Entry].self, from: data) else { return ModelRegistry() } var registry = ModelRegistry() for (slug, entry) in parsed { if let provider = ModelProvider(rawValue: slug) { registry.models[provider] = entry.models ?? [] } } return registry } /// The default load, memoized — `SettingsModel()` runs its default /// arguments on every SwiftUI construction of the pane, so the disk read /// + decode must happen once. ponytail: refreshed on next launch, not /// live; S3 lifts persistence anyway. static let loadedDefault = ModelRegistry.load() } /// The write-path seam (#135). S3 implements this against the Hermes CLI /// (`hermes -p config set` for the model block, `.env` fan-out /// for provider keys — ADR-0014); implementations own batching/debounce and /// hop off-main internally when the rail needs it. Contract for implementers /// (finish-audit #135): in-flight edits are TENTATIVE — implementations MUST /// debounce writes (the key field fires per keystroke; persisting every /// partial prefix of a secret to `.env` leaks key material through later /// overwrites). Secrets travel via stdin or the child's environment, never /// argv (`ps` reads live command lines), and surfaced error text must be /// redacted of key-bearing content (lastWriteError renders verbatim). @MainActor protocol SettingsWriting { func writeSurface(_ surface: ProfileSurface, config: SurfaceModelConfig) async throws func writeProviderKey(provider: ModelProvider, config: ProviderKeyConfig, keyType: ZaiKeyType?) async throws } /// S2's inert writer: persistence is S3's job; the UI runs over the /// in-memory model meanwhile. struct NoopSettingsWriter: SettingsWriting { func writeSurface(_: ProfileSurface, config _: SurfaceModelConfig) async throws {} func writeProviderKey(provider _: ModelProvider, config _: ProviderKeyConfig, keyType _: ZaiKeyType?) async throws {} } /// The Settings page's state (#135): per-surface model configs, per-provider /// keys, the registry the model combobox reads, and the write path every /// committed change flows through. Pane-local for S2 — S3 lifts it to /// AppGateState when persistence lands. @MainActor @Observable final class SettingsModel { private(set) var surfaces: [ProfileSurface: SurfaceModelConfig] private(set) var keys: [ModelProvider: ProviderKeyConfig] private(set) var zaiKeyType: ZaiKeyType = .standard private(set) var registry: ModelRegistry /// Write failures land here — the honest strip (S3's rail can fail). private(set) var lastWriteError: String? private let writer: any SettingsWriting init( registry: ModelRegistry = .loadedDefault, writer: any SettingsWriting = NoopSettingsWriter(), surfaces: [ProfileSurface: SurfaceModelConfig]? = nil, ) { self.registry = registry self.writer = writer self.surfaces = surfaces ?? Dictionary(uniqueKeysWithValues: ProfileSurface.allCases.map { ($0, .surfaceDefault) }) keys = Dictionary( uniqueKeysWithValues: ModelProvider.allCases.map { ($0, ProviderKeyConfig(endpoint: $0.defaultEndpoint)) }, ) } func config(for surface: ProfileSurface) -> SurfaceModelConfig { var config = surfaces[surface] ?? .surfaceDefault // Read-boundary clamp: a config hydrated with an effort outside the // provider's ladder (S3 reads hand-edited config.yaml files) must not // render a blank menu selection. The stored value is untouched — the // next mutation writes a clamped copy. if let effort = config.effort, !config.provider.effortOptions.contains(effort) { config.effort = nil } return config } func keyConfig(for provider: ModelProvider) -> ProviderKeyConfig { keys[provider] ?? ProviderKeyConfig(endpoint: provider.defaultEndpoint) } /// True when the model id isn't in Hermes' registry for its provider — /// claude-sonnet-5-5 (the #132 seed) is NOT in the cache, so custom is /// the DEFAULT state, not an edge case. func isCustom(_ surface: ProfileSurface) -> Bool { let config = config(for: surface) return !registry.list(for: config.provider).contains(config.model) } /// A provider switch lands on that provider's pinned default model with /// effort reset (each provider's ladder differs; the writer should see /// intent, not residue). func setProvider(_ provider: ModelProvider, for surface: ProfileSurface) { var config = config(for: surface) guard config.provider != provider else { return } config.provider = provider config.model = provider.switchDefaultModel config.effort = nil surfaces[surface] = config persist(surface, config) } func setModel(_ model: String, for surface: ProfileSurface) { let trimmed = model.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return } var config = config(for: surface) guard config.model != trimmed else { return } config.model = trimmed surfaces[surface] = config persist(surface, config) } func setEffort(_ effort: ReasoningEffort?, for surface: ProfileSurface) { var config = config(for: surface) guard config.effort != effort else { return } config.effort = effort surfaces[surface] = config persist(surface, config) } /// Back to the #132 seed (sonnet, effort unset) — the page's Restore /// Defaults button. No-op when already there; a real reset persists. func resetToDefault(for surface: ProfileSurface) { guard config(for: surface) != .surfaceDefault else { return } surfaces[surface] = .surfaceDefault persist(surface, .surfaceDefault) } /// z.ai's key type picks the endpoint family (factsheet §1). A custom /// endpoint survives the toggle; a family default (or empty) swaps. func setZaiKeyType(_ type: ZaiKeyType) { guard zaiKeyType != type else { return } zaiKeyType = type let endpoint = keyConfig(for: .zai).endpoint if endpoint.isEmpty || ZaiKeyType.allCases.contains(where: { $0.endpoint == endpoint }) { keys[.zai]?.endpoint = type.endpoint } persistKey(.zai) } func setEndpoint(_ endpoint: String, for provider: ModelProvider) { guard keys[provider]?.endpoint != endpoint else { return } keys[provider]?.endpoint = endpoint persistKey(provider) } func setAPIKey(_ key: String, for provider: ModelProvider) { guard keys[provider]?.apiKey != key else { return } keys[provider]?.apiKey = key persistKey(provider) } /// Fire-and-forget: the UI never blocks on writes; failures surface in /// `lastWriteError` (LearningsPane's strip posture), cleared by the next /// SUCCESSFUL write — not optimistically at commit. /// ponytail: interleaved writes are unordered — an older write failing /// after a newer one succeeded leaves its error up; a write-generation /// token fixes it if S3's real writers ever interleave. private var pendingWrites: [Task] = [] /// Awaits in-flight writes — the tests' deterministic sync point. func awaitPendingWrites() async { for task in pendingWrites { await task.value } pendingWrites.removeAll() } // ponytail: finished tasks are only reference-hygiene; cap, don't track. private func track(_ task: Task) { pendingWrites.append(task) if pendingWrites.count > 64 { pendingWrites.removeFirst(pendingWrites.count - 64) } } private func persist(_ surface: ProfileSurface, _ config: SurfaceModelConfig) { track(Task { do { try await writer.writeSurface(surface, config: config) lastWriteError = nil } catch { lastWriteError = error.localizedDescription } }) } private func persistKey(_ provider: ModelProvider) { let config = keyConfig(for: provider) let keyType = provider == .zai ? zaiKeyType : nil track(Task { do { try await writer.writeProviderKey(provider: provider, config: config, keyType: keyType) lastWriteError = nil } catch { lastWriteError = error.localizedDescription } }) } }