Files
museion/Museion/HermesSettingsWriter.swift
T
AlexKucera 5ad605eb3c feat(settings): profiles write path + Test Connection (#136)
Profiles S3 over the S2 shell: every Settings change now persists.

Model/effort writes ride the engine's own CLI — `hermes -p <profile>
config set/unset` for model.provider / model.default /
model.reasoning_effort / model.base_url (zai endpoint family written
LAST: setting model.provider clears a stale base_url, live-probed;
unset-when-absent is idempotent success). Provider keys upsert
VAR=value into ALL THREE profiles' .env — a key entered before any
surface is on its provider still persists and pre-lands for any later
switch (maintainer ruling 2026-10-28; no switch re-fire). 0600,
foreign lines preserved byte-for-byte, line-broken values refused at
the shared sink (env-file injection guard), NSLock serializes the
read-upsert-write across concurrent provider writes.

Hydration reads model blocks and keys back at pane open — a restart
neither blanks the key fields nor refuses Test Connection; an edit
made mid-read owns the truth (no stomp), and a custom z.ai base_url
seeds the endpoint field instead of being clobbered to a family
default. Per-target writes coalesce AND chain past the debounce
guard: cancellation can't stop a past-the-guard CLI write, so the
newer write queues — the last edit is always the last write to land
(finish-audit race fix, pinned).

Test Connection = two-step probe (GET /models, then a minimal
streaming chat) with honest decode per the factsheet: zai 1113 →
wrong key type, 401s → auth failed (Anthropic request_id),
finish=length → starved, empty 200 → request failed, errors riding a
2xx decoded as the provider error.

Live-probed wire corrections (dogfood, 2026-10-28): Content-Type
application/json on every request — URLSession defaults to
form-urlencoded and providers diverge (zai 200+envelope, OpenAI 400,
Anthropic tolerates); OpenAI speaks the Responses API (/responses,
input + max_output_tokens, flagship gpt-6.1-sol); probe token cap 512
(64 starved reasoning models into "no content"); OpenAI's
"error": null event snapshots don't decode as failures.

Finish-audit (ponytail + security + general reviewers): write-ordering
race + .env lost update + hydrate stomp + custom-endpoint clobber
fixed and pinned (one-shot hold / latched read knobs in the test
double); ~30 lines of dead flexibility cut (keyType protocol param,
works(reply:) payload, unused timeout knob, double JSON round trips).

Suite 468/468 xcresult-verified; swiftlint clean; factsheet §6
correction logged. Closes #136
2026-10-27 18:32:30 +01:00

289 lines
12 KiB
Swift

//
// HermesSettingsWriter.swift
// Museion
//
// #136 (Profiles S3): the real SettingsWriting — surface model blocks via
// the engine's own CLI (`hermes -p <profile> config set/unset`, format
// owned by Hermes, wire-verified `✓` lines — the provisioner's posture),
// provider keys via direct `.env` edit per matching profile (one key fans
// out to every profile on that provider, no Keychain — ADR-0014), and the
// z.ai key type's endpoint family written through as `model.base_url`.
//
// Live-probed wire facts (2026-10-27): `config set` prints
// `✓ Set <key> = <value> in <path>` exit 0; `config unset` prints
// `✓ Unset <key> from <path>` exit 0 and exits 1 with
// `Config key not set: <key>` when already absent (idempotent success);
// `config get` prints the value exit 0, or the not-set line on stderr
// exit 1. Setting `model.provider` CLEARS a stale `model.base_url` — so
// the z.ai endpoint is (re)written after the provider, and key writes
// write it again (both paths converge on the same value).
//
import Foundation
/// The write-path seam (#135/#136). `HermesSettingsWriter` is the
/// production implementation — `hermes -p <profile> config set` for the
/// model block (validated keys, format owned by Hermes), `.env` fan-out for
/// provider keys (ADR-0014). Contract for implementers (finish-audit
/// #135, amended #136): the MODEL coalesces rapid edits per target before
/// calling (a superseded write never reaches the writer), but calls still
/// arrive tentative — implementations MUST hop off-main internally (the
/// CLI rail blocks) and keep surfaced error text free of key-bearing
/// content (`lastWriteError` renders verbatim). Secrets never ride argv
/// (`ps` reads live command lines).
@MainActor
protocol SettingsWriting: Sendable {
/// `zaiEndpoint`: the z.ai endpoint family when (and only when) the
/// config's provider is z.ai — written LAST because setting
/// `model.provider` clears a stale `model.base_url` (live-probed).
func writeSurface(_ surface: ProfileSurface, config: SurfaceModelConfig, zaiEndpoint: String?) async throws
/// The key lands in ALL THREE profiles' `.env` (a key entered before
/// any surface is on its provider still persists and pre-lands for any
/// later switch; inert vars are ignored by hermes for other providers).
/// `profiles` gates only the z.ai `base_url` write-through. An empty
/// `config.apiKey` leaves `.env` alone — the field sets, never removes.
func writeProviderKey(provider: ModelProvider, config: ProviderKeyConfig, profiles: [ProfileSurface]) async throws
/// The profile's live model block for hydration; nil = unreadable or a
/// provider Settings doesn't offer (the surface keeps its seed — never
/// stomped by defaults).
func readSurface(_ surface: ProfileSurface) async throws -> (config: SurfaceModelConfig, baseURL: String?)?
/// The provider's persisted key from the profiles' `.env` (first
/// non-empty wins); nil = nothing stored. Hydration fills the key
/// fields so a restart doesn't read as "no key" — the probe and the
/// masked field ride the STORED truth.
func readProviderKey(provider: ModelProvider) async throws -> String?
}
/// The inert writer: previews and pre-gate states; the UI runs over the
/// in-memory model.
struct NoopSettingsWriter: SettingsWriting {
func writeSurface(_: ProfileSurface, config _: SurfaceModelConfig, zaiEndpoint _: String?) async throws {}
func writeProviderKey(
provider _: ModelProvider,
config _: ProviderKeyConfig,
profiles _: [ProfileSurface],
) async throws {}
func readSurface(_: ProfileSurface) async throws -> (config: SurfaceModelConfig, baseURL: String?)? {
nil
}
func readProviderKey(provider _: ModelProvider) async throws -> String? {
nil
}
}
struct HermesSettingsWriter: SettingsWriting {
let hermesBinary: String?
var profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath
struct WriteError: LocalizedError, Equatable {
let message: String
var errorDescription: String? {
message
}
}
// MARK: Surface writes (the profile's `model:` block)
func writeSurface(
_ surface: ProfileSurface,
config: SurfaceModelConfig,
zaiEndpoint: String?,
) async throws {
guard let hermesBinary else {
throw WriteError(message: "hermes binary not found — pass the engine gate first")
}
let binary = hermesBinary, profile = surface.profileName
try await Task.detached(priority: .utility) {
// Provider first (switching clears a stale base_url — probed),
// then the model, then effort, then the z.ai endpoint family.
try Self.setKey("model.provider", config.provider.rawValue, profile: profile, binary: binary, timeout: 30)
try Self.setKey("model.default", config.model, profile: profile, binary: binary, timeout: 30)
if let effort = config.effort {
try Self.setKey("model.reasoning_effort", effort.rawValue, profile: profile, binary: binary, timeout: 30)
} else {
try Self.unsetKey("model.reasoning_effort", profile: profile, binary: binary, timeout: 30)
}
if let zaiEndpoint, !zaiEndpoint.isEmpty {
try Self.setKey("model.base_url", zaiEndpoint, profile: profile, binary: binary, timeout: 30)
}
}.value
}
// MARK: Provider keys (.env fan-out + the z.ai endpoint family)
/// The key upserts into ALL THREE profiles' `.env` (it pre-lands for
/// any later provider switch; an EMPTY key leaves `.env` alone — the
/// field sets a key, it never removes one). The z.ai endpoint family
/// write-through (`model.base_url`, factsheet §1.1) rides only the
/// profiles currently on z.ai — a zai endpoint in an anthropic profile
/// would be wrong.
func writeProviderKey(
provider: ModelProvider,
config: ProviderKeyConfig,
profiles: [ProfileSurface],
) async throws {
let writesBaseURL = provider == .zai && !config.endpoint.isEmpty
if writesBaseURL, hermesBinary == nil {
throw WriteError(message: "hermes binary not found — pass the engine gate first")
}
let root = profileRoot, key = config.apiKey, varName = provider.envVarName
let endpoint = writesBaseURL ? config.endpoint : nil
let binary = hermesBinary
try await Task.detached(priority: .utility) {
for surface in ProfileSurface.allCases {
let dir = (root as NSString).appendingPathComponent(surface.profileName)
if !key.isEmpty {
try Self.upsertEnvFile(varName: varName, value: key, profileDir: dir, profile: surface.profileName)
}
}
if let endpoint, let binary {
for surface in profiles {
try Self.setKey("model.base_url", endpoint, profile: surface.profileName, binary: binary, timeout: 30)
}
}
}.value
}
// MARK: Reads (hydration)
/// The profile's live `model:` block. nil = unreadable profile or a
/// provider Settings doesn't offer (a hand-configured kimi-coding
/// surface stays untouched rather than stomped by defaults).
func readSurface(_ surface: ProfileSurface) async throws -> (config: SurfaceModelConfig, baseURL: String?)? {
guard let hermesBinary else { return nil }
let binary = hermesBinary, profile = surface.profileName
return await Task.detached(priority: .utility) { () -> (SurfaceModelConfig, String?)? in
func get(_ key: String) -> String? {
let run = EngineProbe.execute([binary, "-p", profile, "config", "get", key], timeout: 30)
guard run.exitCode == 0 else { return nil } // not set / unknown profile
let value = run.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
return value.isEmpty ? nil : value
}
guard let slug = get("model.provider"), let provider = ModelProvider(rawValue: slug) else { return nil }
return (
SurfaceModelConfig(
provider: provider,
model: get("model.default") ?? ProfileSurface.defaultModelID,
effort: get("model.reasoning_effort").flatMap(ReasoningEffort.init(rawValue:)),
),
get("model.base_url"),
)
}.value
}
/// The provider's persisted key: the first non-empty `VAR=` line
/// across the profiles' `.env` files (the write landed the same key in
/// all of them; one authoritative copy is enough to refill the field).
/// File reads only — no CLI spawn.
func readProviderKey(provider: ModelProvider) async throws -> String? {
let root = profileRoot, varName = provider.envVarName
return await Task.detached(priority: .utility) { () -> String? in
for surface in ProfileSurface.allCases {
let envPath = ((root as NSString).appendingPathComponent(surface.profileName) as NSString)
.appendingPathComponent(".env")
guard let text = try? String(contentsOfFile: envPath, encoding: .utf8) else { continue }
for line in text.split(separator: "\n") where line.hasPrefix("\(varName)=") {
let value = line.dropFirst("\(varName)=".count).trimmingCharacters(in: .whitespaces)
if !value.isEmpty {
return value
}
}
}
return nil
}.value
}
// MARK: CLI rail (wire-verified, the provisioner's posture) — nonisolated:
// they run inside Task.detached, off the actor.
private nonisolated static func setKey(
_ key: String,
_ value: String,
profile: String,
binary: String,
timeout: TimeInterval,
) throws {
let run = EngineProbe.execute([binary, "-p", profile, "config", "set", key, value], timeout: timeout)
guard run.exitCode == 0, run.stdout.contains("✓ Set \(key)") else {
throw WriteError(message: "couldn't set \(key) on \(profile): \(excerpt(run))")
}
}
private nonisolated static func unsetKey(
_ key: String,
profile: String,
binary: String,
timeout: TimeInterval,
) throws {
let run = EngineProbe.execute([binary, "-p", profile, "config", "unset", key], timeout: timeout)
// Absent already = the desired state (idempotent; exit 1 + not-set line).
let output = run.stdout + run.stderr
guard run.stdout.contains("✓ Unset \(key)") || output.contains("Config key not set: \(key)") else {
throw WriteError(message: "couldn't unset \(key) on \(profile): \(excerpt(run))")
}
}
/// Secrets never ride argv (`ps` reads live command lines) — this rail
/// only ever carries provider/model/effort/base_url. Errors keep the
/// same guarantee: excerpt content is CLI output, key text never
/// reaches `lastWriteError`.
private nonisolated static func excerpt(_ run: EngineProbe.ProcessOutput) -> String {
let text = run.stdout.isEmpty ? run.stderr : run.stdout
return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(300))
}
// MARK: .env edit
/// Upsert `VAR=value` preserving every other line (hermes' own .env
/// header comments and foreign keys survive byte-for-byte). Pure — the
/// fan-out tests pin the edges.
nonisolated static func upsertEnv(varName: String, value: String, in text: String) -> String {
let prefix = "\(varName)="
var lines = text.isEmpty
? []
: text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
if lines.last == "" {
lines.removeLast()
} // trailing-newline artifact; re-added below
lines = lines.filter { !$0.hasPrefix(prefix) }
lines.append(prefix + value)
return lines.joined(separator: "\n") + "\n"
}
/// 2026-10-28 audit fix: a pasted value containing a line break (or
/// NUL) is an env-file injection — "key\nOTHER_VAR=x" would land as a
/// real second line in every profile's `.env`. One guard at the shared
/// sink; the thrown error rides `lastWriteError`, nothing is written.
/// The lock serializes the read→upsert→write across concurrent
/// cross-provider key writes (same three files — last writer would
/// otherwise drop the other's var).
private nonisolated static let envWriteLock = NSLock()
private nonisolated static func upsertEnvFile(varName: String, value: String, profileDir: String, profile: String) throws {
guard !value.contains(where: { $0 == "\n" || $0 == "\r" || $0 == "\0" }) else {
throw WriteError(message: "\(varName) value contains a line break — not written")
}
envWriteLock.lock()
defer { envWriteLock.unlock() }
let envPath = (profileDir as NSString).appendingPathComponent(".env")
let existing = (try? String(contentsOfFile: envPath, encoding: .utf8)) ?? ""
let updated = upsertEnv(varName: varName, value: value, in: existing)
do {
try FileManager.default.createDirectory(atPath: profileDir, withIntermediateDirectories: true)
try updated.write(toFile: envPath, atomically: true, encoding: .utf8)
// Hermes' own .env files are 0600; a secret we just wrote must
// not be group/world-readable (String.write creates 0644).
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: envPath)
} catch {
throw WriteError(message: "couldn't write \(profile)/.env: \(error.localizedDescription)")
}
}
}