Files
museion/Museion/ProviderProbe.swift
AlexKucera f49e4b6ca0
CI / ci (push) Canceled after 0s
refactor(settings): provider facts as data
#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
2026-11-10 10:58:29 +01:00

375 lines
16 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// 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
case .nous:
// #175: plain OpenAI chat-completions — live-probed, the portal
// router takes no thinking knobs and answers finish=stop.
body["messages"] = [user]
body["max_tokens"] = Self.probeTokenCap
}
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). Nous (#175, live-probed
/// 2026-11-05) is plain OpenAI chat-completions on a versioned base.
/// #181: the paths live on the descriptor's dialect — 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 = ModelProvider.trimmedEndpoint(endpoint)
return httpURL(base + provider.dialect.chatPath)
}
static func modelsURL(for provider: ModelProvider, endpoint: String) -> URL? {
let base = ModelProvider.trimmedEndpoint(endpoint)
return httpURL(base + provider.dialect.modelsPath)
}
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). Nous rides
/// Bearer too — the portal accepts the session agent_key and an API
/// key interchangeably (#175). #181: the shape keys off the
/// descriptor's auth mode.
static func applyAuth(_ request: inout URLRequest, provider: ModelProvider, key: String) {
switch provider.authMode {
case .bearer:
request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
case let .headerKey(version):
request.setValue(key, forHTTPHeaderField: "x-api-key")
request.setValue(version, 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 ?? ""
// #175: the portal's envelope is bare {status, message} — no error
// object — so fall back to the root message (existing providers
// always carry an error object; the fallback is invisible to them).
let message = (envelope["message"] as? String) ?? (root["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.dialect {
case .anthropic: (text, finish) = anthropicStream(events)
case .responses: (text, finish) = responsesStream(events)
case .chatCompletions: (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
}
}