refactor(settings): provider facts as data
CI / ci (push) Canceled after 0s

#181: ModelProvider is the provider-descriptor table — label, effort
ladder, flagship, endpoint, env var joined by wire dialect (chat/models
paths + the SSE decoder selector), auth mode (Bearer vs Anthropic's
header pair), keyless (nous rides the Portal login), and the ONE
trailing-slash endpoint trim. The probe's URL builders, auth headers,
and stream-decoder picks select by data; the per-dialect bodies and
decoders stay separate functions, not switch clothing.

ProviderCredential.resolve is the ONE credential rail (provider key,
else the shared Portal session key for keyless providers — official
endpoint ONLY, never a user-set URL). Settings' Test Connection and the
new PassReadiness module both call it; the twice-implemented #175
fallback can no longer drift. One deliberate tightening, reviewer-
blessed: a nous pass profile on a custom base_url with no pasted key now
reads missingKey where the old session-model fallback said ready — the
old copy had no endpoint gate at all.

Pass readiness leaves the session model (PassReadiness.swift maps each
pass surface to ready/missingKey/unknown over the descriptor;
MentorSessionModel stores the verdicts and reads no keys or auth
files). runPass and blindRead run their guards through one shared rail
(guardOpenPieceRun) — identical refusal strings, blockers named
honestly. No app-side model-settings store (ADR-0014 red line).

Rider: the #179 mid-pass repoint pin polls the rig's hasHeldPrompt
before releasing the held turn — runningPass flips before the one-shot
engine parks its prompt, so firing into that window false-failed under
parallel-suite load.

Full suite 668/668 (xcresult executed count). Finish-audit: three
reviewers (ponytail/security/general), zero findings above LOW; two
ponytail trims and one pin tightening applied.

Closes #181
This commit is contained in:
AlexKucera committed 2026-11-10 10:58:29 +01:00
1 parent 218e2db397
commit f49e4b6ca0
15 files changed
+506 -184

No files matched your search

+130 -36
View File
@@ -89,6 +89,78 @@ nonisolated enum ModelProvider: String, CaseIterable, Sendable {
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 <key>`.
case bearer
/// `x-api-key: <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 {
@@ -169,6 +241,44 @@ nonisolated enum PortalAuth {
}
}
/// #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
@@ -367,46 +477,30 @@ final class SettingsModel {
/// 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.
/// 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
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(
let keyConfig = keyConfig(for: provider)
switch await ProviderCredential.resolve(
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))
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