feat(settings): add Nous Portal provider (#175)
CI / ci (push) Canceled after 0s

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
This commit is contained in:
AlexKucera committed 2026-11-05 15:59:41 +01:00
1 parent d305f822aa
commit b2db859887
15 files changed
+410 -30

No files matched your search

+1 -1
View File
@@ -48,7 +48,7 @@ Owned by the root AGENTS.md contract.
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
- `ProseListTests.swift` (#115 / S5) — the prose list model + fold rendering: scan pins (item basics, nested children + fold scope, lazy continuation, blank-separated child folds the blank too, fences end blocks, parents scan), indent/outdent (dash content column, caret ride + park, ordered-marker unit, boundary nils), move (subtree swap with between-text, boundary no-ops); `ProseFoldRenderingTests` (@MainActor, plain `ProseListTextView()` — no window, chrome never installs) — folding never edits the buffer, hidden scopes carry `foldedAttributes`, parent stays body-size, unfold restores, folds re-key to the nearest same-marker parent after an edit above, and a fold dies when its marker text vanishes.
- `ProseRekeyTests.swift` (#142, F1 — scenario header at file top; own file, split from ProseListTests at the file-length ceiling) — `ProseFoldRekeyTests` drives the keystroke pipeline through the REAL seams (`shouldChangeText` records → storage mutates → `refreshFolds`): a single-line edit above re-keys in place with hidden styling intact (no storage swap), typing on the marker line kills the fold AND restores its scope to view, a multi-line edit still takes the full pass, and a wholesale restyle (the fence-flip shape) self-heals into the full pass via the font probe; `ProseRekeyMathTests` pins the pure `rekey` math exactly (shift above, untouched below, death + translated diedScope, boundary-insertion deaths at both marker-content edges, scope-interior deletion → shrunk scope + rehide range + caret park). The painted-layer chrome skip itself is unpinnable headless (needs a window) — dogfood owns it.
- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `cannedKeys` feeds `readProviderKey(provider:)` — #136 dogfood amendment: keys land in ALL THREE `.env` files, so hydration refills every key field with no per-provider profile list; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing). **#136 (Profiles S3):** the RecordingWriter double carries the new protocol shape (surface records include `zaiEndpoint`, key records the fan-out `profiles`, `cannedReads` feeds `readSurface`); the #136 model-side pins live in `SettingsModelWritePathTests.swift` (own file, file-length ceiling) sharing the now-internal `RecordingWriter` + `liveShapedRegistry` — a provider switch to a keyed zai threads the endpoint family into the surface write WITHOUT re-firing keys (they pre-landed in all three `.env` files at entry time), key writes carry the surfaces-on-provider list as the zai base_url write-through targets (chat first), rapid key edits coalesce into one write (superseded writes never spawn — partial key prefixes never reach `.env`; `writeDebounce: 0` keeps the suite deterministic), hydrate maps profile reads + infers the zai key type from the coding base_url (unread/unknown-provider surfaces stay seeded) and SEEDS a custom zai base_url instead of clobbering it, an edit made mid-hydrate never gets stomped, a second edit WAITS for the in-flight write (record order pinned `old → new`), and an unkeyed Test Connection authFails fast off the network; `probeModel` picks the first surface on a provider else its flagship. `HermesSettingsWriterTests.swift` (own file) — the real write path against the fake CLI (Real-Process pattern): write→`config get` round-trip, the exact config-set ORDER (provider → model → effort → base_url LAST, because setting model.provider clears base_url — live-probed), nil-effort unset + idempotent unset-when-absent, the `.env` writes over temp profile dirs (the key lands in ALL THREE profiles — a key with no surface on its provider still persists; foreign lines + comments preserved byte-for-byte, 0600 — hermes' own posture, the zai base_url config-set rides ONLY the listed profiles, an empty key leaves bytes alone but still writes the zai base_url, non-zai providers never config-set; readProviderKey round-trips, a line-broken key value is refused with nothing written — the env-injection guard), profile-named failures, missing-binary refusals + nil reads, and pure `upsertEnv` edges (in-place replace, append, trailing-newline, empty). `ProviderProbeTests.swift` (own file) — the factsheet decode matrix: zai 1113 → wrongKeyType, 401s per provider (Anthropic detail carries `request_id`), 429/foreign bodies → requestFailed; the three SSE dialects (zai chat-completions content + reasoning channels, Anthropic text_delta/stop_reason, OpenAI Responses output_text.delta/completed/incomplete/failed) — works carries reply + model count, `finish=length`/`max_tokens`/`incomplete` + empty → starved, response.failed → requestFailed, and the live 2026-10-28 z.ai **200-carried error envelope** (wrong content-type) decodes as the provider error; `ssePayloads` skipping event/DONE/blank lines; `decodeModelsCount` shapes; free `probeHTTPResponse`/`probeData` canned-response helpers live here (shared-helper convention). `ProviderProbeTransportTests.swift` (own file — the decode suite crossed its type-body ceiling, MCPToolsPromoteTests precedent) — the request builders (the 2026-10-28 Content-Type pin across all providers; Anthropic `x-api-key` + pinned version + required max_tokens; zai `thinking:enabled`+`reasoning_effort:low` wire at the 512 cap; **OpenAI in the ResponseLine truncated
- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `cannedKeys` feeds `readProviderKey(provider:)` — #136 dogfood amendment: keys land in ALL THREE `.env` files, so hydration refills every key field with no per-provider profile list; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing). **#136 (Profiles S3):** the RecordingWriter double carries the new protocol shape (surface records include `zaiEndpoint`, key records the fan-out `profiles`, `cannedReads` feeds `readSurface`); the #136 model-side pins live in `SettingsModelWritePathTests.swift` (own file, file-length ceiling) sharing the now-internal `RecordingWriter` + `liveShapedRegistry` — a provider switch to a keyed zai threads the endpoint family into the surface write WITHOUT re-firing keys (they pre-landed in all three `.env` files at entry time), key writes carry the surfaces-on-provider list as the zai base_url write-through targets (chat first), rapid key edits coalesce into one write (superseded writes never spawn — partial key prefixes never reach `.env`; `writeDebounce: 0` keeps the suite deterministic), hydrate maps profile reads + infers the zai key type from the coding base_url (unread/unknown-provider surfaces stay seeded) and SEEDS a custom zai base_url instead of clobbering it, an edit made mid-hydrate never gets stomped, a second edit WAITS for the in-flight write (record order pinned `old → new`), and an unkeyed Test Connection authFails fast off the network; `probeModel` picks the first surface on a provider else its flagship. **#175 (nous):** the nous provider facts pin (slug/label/endpoint/NOUS_API_KEY) lives here too (SettingsModelTests' file-length ceiling), an unkeyed nous Test Connection borrows the shared `~/.hermes/auth.json` agent_key as Bearer (`PortalAuth.sessionKey`; injectable `portalAuthPath` + `probeTransport` — offline canned transport), and no-key-no-login authFails naming `hermes auth add nous`; the custom-endpoint refusal pin (a hand-edited nous endpoint with an empty key authFails pre-network — the session key never rides a user-set URL); **EngineLifecycleTests** carries the readiness counterpart (`nous pass readiness rides the portal login without a key` — `.ready` via the injected `portalAuthPath`, `.missingKey("Nous Portal")` with no login); ProviderProbeTests pins the bare-envelope **401 → authFailed** (the fallback credential's own failure mode). `HermesSettingsWriterTests.swift` (own file) — the real write path against the fake CLI (Real-Process pattern): write→`config get` round-trip, the exact config-set ORDER (provider → model → effort → base_url LAST, because setting model.provider clears base_url — live-probed), nil-effort unset + idempotent unset-when-absent, the `.env` writes over temp profile dirs (the key lands in ALL THREE profiles — a key with no surface on its provider still persists; foreign lines + comments preserved byte-for-byte, 0600 — hermes' own posture, the zai base_url config-set rides ONLY the listed profiles, an empty key leaves bytes alone but still writes the zai base_url, non-zai providers never config-set; readProviderKey round-trips, a line-broken key value is refused with nothing written — the env-injection guard), profile-named failures, missing-binary refusals + nil reads, and pure `upsertEnv` edges (in-place replace, append, trailing-newline, empty). `ProviderProbeTests.swift` (own file) — the factsheet decode matrix: zai 1113 → wrongKeyType, 401s per provider (Anthropic detail carries `request_id`), 429/foreign bodies → requestFailed; the SSE dialects (zai chat-completions content + reasoning channels, Anthropic text_delta/Line truncated
- `PersonaLoadOrderTests.swift` (#1) — persona-content pins over the REAL bundled payload (`ProfileProvisioner.defaultPayloadRoot()`): both personas carry the `## Draft first, rules last` load-order doctrine (pass-persona 1.5 / session-persona 1.2, the PRD prompt-end rule), and the section is verbatim-shared between the pair (the four-shared-sections contract, ref/writing skills/AGENTS.md). Verified layout lives in `docs/research/prompt-layout-factsheet.md`.
## Verification
+27
View File
@@ -250,6 +250,33 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
// link; once the key is provided via Settings, Run Pass re-enables (pane
// re-entry refreshes).
// Scenario: Keyless Nous pass readiness — From user story #175
// Given a pass surface switched to Nous Portal and hermes logged into
// the Portal (the shared auth.json session — the engine's credential;
// the .env key is optional and bills the same account credits)
// When refreshPassReadiness runs
// Then the pass reads .ready with NO key (the session agent_key stands
// in), and with no login either it names the missing key honestly.
@Test @MainActor func `nous pass readiness rides the portal login without a key`() async throws {
let mentor = MentorSessionModel()
let writer = RecordingWriter()
writer.cannedReads[.pass1] = (SurfaceModelConfig(provider: .nous, model: "anthropic/claude-sonnet-5", effort: nil), nil)
mentor.passReadinessWriter = writer
let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nous-readiness-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let authPath = dir.appendingPathComponent("auth.json").path
try #"{"providers":{"nous":{"agent_key":"ak-shared-123"}}}"#.write(toFile: authPath, atomically: true, encoding: .utf8)
mentor.portalAuthPath = authPath
await mentor.refreshPassReadiness()
#expect(mentor.readiness(for: .pass1) == .ready)
// No key and no login — the honest missing-key verdict.
mentor.portalAuthPath = dir.appendingPathComponent("missing.json").path
await mentor.refreshPassReadiness()
#expect(mentor.readiness(for: .pass1) == .missingKey(providerLabel: "Nous Portal"))
}
/// B1 readiness pins: refreshPassReadiness over the injected RecordingWriter
/// — keyed provider reads .ready, an unkeyed one reads .missingKey with its
/// label, a key landing re-enables on the next refresh (the pane's .task),
+49 -1
View File
@@ -107,7 +107,55 @@ struct ProviderProbeTests {
#expect(foreignStatus == 502)
}
// MARK: Chat decode — the three SSE dialects
// MARK: Chat decode — the SSE dialects
// Scenario: Nous Portal decode — From user story #175
// Given the portal's OpenAI-compatible chat SSE (live-captured
// 2026-11-05: delta.content chunks, finish stop) and its bare
// {status, message} error envelope (no error object — a bad model id
// answers HTTP 404 + message)
// When the probe decodes a nous response
// Then content decodes works, and the error decodes requestFailed
// carrying the portal's own message — never a bare "HTTP 404".
@Test func `nous sse decodes works and the portal error envelope carries its message`() {
let sse = """
data: {"choices":[{"delta":{"content":"Hi there!"},"finish_reason":null}]}
data: {"choices":[{"delta":{},"finish_reason":"stop"}]}
data: [DONE]
"""
guard case .works = ProviderProbe.decodeChat(
provider: .nous, body: Data(sse.utf8), modelCount: 385, latencyMS: 900,
) else {
Issue.record("expected works over the portal SSE")
return
}
guard case let .requestFailed(status, detail) = ProviderProbe.decodeError(
status: 404,
body: probeData(
#"{"status":404,"message":"Model 'x' not found in our configuration."}"#,
),
provider: .nous,
) else {
Issue.record("expected requestFailed for the portal envelope")
return
}
#expect(status == 404)
#expect(detail.contains("not found"))
// Finish-audit #175: the fallback credential's own failure mode —
// 401 over the bare envelope decodes authFailed carrying the
// message (an expired/revoked agent_key).
guard case let .authFailed(authDetail) = ProviderProbe.decodeError(
status: 401,
body: probeData(#"{"status":401,"message":"token expired"}"#),
provider: .nous,
) else {
Issue.record("expected authFailed for the bare 401 envelope")
return
}
#expect(authDetail.contains("token expired"))
}
@Test func `zai sse content decodes works and empty length decodes starved`() {
let sse = """
@@ -56,6 +56,27 @@ struct ProviderProbeTransportTests {
#expect(request.url?.absoluteString == "\(ZaiKeyType.coding.endpoint)/chat/completions")
}
/// #175: Nous Portal is plain OpenAI chat-completions on the wire —
/// live-probed 2026-11-05 (messages body answers finish=stop; the
/// portal router has no z.ai-style thinking knobs) — Bearer auth like
/// z.ai/openai, `/chat/completions` + `/models` on the versioned base.
@Test func `nous chat speaks the plain chat completions dialect`() throws {
let config = ProviderProbe.Config(
provider: .nous, endpoint: ModelProvider.nous.defaultEndpoint, apiKey: "sk-nous", model: "anthropic/claude-sonnet-5",
)
let request = try #require(ProviderProbe.makeChatRequest(config))
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer sk-nous")
#expect(request.url?.absoluteString == "https://inference-api.nousresearch.com/v1/chat/completions")
#expect(ProviderProbe.modelsURL(for: .nous, endpoint: ModelProvider.nous.defaultEndpoint)?
.absoluteString == "https://inference-api.nousresearch.com/v1/models")
let bodyData = try #require(request.httpBody)
let body = try #require(String(bytes: bodyData, encoding: .utf8))
#expect(body.contains(#""messages""#))
#expect(body.contains(#""max_tokens":\#(ProviderProbe.probeTokenCap)"#))
#expect(!body.contains("thinking")) // no z.ai reasoning knobs on the portal router
#expect(!body.contains("reasoning_effort"))
}
@Test func `openai chat speaks the responses api and urls append cleanly`() throws {
let config = ProviderProbe.Config(
provider: .openaiAPI, endpoint: "https://api.openai.com/v1/", apiKey: "sk-oai", model: "gpt-6.1-sol",
+11
View File
@@ -124,6 +124,9 @@ func liveShapedRegistry() -> ModelRegistry {
.zai: ["glm-4.5", "glm-5", "glm-5.3", "glm-5.3-flashx"],
.anthropic: ["claude-fable-5.1", "claude-opus-5-5", "claude-sonnet-5", "claude-sonnet-4-6"],
.openaiAPI: ["gpt-5.6-sol", "gpt-5.5", "gpt-5.4-mini"],
// #175: the portal's router catalog shape — vendor-prefixed ids, the
// switch flagship first.
.nous: ["anthropic/claude-sonnet-5", "z-ai/glm-5.3", "openai/gpt-5.5"],
])
}
@@ -135,6 +138,9 @@ struct SettingsModelTests {
#expect(ModelProvider.zai.effortOptions == [.low, .high, .max])
#expect(ModelProvider.openaiAPI.effortOptions == [.low, .medium, .high, .xhigh, .max])
#expect(ModelProvider.anthropic.effortOptions == [.low, .medium, .high, .xhigh, .max])
// #175: hermes clamps nous on the widest OpenAI-compatible vocabulary
// (OPENAI_COMPAT_WIRE_EFFORTS — the Museion-facing subset).
#expect(ModelProvider.nous.effortOptions == [.low, .medium, .high, .xhigh, .max])
}
@Test @MainActor func `effort unset is the leading default state`() {
@@ -184,6 +190,11 @@ struct SettingsModelTests {
#expect(model.config(for: .chat).model == "gpt-6.1-sol")
model.setProvider(.anthropic, for: .chat)
#expect(model.config(for: .chat).model == "claude-sonnet-5")
// #175: the portal switch keeps the app's sonnet posture — same
// default model, routed and billed through Nous.
model.setProvider(.nous, for: .chat)
#expect(model.config(for: .chat).model == "anthropic/claude-sonnet-5")
#expect(!model.isCustom(.chat))
}
@Test @MainActor func `an empty registry leaves every model custom free text stays first class`() {
@@ -149,6 +149,103 @@ struct SettingsModelWritePathTests {
#expect(model.probeModel(for: .zai) == ModelProvider.zai.switchDefaultModel)
}
// Scenario: Nous Portal as a fourth provider — From user story #175
// Given Hermes' own registry offers the `nous` slug (OpenAI-compatible
// inference API — one account bill behind key and subscription alike)
// When Settings offers Nous Portal
// Then the pinned facts match the live-probed wire: the portal inference
// endpoint, the env var hermes' tooling maps the slug to, and the label.
@Test func `nous provider facts pin the portal wire`() {
#expect(ModelProvider.nous.rawValue == "nous")
#expect(ModelProvider.nous.label == "Nous Portal")
#expect(ModelProvider.nous.defaultEndpoint == "https://inference-api.nousresearch.com/v1")
#expect(ModelProvider.nous.envVarName == "NOUS_API_KEY")
}
// Scenario: Test Connection on an unkeyed Nous Portal — From user story #175
// Given hermes logged into the Nous Portal (the shared auth.json session —
// the engine's own credential; API key and subscription bill the same
// account credits)
// When the user tests Nous with no key pasted
// Then the probe borrows the session's agent_key as its Bearer — and with
// no session either, it names the portal login path, not a bare "no key".
@Test @MainActor func `nous connection borrows the shared portal session key`() async throws {
final class AuthSaw: @unchecked Sendable { var header: String? }
let saw = AuthSaw()
let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nous-auth-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let authPath = dir.appendingPathComponent("auth.json").path
try #"{"providers":{"nous":{"agent_key":"ak-shared-123"}}}"#.write(toFile: authPath, atomically: true, encoding: .utf8)
let model = SettingsModel(
registry: liveShapedRegistry(),
writer: RecordingWriter(),
writeDebounce: 0,
probeTransport: { request in
saw.header = request.value(forHTTPHeaderField: "Authorization")
if request.url!.path.hasSuffix("/models") {
return (probeData(#"{"object":"list","data":[{},{},{},{}]}"#), probeHTTPResponse(200))
}
return (
Data("data: {\"choices\":[{\"delta\":{\"content\":\"Hi\"},\"finish_reason\":\"stop\"}]}\n\n".utf8),
probeHTTPResponse(200),
)
},
portalAuthPath: authPath,
)
await model.testConnection(for: .nous)
#expect(saw.header == "Bearer ak-shared-123")
guard case let .done(outcome) = model.testStates[.nous], case .works = outcome else {
Issue.record("expected works over the session key, got \(String(describing: model.testStates[.nous]))")
return
}
}
/// Finish-audit #175: the implicit session credential never rides a
/// hand-edited endpoint — a custom endpoint with an empty key refuses
/// before any network, pointing at the key field.
@Test @MainActor func `nous session key never rides a custom endpoint`() async throws {
let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nous-gate-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let authPath = dir.appendingPathComponent("auth.json").path
try #"{"providers":{"nous":{"agent_key":"ak-shared-123"}}}"#.write(toFile: authPath, atomically: true, encoding: .utf8)
let model = SettingsModel(
registry: liveShapedRegistry(),
writer: RecordingWriter(),
writeDebounce: 0,
probeTransport: { _ in
Issue.record("a custom endpoint must never receive the session key")
throw URLError(.badURL)
},
portalAuthPath: authPath,
)
model.setEndpoint("http://proxy.example/v1", for: .nous)
await model.testConnection(for: .nous)
guard case let .done(outcome) = model.testStates[.nous], case let .authFailed(detail) = outcome else {
Issue.record("expected the custom-endpoint refusal, got \(String(describing: model.testStates[.nous]))")
return
}
#expect(detail.contains("paste an API key"))
}
@Test @MainActor func `nous connection with no key and no login names the portal path`() async {
let missing = FileManager.default.temporaryDirectory
.appendingPathComponent("nous-auth-missing-\(UUID().uuidString)").path
let model = SettingsModel(
registry: liveShapedRegistry(),
writer: RecordingWriter(),
writeDebounce: 0,
portalAuthPath: missing,
)
await model.testConnection(for: .nous)
guard case let .done(outcome) = model.testStates[.nous], case let .authFailed(detail) = outcome else {
Issue.record("expected authFailed, got \(String(describing: model.testStates[.nous]))")
return
}
#expect(detail.contains("hermes auth add nous"))
}
// Scenario: Saving a Chat model change reaches the resident engine
// From user story #137 acceptance 2
// Given the Settings pane is open