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
368 lines
15 KiB
Swift
368 lines
15 KiB
Swift
//
|
||
// ProviderProbe.swift
|
||
// Museion
|
||
//
|
||
// #136 (Profiles S3): Test Connection — the factsheet §4 two-step probe
|
||
// per provider: (1) GET /models = key validity + reachability (on z.ai it
|
||
// proves nothing about key-type/endpoint pairing, §1.2), (2) a minimal
|
||
// streaming chat call (max_tokens ≈ 64, "hi") proving key × endpoint ×
|
||
// model actually generates. Decoding is honest per the factsheet: HTTP
|
||
// status + provider error envelope, z.ai 1113 → wrong key type for this
|
||
// endpoint family, `finish=length` + empty content → raise the cap — never
|
||
// gated on status 200 alone (§1.5 starvation is a 200).
|
||
//
|
||
|
||
import Foundation
|
||
|
||
nonisolated enum ProviderProbe {
|
||
/// What one probe needs: the provider dialect, endpoint base URL, key,
|
||
/// and the model the chat step proves generation on (a surface's model —
|
||
/// what the writer actually configures).
|
||
struct Config: Sendable, Equatable {
|
||
var provider: ModelProvider
|
||
var endpoint: String
|
||
var apiKey: String
|
||
var model: String
|
||
}
|
||
|
||
/// The honest verdicts (factsheet §1.6/§2.5/§3.5). `works` carries the
|
||
/// chat latency (ms) and the /models count.
|
||
enum Outcome: Equatable, Sendable {
|
||
case works(latencyMS: Int, modelCount: Int)
|
||
case authFailed(String)
|
||
case wrongKeyType(String)
|
||
case unreachable(String)
|
||
/// 200 + finish=length/stop_reason=max_tokens with no content — the
|
||
/// cap starved reasoning (§1.5); not "the model broke".
|
||
case starved(String)
|
||
case requestFailed(status: Int, detail: String)
|
||
}
|
||
|
||
/// One HTTP round trip: (body, response). Injected in tests with canned
|
||
/// bodies; production buffers the streamed response (the request still
|
||
/// carries `stream: true` — the wire shape the app's engines use).
|
||
typealias Transport = @Sendable (_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
|
||
|
||
static let urlSessionTransport: Transport = { request in
|
||
let (data, response) = try await URLSession.shared.data(for: request)
|
||
guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }
|
||
return (data, http)
|
||
}
|
||
|
||
/// The two-step probe. Step 1 failure short-circuits (an unreachable or
|
||
/// rejected key on /models needs no chat call); step 2 is the real
|
||
/// key × endpoint × model proof.
|
||
static func probe(_ config: Config, transport: Transport = urlSessionTransport) async -> Outcome {
|
||
guard !config.apiKey.isEmpty else {
|
||
return .authFailed("no API key set — paste the key first")
|
||
}
|
||
let step = await stepModels(config, transport: transport)
|
||
if let failure = step.failure {
|
||
return failure
|
||
}
|
||
let modelCount = step.count ?? 0
|
||
guard let chatRequest = makeChatRequest(config) else {
|
||
return .unreachable("endpoint is not a valid URL")
|
||
}
|
||
let started = Date()
|
||
do {
|
||
let (data, response) = try await transport(chatRequest)
|
||
let elapsed = Int(Date().timeIntervalSince(started) * 1000)
|
||
guard (200 ..< 300).contains(response.statusCode) else {
|
||
return decodeError(status: response.statusCode, body: data, provider: config.provider)
|
||
}
|
||
return decodeChat(provider: config.provider, body: data, modelCount: modelCount, latencyMS: elapsed)
|
||
} catch {
|
||
return .unreachable(error.localizedDescription)
|
||
}
|
||
}
|
||
|
||
// MARK: Requests (factsheet §1–§3 wire shapes)
|
||
|
||
/// The z.ai chat call pins the stable GLM-5.x wire format (§1.5):
|
||
/// thinking enabled + explicit effort (`low` keeps thinking minimal).
|
||
/// OpenAI speaks the RESPONSES API (2026-10-28 maintainer correction:
|
||
/// `POST /v1/responses`, `input`, `max_output_tokens` — the
|
||
/// chat-completions dialect is the retired path); Anthropic requires
|
||
/// `max_tokens` and auths via header, never Bearer. The cap is 512
|
||
/// everywhere — the live 2026-10-28 tail proved 64 starves reasoning
|
||
/// models (glm-5.3: reasoning_tokens 64/64, finish=length, zero
|
||
/// content), so the factsheet's "≈64" would always read starved.
|
||
static func makeChatRequest(_ config: Config) -> URLRequest? {
|
||
guard let url = chatURL(for: config.provider, endpoint: config.endpoint) else { return nil }
|
||
var request = URLRequest(url: url)
|
||
request.httpMethod = "POST"
|
||
request.timeoutInterval = 30
|
||
// 2026-10-28 live incident: without this header URLSession defaults
|
||
// the request to x-www-form-urlencoded — z.ai answers HTTP 200 with
|
||
// an error envelope (content type not supported), OpenAI can't
|
||
// parse the body ("you must provide a model parameter"). curl set
|
||
// it; the app didn't. Anthropic tolerated the omission.
|
||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||
let user: [String: Any] = ["role": "user", "content": "hi"]
|
||
var body: [String: Any] = ["model": config.model, "stream": true]
|
||
switch config.provider {
|
||
case .zai:
|
||
body["messages"] = [user]
|
||
body["max_tokens"] = Self.probeTokenCap
|
||
body["thinking"] = ["type": "enabled"]
|
||
body["reasoning_effort"] = "low"
|
||
case .openaiAPI:
|
||
body["input"] = "hi"
|
||
body["max_output_tokens"] = Self.probeTokenCap
|
||
case .anthropic:
|
||
body["messages"] = [user]
|
||
body["max_tokens"] = Self.probeTokenCap // required
|
||
}
|
||
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
|
||
applyAuth(&request, provider: config.provider, key: config.apiKey)
|
||
return request
|
||
}
|
||
|
||
/// The probe's token cap — generous enough that a reasoning model's
|
||
/// thinking can't starve it (the failure mode is real: 64 burned
|
||
/// entirely on glm-5.3 reasoning), small enough to stay cents.
|
||
static let probeTokenCap = 512
|
||
|
||
static func makeModelsRequest(_ config: Config) -> URLRequest? {
|
||
guard let url = modelsURL(for: config.provider, endpoint: config.endpoint) else { return nil }
|
||
var request = URLRequest(url: url)
|
||
request.timeoutInterval = 20
|
||
applyAuth(&request, provider: config.provider, key: config.apiKey)
|
||
return request
|
||
}
|
||
|
||
/// z.ai's endpoint carries its version segment already (`…/paas/v4`);
|
||
/// Anthropic's base is bare and appends `/v1`; OpenAI speaks the
|
||
/// Responses API (`/v1/responses`, 2026-10-28 maintainer correction —
|
||
/// chat-completions is the retired path). A trailing slash on a
|
||
/// hand-edited endpoint never doubles up. A non-URL endpoint is nil
|
||
/// (URL(string:) happily percent-encodes "not a url" — the scheme check
|
||
/// is what actually rejects garbage; probe reports unreachable, never
|
||
/// traps).
|
||
static func chatURL(for provider: ModelProvider, endpoint: String) -> URL? {
|
||
let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
|
||
let path = switch provider {
|
||
case .anthropic: "/v1/messages"
|
||
case .openaiAPI: "/responses"
|
||
case .zai: "/chat/completions"
|
||
}
|
||
return httpURL(base + path)
|
||
}
|
||
|
||
static func modelsURL(for provider: ModelProvider, endpoint: String) -> URL? {
|
||
let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
|
||
let path = provider == .anthropic ? "/v1/models" : "/models"
|
||
return httpURL(base + path)
|
||
}
|
||
|
||
private static func httpURL(_ string: String) -> URL? {
|
||
guard let url = URL(string: string), let scheme = url.scheme?.lowercased(),
|
||
scheme == "http" || scheme == "https", url.host != nil
|
||
else { return nil }
|
||
return url
|
||
}
|
||
|
||
/// Bearer everywhere except Anthropic: `x-api-key` + a pinned
|
||
/// `anthropic-version` (factsheet §2.1 — never send none).
|
||
static func applyAuth(_ request: inout URLRequest, provider: ModelProvider, key: String) {
|
||
switch provider {
|
||
case .zai, .openaiAPI:
|
||
request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
|
||
case .anthropic:
|
||
request.setValue(key, forHTTPHeaderField: "x-api-key")
|
||
request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version")
|
||
}
|
||
}
|
||
|
||
// MARK: Step 1 — models (key validity + reachability)
|
||
|
||
private static func stepModels(_ config: Config, transport: Transport) async -> (count: Int?, failure: Outcome?) {
|
||
guard let request = makeModelsRequest(config) else {
|
||
return (nil, .unreachable("endpoint is not a valid URL"))
|
||
}
|
||
do {
|
||
let (data, response) = try await transport(request)
|
||
guard (200 ..< 300).contains(response.statusCode) else {
|
||
return (nil, decodeError(status: response.statusCode, body: data, provider: config.provider))
|
||
}
|
||
// A foreign-shaped 200 still lets the chat step run — /models is
|
||
// the prelude, the chat call is the proof (§1.2).
|
||
return (decodeModelsCount(data) ?? 0, nil)
|
||
} catch {
|
||
return (nil, .unreachable(error.localizedDescription))
|
||
}
|
||
}
|
||
|
||
/// All three listings put the entries in `data: []`.
|
||
static func decodeModelsCount(_ data: Data) -> Int? {
|
||
guard let parsed = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||
let entries = parsed["data"] as? [Any]
|
||
else { return nil }
|
||
return entries.count
|
||
}
|
||
|
||
// MARK: Decode — the factsheet cases (pure; unit-pinned)
|
||
|
||
/// Maps an HTTP error envelope to the honest verdict: z.ai
|
||
/// `error.code` (1113 = wrong key type for this endpoint family, 401 =
|
||
/// auth), Anthropic `error.type` + `request_id`, OpenAI `error.code`.
|
||
static func decodeError(status: Int, body: Data, provider: ModelProvider) -> Outcome {
|
||
let root = (try? JSONSerialization.jsonObject(with: body)).flatMap { $0 as? [String: Any] }
|
||
return decodeErrorRoot(status: status, root: root ?? [:], provider: provider)
|
||
}
|
||
|
||
/// The same decode over an already-parsed envelope — the SSE path
|
||
/// holds the parsed object, no serialize-then-reparse round trip.
|
||
private static func decodeErrorRoot(status: Int, root: [String: Any], provider: ModelProvider) -> Outcome {
|
||
let envelope = (root["error"] as? [String: Any]) ?? [:]
|
||
let code = envelope["code"] as? String ?? ""
|
||
let type = envelope["type"] as? String ?? ""
|
||
let message = (envelope["message"] as? String) ?? "HTTP \(status)"
|
||
let requestID = (root["request_id"] as? String).map { " (request \($0))" } ?? ""
|
||
|
||
if provider == .zai, code == "1113" {
|
||
return .wrongKeyType("z.ai 1113 — wrong key type for this endpoint family; switch the key type")
|
||
}
|
||
if status == 401 || code == "401" || code == "invalid_api_key" || type == "authentication_error" {
|
||
return .authFailed(message + requestID)
|
||
}
|
||
return .requestFailed(status: status, detail: message + requestID)
|
||
}
|
||
|
||
/// A 2xx chat response: SSE events (the request streamed). Content
|
||
/// arrived → works; the finish marker says length/max_tokens/
|
||
/// incomplete with no content → starved; no content at all →
|
||
/// requestFailed (never a silent "works" on an empty 200, §4.4).
|
||
/// HTTP 200 can also CARRY the provider's error — live 2026-10-28: z.ai
|
||
/// answers a wrong content-type as 200 + a plain-JSON error envelope —
|
||
/// so the envelope decodes before any no-content fallback.
|
||
static func decodeChat(provider: ModelProvider, body: Data, modelCount: Int, latencyMS: Int) -> Outcome {
|
||
let raw = String(bytes: body, encoding: .utf8) ?? ""
|
||
let events = ssePayloads(raw)
|
||
if let failure = errorEnvelope(in: events, rawBody: body, provider: provider) {
|
||
return failure
|
||
}
|
||
let (text, finish): (String, String?)
|
||
switch provider {
|
||
case .anthropic: (text, finish) = anthropicStream(events)
|
||
case .openaiAPI: (text, finish) = responsesStream(events)
|
||
case .zai: (text, finish) = chatCompletionsStream(events)
|
||
}
|
||
if !text.isEmpty {
|
||
return .works(latencyMS: latencyMS, modelCount: modelCount)
|
||
}
|
||
if finish == "length" || finish == "max_tokens" || finish == "incomplete" {
|
||
return .starved("finish=\(finish!) with empty content — raise the token cap")
|
||
}
|
||
return .requestFailed(status: 200, detail: "no content (finish=\(finish ?? "none"))")
|
||
}
|
||
|
||
/// Errors riding a 2xx: an `error` OBJECT in any SSE event (OpenAI
|
||
/// Responses nests it under `response.error` — and every response
|
||
/// snapshot carries `"error": null`, which is NOT an error), or the
|
||
/// whole body as a plain-JSON envelope (z.ai's 200 content-type
|
||
/// rejection) — routed through the same decoder as HTTP errors.
|
||
private static func errorEnvelope(in events: [JSONValue], rawBody: Data, provider: ModelProvider) -> Outcome? {
|
||
for event in events {
|
||
guard case let .object(obj) = event else { continue }
|
||
var envelope = obj
|
||
if !isError(obj["error"]), case let .object(response)? = obj["response"] {
|
||
envelope = response // response.failed carries response.error
|
||
}
|
||
guard isError(envelope["error"]),
|
||
let root = JSONValue.object(envelope).any as? [String: Any]
|
||
else { continue }
|
||
return decodeErrorRoot(status: 200, root: root, provider: provider)
|
||
}
|
||
if let parsed = try? JSONSerialization.jsonObject(with: rawBody) as? [String: Any], parsed["error"] is [String: Any] {
|
||
return decodeErrorRoot(status: 200, root: parsed, provider: provider)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
/// JSON null isn't nil — OpenAI's response snapshots carry `"error":
|
||
/// null` on every event; only a real error object counts (2026-10-28
|
||
/// dogfood: the null tripped the check and a healthy stream decoded as
|
||
/// "HTTP 200").
|
||
private static func isError(_ value: JSONValue?) -> Bool {
|
||
if case .object = value {
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
/// Anthropic SSE: `content_block_delta.delta.text_delta` carries text,
|
||
/// `message_delta.delta.stop_reason` the finish marker.
|
||
private static func anthropicStream(_ events: [JSONValue]) -> (text: String, finish: String?) {
|
||
var text = ""
|
||
var finish: String?
|
||
for event in events {
|
||
guard case let .object(obj) = event, case let .object(delta)? = obj["delta"] else { continue }
|
||
if delta["type"] == .string("text_delta"), case let .string(chunk)? = delta["text"] {
|
||
text += chunk
|
||
}
|
||
if case let .string(reason)? = delta["stop_reason"] {
|
||
finish = reason
|
||
}
|
||
}
|
||
return (text, finish)
|
||
}
|
||
|
||
/// z.ai SSE (chat-completions dialect): `choices[0].delta.content`
|
||
/// carries text (the reasoning side-channel is ignored), the last
|
||
/// non-null `choices[0].finish_reason` the finish marker; usage chunks
|
||
/// carry an empty `choices` array and skip through.
|
||
private static func chatCompletionsStream(_ events: [JSONValue]) -> (text: String, finish: String?) {
|
||
var text = ""
|
||
var finish: String?
|
||
for event in events {
|
||
guard case let .object(obj) = event,
|
||
case let .array(choices)? = obj["choices"],
|
||
case let .object(choice)? = choices.first
|
||
else { continue }
|
||
if case let .object(delta) = choice["delta"], case let .string(chunk)? = delta["content"] {
|
||
text += chunk
|
||
}
|
||
if case let .string(reason)? = choice["finish_reason"] {
|
||
finish = reason
|
||
}
|
||
}
|
||
return (text, finish)
|
||
}
|
||
|
||
/// OpenAI Responses SSE: `response.output_text.delta` events carry text
|
||
/// (`.delta` string); the closing `response.completed`/`incomplete`/
|
||
/// `failed` events carry `response.status`.
|
||
private static func responsesStream(_ events: [JSONValue]) -> (text: String, finish: String?) {
|
||
var text = ""
|
||
var finish: String?
|
||
for event in events {
|
||
guard case let .object(obj) = event else { continue }
|
||
if obj["type"] == .string("response.output_text.delta"), case let .string(chunk)? = obj["delta"] {
|
||
text += chunk
|
||
}
|
||
if case let .object(response)? = obj["response"], case let .string(status)? = response["status"] {
|
||
finish = status
|
||
}
|
||
}
|
||
return (text, finish)
|
||
}
|
||
|
||
/// SSE event payloads: `data: {…}` lines as JSON values. `data:
|
||
/// [DONE]`, `event:` lines, and blanks are not payloads.
|
||
static func ssePayloads(_ text: String) -> [JSONValue] {
|
||
var payloads: [JSONValue] = []
|
||
for line in text.split(separator: "\n") {
|
||
guard line.hasPrefix("data:") else { continue }
|
||
let payload = line.dropFirst("data:".count).trimmingCharacters(in: .whitespaces)
|
||
guard payload != "[DONE]", !payload.isEmpty,
|
||
let data = payload.data(using: .utf8),
|
||
let parsed = try? JSONSerialization.jsonObject(with: data)
|
||
else { continue }
|
||
payloads.append(JSONValue(parsed))
|
||
}
|
||
return payloads
|
||
}
|
||
}
|