Files
museion/Museion/SettingsModel.swift
T
AlexKucera b2db859887
CI / ci (push) Canceled after 0s
feat(settings): add Nous Portal provider (#175)
Settings gains hermes' `nous` slug as a fourth provider on every
surface and the Provider Keys page — endpoint
https://inference-api.nousresearch.com/v1, NOUS_API_KEY, the
5-level OpenAI-compatible effort ladder, switch flagship
anthropic/claude-sonnet-5 (live-probed: the portal's docs-listed
Hermes-4 ids 404 — the inference API serves the OpenRouter catalog,
so the switch keeps the app's sonnet posture billed through Nous).
The probe speaks plain OpenAI chat-completions; an unkeyed test
borrows the shared Portal session's agent_key (the engine's own
credential — hermes' nous runtime is OAuth-only, and a portal key
and subscription bill the same account credits), gated to the
official https endpoint so the implicit credential never rides a
user-edited URL. Pass readiness rides the same fallback, so a
logged-in machine runs passes with no key. Suite 635.

Closes #175
2026-11-05 15:59:41 +01:00

484 lines
18 KiB
Swift

//
// 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"
}
}
}
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
}
}
/// 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<Void, Never>] = [:]
private var keyTasks: [ModelProvider: Task<Void, Never>] = [:]
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. #175: an unkeyed NOUS probe
/// falls back to the shared Portal session key — the engine's own
/// credential — and names the login path when neither exists.
func testConnection(for provider: ModelProvider) async {
guard testStates[provider] != .running else { return }
testStates[provider] = .running
var key = keyConfig(for: provider).apiKey
if provider == .nous, key.isEmpty {
// Finish-audit #175: the session agent_key is an IMPLICIT
// credential (never pasted, field reads empty) — it only ever
// rides the official https endpoint, never a hand-edited one
// (cleartext http / foreign host = silent exfiltration with no
// on-screen cue). Custom endpoints get the paste-a-key refusal.
let endpoint = keyConfig(for: .nous).endpoint
let trimmed = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
guard trimmed == ModelProvider.nous.defaultEndpoint else {
testStates[provider] = .done(.authFailed(
"custom endpoint — paste an API key to test it (the Portal session key stays on the official endpoint)",
))
return
}
let path = portalAuthPath
key = await Task.detached(priority: .utility) {
PortalAuth.sessionKey(authJSONPath: path) ?? ""
}.value
if key.isEmpty {
testStates[provider] = .done(.authFailed(
"no key set and no Hermes Portal login — paste a key or run `hermes auth add nous`",
))
return
}
}
let config = ProviderProbe.Config(
provider: provider,
endpoint: keyConfig(for: provider).endpoint,
apiKey: key,
model: probeModel(for: provider),
)
let transport = probeTransport
testStates[provider] = await .done(ProviderProbe.probe(config, transport: transport))
}
/// 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
}
}
}
}