// // 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. // // #136 (Profiles S3): the real write path — HermesSettingsWriter (CLI // rail + .env fan-out) is the production writer; the model hydrates from // the profiles at pane open, COALESCES rapid edits per target (the key // field fires per keystroke — a superseded write is canceled before it // ever spawns, so partial key prefixes never reach `.env`), and runs the // Test Connection probe per provider. // // swiftlint:disable file_length // One Settings model, one write story: state, hydration, coalescing, and // the #137 restart hook read as one unit; a page-per-file split follows if // the file keeps growing. import Foundation import Observation /// The providers Settings offers (#135; Nous Portal #175). 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" case nous var label: String { switch self { case .zai: "z.ai" case .anthropic: "Anthropic" case .openaiAPI: "OpenAI" case .nous: "Nous Portal" } } /// #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, .nous: [.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; /// #136 dogfood: OpenAI's flagship is gpt-6.1-sol, the current /// Responses-era default). #175: the portal's catalog is the /// vendor-prefixed router list — the switch keeps the app's sonnet /// posture (live-probed: `anthropic/claude-sonnet-5` generates). var switchDefaultModel: String { switch self { case .zai: "glm-5.3" case .anthropic: "claude-sonnet-5" case .openaiAPI: "gpt-6.1-sol" case .nous: "anthropic/claude-sonnet-5" } } /// Default endpoint families (factsheet §1; z.ai's is key-type keyed). /// #175: the Nous Portal inference API (portal.nousresearch.com/api-docs). var defaultEndpoint: String { switch self { case .zai: ZaiKeyType.standard.endpoint case .anthropic: "https://api.anthropic.com" case .openaiAPI: "https://api.openai.com/v1" case .nous: "https://inference-api.nousresearch.com/v1" } } /// #136: the `.env` var Hermes' own provider registry maps each slug to /// (`hermes_cli/auth.py` live-read): zai→GLM_API_KEY (ZAI_/Z_AI_ are /// aliases), anthropic→ANTHROPIC_API_KEY, openai-api→OPENAI_API_KEY, /// nous→NOUS_API_KEY (the plugin profile's env var — the engine's model /// auth rides the Portal login, the key bills the same account credits). var envVarName: String { switch self { case .zai: "GLM_API_KEY" case .anthropic: "ANTHROPIC_API_KEY" case .openaiAPI: "OPENAI_API_KEY" case .nous: "NOUS_API_KEY" } } /// #181: the wire family the probe speaks. The SELECTOR is data — /// endpoint paths, auth shape, and the SSE decoder pick ride the /// dialect; the per-family code (request bodies, stream decoders) /// stays separate functions, not switch clothing. nonisolated enum Dialect: Sendable { /// Anthropic `/v1/messages`, header-key auth, Anthropic SSE. case anthropic /// OpenAI Responses `/responses`, Bearer, Responses SSE. case responses /// OpenAI chat-completions (`/chat/completions` — z.ai and the /// Nous Portal), Bearer, chat-completions SSE. case chatCompletions /// The chat-call path appended to the endpoint base (callers trim /// a trailing slash off the base first). var chatPath: String { switch self { case .anthropic: "/v1/messages" case .responses: "/responses" case .chatCompletions: "/chat/completions" } } var modelsPath: String { switch self { case .anthropic: "/v1/models" case .responses, .chatCompletions: "/models" } } } /// #181: the provider's wire family (the probe's dialect selector). var dialect: Dialect { switch self { case .zai, .nous: .chatCompletions case .anthropic: .anthropic case .openaiAPI: .responses } } /// #181: the auth-header shape (factsheet §2.1) — Bearer everywhere /// except Anthropic's `x-api-key` + a pinned `anthropic-version` /// (never send none). nonisolated enum AuthMode: Sendable { /// `Authorization: Bearer `. case bearer /// `x-api-key: ` plus the pinned version header. case headerKey(version: String) } var authMode: AuthMode { switch self { case .zai, .openaiAPI, .nous: .bearer case .anthropic: .headerKey(version: "2023-06-01") } } /// #175: keyless providers run on the shared Hermes Portal login — /// the engine's own credential stands in when no API key is pasted /// (API key and subscription bill the same account credits). var keyless: Bool { self == .nous } /// The endpoint with any trailing slash trimmed — the ONE /// normalization every endpoint consumer (the probe's URL builders, /// the credential rail's official-endpoint gate) compares against; /// divergent trims would gate or route differently in silence. nonisolated static func trimmedEndpoint(_ endpoint: String) -> String { endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint } } 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 = "" } /// #175: the shared Portal session's inference key from the Hermes auth /// store (`~/.hermes/auth.json` — where the device-code login's agent_key /// lives; profiles inherit it via the shared nous state). This is the /// credential the engine itself runs nous on (API key and subscription /// bill the same account credits). Read-only and lenient: a missing or /// foreign-shaped store is nil, never an error. Nonisolated so the model's /// fallback can read it off-main. /// ponytail: agent_key_expires_at is not checked — a stale key probes /// honestly (the portal's 401 decodes authFailed); parse the expiry if a /// stale-key verdict ever misleads. nonisolated enum PortalAuth { static let defaultAuthPath = ("~/.hermes/auth.json" as NSString).expandingTildeInPath static func sessionKey(authJSONPath: String = defaultAuthPath) -> String? { guard let data = try? Data(contentsOf: URL(fileURLWithPath: authJSONPath)), let parsed = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let providers = parsed["providers"] as? [String: Any], let nous = providers["nous"] as? [String: Any], let agentKey = (nous["agent_key"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines), !agentKey.isEmpty else { return nil } return agentKey } } /// #181: THE credential resolution — the provider's own API key, else the /// shared Portal session key for keyless providers. Settings' Test /// Connection and pass readiness both call this ONE function, so the /// fallback can no longer drift between them. The implicit session /// credential only ever rides the OFFICIAL endpoint (#175 finish-audit: /// cleartext http / foreign host = silent exfiltration with no on-screen /// cue) — a keyless provider on any other endpoint refuses with the /// paste-a-key path. Nonisolated async, so the auth-store read never runs /// on the main actor. nonisolated enum ProviderCredential { enum Resolved: Equatable { case key(String) case refused(String) } static func resolve( provider: ModelProvider, envKey: String, endpoint: String, portalAuthPath: String, ) async -> Resolved { if !envKey.isEmpty { return .key(envKey) } guard provider.keyless else { return .refused("no API key set — paste the key first") } let trimmed = ModelProvider.trimmedEndpoint(endpoint) guard trimmed == provider.defaultEndpoint else { return .refused("custom endpoint — paste an API key to test it (the Portal session key stays on the official endpoint)") } guard let sessionKey = PortalAuth.sessionKey(authJSONPath: portalAuthPath) else { return .refused("no key set and no Hermes Portal login — paste a key or run `hermes auth add nous`") } return .key(sessionKey) } } /// 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. #136: hydrated from the profiles at pane /// open; pane-local still — the AppGateState lift waits on the /// restart-on-change slice. @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 (the CLI rail can fail). private(set) var lastWriteError: String? /// #136: Test Connection state per provider (the Provider Keys page). private(set) var testStates: [ModelProvider: TestState] = [:] private let writer: any SettingsWriting /// #175: injected so the nous Test Connection tests run offline. private let probeTransport: ProviderProbe.Transport /// #175: the shared Hermes auth store — the nous fallback's agent_key. private let portalAuthPath: String /// #137 (S4): fired after a SUCCESSFUL chat-surface write ONLY — the /// resident chat engine restarts to read the new model block /// (WorkspaceView wires it to MentorSessionModel.requestRestart). /// Never on failure (lastWriteError path), never for pass surfaces /// (their engines are one-shot), never for key writes. var onChatSurfaceWrite: (() -> Void)? /// Rapid edits per target coalesce: a newer write cancels the older /// task during its debounce window (the key field fires per keystroke — /// a partial prefix of a secret must never reach `.env`). Tests pass 0. private let writeDebounce: TimeInterval private var surfaceTasks: [ProfileSurface: Task] = [:] private var keyTasks: [ModelProvider: Task] = [:] init( registry: ModelRegistry = .loadedDefault, writer: any SettingsWriting = NoopSettingsWriter(), surfaces: [ProfileSurface: SurfaceModelConfig]? = nil, writeDebounce: TimeInterval = 0.35, probeTransport: @escaping ProviderProbe.Transport = ProviderProbe.urlSessionTransport, portalAuthPath: String = PortalAuth.defaultAuthPath, ) { self.registry = registry self.writer = writer self.writeDebounce = writeDebounce self.probeTransport = probeTransport self.portalAuthPath = portalAuthPath 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) } /// #136: hydration — each profile's live `model:` block, read in /// parallel through the writer's CLI rail (format owned by Hermes). /// Surfaces on providers Settings doesn't offer stay seeded (their /// config is the user's, not ours to rewrite); a z.ai profile pinned to /// the coding endpoint infers the key type. Keys persist in the /// fanned-out `.env` files — they're read back too, so a restart /// neither blanks the fields nor refuses Test Connection. Reads only — /// hydrate never writes. func hydrate() async { let writer = writer await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in for surface in ProfileSurface.allCases { group.addTask { await (surface, try? writer.readSurface(surface)) } } for await (surface, read) in group { guard let read else { continue } // An edit that fired while this read was in flight owns the // truth — applying the stale read would revert the UI and // the next edit would persist from the stale base. guard surfaceTasks[surface] == nil else { continue } surfaces[surface] = read.config if read.config.provider == .zai { if read.baseURL == ZaiKeyType.coding.endpoint { zaiKeyType = .coding keys[.zai]?.endpoint = ZaiKeyType.coding.endpoint } else if let baseURL = read.baseURL, !baseURL.isEmpty, baseURL != ZaiKeyType.standard.endpoint { // A custom zai base_url (hand-edited, or a family // Settings doesn't model) survives hydration — the // next zai write-through threads it, never a default. keys[.zai]?.endpoint = baseURL } } } } for provider in ModelProvider.allCases { guard keyTasks[provider] == nil else { continue } if let key = try? await writer.readProviderKey(provider: provider), !key.isEmpty { keys[provider]?.apiKey = key } } } /// 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) // No key re-fire: key writes land in ALL THREE .env files, so the // key pre-landed before any switch (the zai endpoint family rides // the surface write's zaiEndpoint). } 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) } // MARK: Test Connection (#136 — factsheet §4) enum TestState: Equatable { case running case done(ProviderProbe.Outcome) } /// One probe per provider over the CURRENT key/endpoint state. Guarded /// against stacking; the empty-key precondition makes an unkeyed probe /// fail fast without touching the network. #181: the credential — /// provider key, else the shared Portal session key for keyless /// providers — resolves through the ONE rail pass readiness also calls. func testConnection(for provider: ModelProvider) async { guard testStates[provider] != .running else { return } testStates[provider] = .running let keyConfig = keyConfig(for: provider) switch await ProviderCredential.resolve( provider: provider, envKey: keyConfig.apiKey, endpoint: keyConfig.endpoint, portalAuthPath: portalAuthPath, ) { case let .key(key): let config = ProviderProbe.Config( provider: provider, endpoint: keyConfig.endpoint, apiKey: key, model: probeModel(for: provider), ) testStates[provider] = await .done(ProviderProbe.probe(config, transport: probeTransport)) case let .refused(message): testStates[provider] = .done(.authFailed(message)) } } /// The model the probe proves generation on: the first surface on this /// provider (what the writer actually configures), else the provider's /// pinned flagship. func probeModel(for provider: ModelProvider) -> String { for surface in ProfileSurface.allCases where config(for: surface).provider == provider { return config(for: surface).model } return provider.switchDefaultModel } // MARK: Write plumbing /// Awaits in-flight writes — the tests' deterministic sync point. func awaitPendingWrites() async { let tasks = Array(surfaceTasks.values) + Array(keyTasks.values) for task in tasks { await task.value } surfaceTasks.removeAll() keyTasks.removeAll() } private func persist(_ surface: ProfileSurface, _ config: SurfaceModelConfig) { let zaiEndpoint = config.provider == .zai ? keyConfig(for: .zai).endpoint : nil let previous = surfaceTasks[surface] previous?.cancel() surfaceTasks[surface] = Task { [writeDebounce] in if writeDebounce > 0 { try? await Task.sleep(for: .seconds(writeDebounce)) } guard !Task.isCancelled else { return } // Cancellation can't stop a past-the-guard CLI write, so the // newer write WAITS — the last edit is always the last write to // land (2026-10-28 audit fix). await previous?.value guard !Task.isCancelled else { return } do { try await writer.writeSurface(surface, config: config, zaiEndpoint: zaiEndpoint) lastWriteError = nil if surface == .chat { onChatSurfaceWrite?() } } catch { lastWriteError = error.localizedDescription } } } private func persistKey(_ provider: ModelProvider) { let config = keyConfig(for: provider) // The zai base_url write-through targets: surfaces currently on // this provider (the KEY lands in all three .env files regardless). let profiles = ProfileSurface.allCases.filter { surfaces[$0]?.provider == provider } let previous = keyTasks[provider] previous?.cancel() keyTasks[provider] = Task { [writeDebounce] in if writeDebounce > 0 { try? await Task.sleep(for: .seconds(writeDebounce)) } guard !Task.isCancelled else { return } // Same contract as persist: wait out the in-flight predecessor. await previous?.value guard !Task.isCancelled else { return } do { try await writer.writeProviderKey(provider: provider, config: config, profiles: profiles) lastWriteError = nil } catch { lastWriteError = error.localizedDescription } } } }