feat(m1): Ollama client, catalog, streaming chat and CLI (T1.1-T1.6)

Add endpoint policy and redirect-safe ephemeral HTTP client, error mapping, catalog cache and version checks, streaming chat with phase timeouts/cancellation, provisional Hy-MT3 prompt/language/request factory, warm-up policy, and sprachmittler-cli models/show/translate. Recapture the 7B fixtures; defer the 1.8B VERIFY items; document ADR-016. Also fix the signature checker's pipefail SIGPIPE issue.
This commit is contained in:
schihei committed 2026-11-26 13:04:22 +01:00
1 parent 7ca5c710ec
commit 26b493e7e5
93 files changed
+3732 -218

No files matched your search

@@ -0,0 +1,18 @@
import Foundation
/// A testable sleep seam for phase timeouts.
public protocol AsyncSleeper: Sendable {
/// Sleeps for the duration, or throws `CancellationError` when the task is cancelled.
func sleep(for duration: Duration) async throws
}
/// The production sleeper backed by the continuous clock.
public struct ContinuousClockSleeper: AsyncSleeper {
/// Creates a continuous-clock sleeper.
public init() {}
/// Sleeps for the duration, or throws `CancellationError` when the task is cancelled.
public func sleep(for duration: Duration) async throws {
try await Task.sleep(for: duration)
}
}
@@ -0,0 +1,7 @@
/// One event from a streaming `/api/chat` response.
public enum ChatEvent: Sendable, Equatable {
/// A content delta.
case delta(String)
/// The final object, with `done_reason` and metrics.
case done(reason: String?, metrics: ChatMetrics)
}
@@ -0,0 +1,13 @@
/// One chat message. v1 sends exactly one user message and never a system message.
public struct ChatMessage: Sendable, Equatable, Codable {
/// The role; always `user` in v1.
public let role: String
/// The message text (the documented prompt).
public let content: String
/// Creates a message.
public init(role: String = "user", content: String) {
self.role = role
self.content = content
}
}
@@ -0,0 +1,35 @@
/// Timing counters from a completed `/api/chat` response. Durations are nanoseconds.
public struct ChatMetrics: Sendable, Equatable {
/// `total_duration`.
public let totalDuration: Int64?
/// `load_duration`.
public let loadDuration: Int64?
/// `prompt_eval_count`.
public let promptEvalCount: Int?
/// `prompt_eval_duration`.
public let promptEvalDuration: Int64?
/// `eval_count`.
public let evalCount: Int?
/// `eval_duration`.
public let evalDuration: Int64?
/// Creates a metrics value.
public init(
totalDuration: Int64? = nil,
loadDuration: Int64? = nil,
promptEvalCount: Int? = nil,
promptEvalDuration: Int64? = nil,
evalCount: Int? = nil,
evalDuration: Int64? = nil
) {
self.totalDuration = totalDuration
self.loadDuration = loadDuration
self.promptEvalCount = promptEvalCount
self.promptEvalDuration = promptEvalDuration
self.evalCount = evalCount
self.evalDuration = evalDuration
}
/// An empty metrics value for streams that never produced a final object.
public static let empty = ChatMetrics()
}
@@ -0,0 +1,42 @@
/// Ollama sampling options. The names on the wire are the publisher's Ollama names, not the
/// model card's names (see docs/OLLAMA_TRANSLATION_API.md §4).
public struct ChatOptions: Sendable, Equatable, Codable {
/// `temperature`.
public let temperature: Double
/// `top_p`.
public let topP: Double
/// `top_k`.
public let topK: Int
/// `repeat_penalty`.
public let repeatPenalty: Double
/// `num_predict`.
public let numPredict: Int
/// `num_ctx`.
public let numCtx: Int
/// Creates options.
public init(
temperature: Double,
topP: Double,
topK: Int,
repeatPenalty: Double,
numPredict: Int,
numCtx: Int
) {
self.temperature = temperature
self.topP = topP
self.topK = topK
self.repeatPenalty = repeatPenalty
self.numPredict = numPredict
self.numCtx = numCtx
}
private enum CodingKeys: String, CodingKey {
case temperature
case topP = "top_p"
case topK = "top_k"
case repeatPenalty = "repeat_penalty"
case numPredict = "num_predict"
case numCtx = "num_ctx"
}
}
@@ -0,0 +1,36 @@
/// A streaming `/api/chat` request.
public struct ChatRequest: Sendable, Equatable, Encodable {
/// The model tag.
public let model: String
/// Exactly one user message in v1.
public let messages: [ChatMessage]
/// Always true for translation and warm-up.
public let stream: Bool
/// The Ollama `keep_alive` value.
public let keepAlive: String
/// The sampling options.
public let options: ChatOptions
/// Creates a request.
public init(
model: String,
messages: [ChatMessage],
stream: Bool = true,
keepAlive: String = "30m",
options: ChatOptions
) {
self.model = model
self.messages = messages
self.stream = stream
self.keepAlive = keepAlive
self.options = options
}
private enum CodingKeys: String, CodingKey {
case model
case messages
case stream
case keepAlive = "keep_alive"
case options
}
}
@@ -0,0 +1,77 @@
import Foundation
/// Owns the stream continuation and the producing task. All state is actor-isolated.
actor ChatStreamContext {
private let continuation: AsyncThrowingStream<ChatEvent, any Error>.Continuation
private var task: Task<Void, Never>?
private var finished = false
private var sawDone = false
private var started = false
private var startContinuation: CheckedContinuation<Void, Never>?
init(continuation: AsyncThrowingStream<ChatEvent, any Error>.Continuation) {
self.continuation = continuation
}
/// Blocks the producer until `setTask` has stored its cancellation handle.
func waitForStart() async {
if started {
return
}
await withCheckedContinuation { continuation in
startContinuation = continuation
}
}
func setTask(_ task: Task<Void, Never>) {
self.task = task
started = true
startContinuation?.resume()
startContinuation = nil
if finished {
task.cancel()
}
}
func markDone() {
sawDone = true
}
func finishIfDone() {
guard !finished else { return }
if sawDone {
finish()
} else {
fail(OllamaError.decoding("Stream ended without a done event"))
}
}
func emit(_ event: ChatEvent) {
guard !finished else { return }
continuation.yield(event)
}
func finish() {
guard !finished else { return }
finished = true
continuation.finish()
task?.cancel()
task = nil
}
func fail(_ error: any Error) {
guard !finished else { return }
finished = true
continuation.finish(throwing: error)
task?.cancel()
task = nil
}
func cancel() {
guard !finished else { return }
finished = true
continuation.finish()
task?.cancel()
task = nil
}
}
@@ -0,0 +1,44 @@
import Foundation
/// Schedules one timeout at a time. Scheduling a new phase cancels the previous timer.
actor ChatTimeoutController {
private let sleeper: any AsyncSleeper
private var generation = 0
private var task: Task<Void, Never>?
private var handler: (@Sendable (TimeoutPhase) -> Void)?
init(sleeper: any AsyncSleeper) {
self.sleeper = sleeper
}
func schedule(
_ phase: TimeoutPhase,
after duration: Duration,
onTimeout: @escaping @Sendable (TimeoutPhase) -> Void
) {
generation += 1
let expected = generation
task?.cancel()
handler = onTimeout
task = Task { [weak self, sleeper] in
do {
try await sleeper.sleep(for: duration)
} catch {
return
}
await self?.fire(expected, phase)
}
}
private func fire(_ expected: Int, _ phase: TimeoutPhase) {
guard expected == generation else { return }
handler?(phase)
}
func cancel() {
generation += 1
task?.cancel()
task = nil
handler = nil
}
}
@@ -0,0 +1,23 @@
/// Per-phase timeout budgets for one chat chunk.
public struct ChatTimeouts: Sendable, Equatable {
/// Request sent to the first content byte; includes a cold model load.
public let firstToken: Duration
/// Gap between stream lines once streaming has started.
public let idle: Duration
/// Hard cap for one chunk.
public let total: Duration
/// Creates a budget.
public init(firstToken: Duration, idle: Duration, total: Duration) {
self.firstToken = firstToken
self.idle = idle
self.total = total
}
/// The documented defaults (docs/OLLAMA_TRANSLATION_API.md §1.3).
public static let standard = ChatTimeouts(
firstToken: .seconds(120),
idle: .seconds(20),
total: .seconds(180)
)
}
@@ -0,0 +1,35 @@
import Foundation
/// Validates the configured Ollama endpoint before any request is built (SP-5, SP-6).
public enum EndpointPolicy {
/// Returns the validated base URL, or throws `EndpointRejection`.
///
/// Loopback (`127.0.0.1`, `localhost`, `::1`) may use `http` or `https`. A remote host needs
/// the explicit `allowRemote` toggle and `https`.
public static func validate(_ url: URL, allowRemote: Bool) throws -> URL {
guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else {
throw EndpointRejection.scheme
}
guard url.user == nil, url.password == nil, url.query == nil, url.fragment == nil,
let host = url.host?.lowercased(), !host.isEmpty
else {
throw EndpointRejection.form
}
if isLoopback(url) {
return url
}
guard allowRemote else {
throw EndpointRejection.remoteNotAllowed
}
guard scheme == "https" else {
throw EndpointRejection.remoteRequiresHTTPS
}
return url
}
/// True for the three loopback spellings the app accepts.
public static func isLoopback(_ url: URL) -> Bool {
guard let host = url.host?.lowercased() else { return false }
return ["127.0.0.1", "localhost", "::1"].contains(host)
}
}
@@ -0,0 +1,13 @@
/// Why an Ollama endpoint was rejected before any request was sent (SP-5, SP-6).
public enum EndpointRejection: Error, Sendable, Equatable {
/// The URL scheme is not `http` or `https`.
case scheme
/// The URL carries user info, a query or a fragment.
case form
/// A non-loopback endpoint was configured without the explicit remote toggle.
case remoteNotAllowed
/// A remote endpoint uses `http` instead of `https`.
case remoteRequiresHTTPS
/// A redirect response was refused.
case redirect
}
@@ -0,0 +1,61 @@
import Foundation
/// One model returned by `GET /api/tags`.
public struct InstalledModel: Sendable, Equatable, Decodable {
/// The user-facing tag, e.g. `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M`.
public let name: String
/// The tag as Ollama reports it (normally identical to `name`).
public let model: String
/// The ISO-8601 modification time, when present.
public let modifiedAt: String?
/// The model size in bytes, when present.
public let size: Int64?
/// The full sha256 digest.
public let digest: String
/// The optional family/quantization details.
public let details: ModelDetailsInfo?
/// Creates a model value.
public init(
name: String,
model: String,
modifiedAt: String? = nil,
size: Int64? = nil,
digest: String,
details: ModelDetailsInfo? = nil
) {
self.name = name
self.model = model
self.modifiedAt = modifiedAt
self.size = size
self.digest = digest
self.details = details
}
/// True when the tag or model name contains `hy-mt3`, case-insensitively.
///
/// Temporary for the M1 CLI filter; the adapter registry (T2.1) owns family matching in M2.
public var isHyMT3: Bool {
name.localizedCaseInsensitiveContains("hy-mt3")
|| model.localizedCaseInsensitiveContains("hy-mt3")
}
/// `name` with a trailing `:latest` removed.
public var normalizedName: String {
Self.normalizedName(name)
}
/// Removes only a trailing `:latest`; other tags are preserved.
public static func normalizedName(_ name: String) -> String {
name.hasSuffix(":latest") ? String(name.dropLast(":latest".count)) : name
}
private enum CodingKeys: String, CodingKey {
case name
case model
case modifiedAt = "modified_at"
case size
case digest
case details
}
}
@@ -0,0 +1,23 @@
import Foundation
/// One model returned by `GET /api/ps`.
public struct LoadedModel: Sendable, Equatable, Decodable {
/// The model tag.
public let name: String
/// The tag as Ollama reports it, when present.
public let model: String?
/// The total resident size in bytes.
public let size: Int64?
/// The resident size in VRAM in bytes.
public let sizeVRAM: Int64?
/// When Ollama will unload the model.
public let expiresAt: String?
private enum CodingKeys: String, CodingKey {
case name
case model
case size
case sizeVRAM = "size_vram"
case expiresAt = "expires_at"
}
}
@@ -0,0 +1,121 @@
import Foundation
/// The details block returned by `/api/tags` and `/api/show`.
public struct ModelDetailsInfo: Sendable, Equatable, Decodable {
/// The parent model tag, when reported.
public let parentModel: String?
/// The format, normally `gguf`.
public let format: String?
/// The model family, e.g. `hunyuan-dense`.
public let family: String?
/// All reported families.
public let families: [String]?
/// The parameter size string, e.g. `7.5B`.
public let parameterSize: String?
/// The quantization level, e.g. `Q4_K_M`.
public let quantizationLevel: String?
/// The base context length from `/api/tags` details, when present (the adapter uses 8192).
public let contextLength: Int?
/// The embedding length from `/api/tags` details, when present.
public let embeddingLength: Int?
/// The runner name, when reported.
public let runner: String?
private enum CodingKeys: String, CodingKey {
case parentModel = "parent_model"
case format
case family
case families
case parameterSize = "parameter_size"
case quantizationLevel = "quantization_level"
case contextLength = "context_length"
case embeddingLength = "embedding_length"
case runner
}
}
/// One parameter line from `/api/show`'s `parameters` string.
public struct ModelParameter: Sendable, Equatable {
/// The parameter name, e.g. `stop`.
public let name: String
/// The parameter value with surrounding quotes removed.
public let value: String
/// Creates a parameter.
public init(name: String, value: String) {
self.name = name
self.value = value
}
/// Parses the newline-separated `name value` lines from `/api/show`.
public static func parse(_ text: String) -> [ModelParameter] {
text.split(separator: "\n").compactMap { line in
let trimmed = line.trimmingCharacters(in: .whitespaces)
guard let separator = trimmed.firstIndex(where: { $0 == " " || $0 == "\t" }) else {
return nil
}
let name = String(trimmed[..<separator])
var value = String(trimmed[separator...]).trimmingCharacters(in: .whitespaces)
if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 {
value = String(value.dropFirst().dropLast())
}
return ModelParameter(name: name, value: value)
}
}
}
/// The fields from `POST /api/show` that v1 uses.
public struct ModelDetails: Sendable, Equatable, Decodable {
/// Capabilities such as `completion`; empty when omitted.
public let capabilities: [String]
/// Family and quantization details.
public let details: ModelDetailsInfo?
/// The raw parameter lines; parse them with `ModelParameter.parse`.
public let parameters: String?
/// The chat template.
public let template: String?
/// The server-reported licence; `null` for the current GGUF.
public let license: String?
/// Creates model details.
public init(
capabilities: [String] = [],
details: ModelDetailsInfo? = nil,
parameters: String? = nil,
template: String? = nil,
license: String? = nil
) {
self.capabilities = capabilities
self.details = details
self.parameters = parameters
self.template = template
self.license = license
}
/// The parsed parameter lines, preserving repeated keys such as `stop`.
public var parsedParameters: [ModelParameter] {
ModelParameter.parse(parameters ?? "")
}
/// True when the model reports text completion.
public var supportsCompletion: Bool {
capabilities.contains("completion")
}
private enum CodingKeys: String, CodingKey {
case capabilities
case details
case parameters
case template
case license
}
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
capabilities = try container.decodeIfPresent([String].self, forKey: .capabilities) ?? []
details = try container.decodeIfPresent(ModelDetailsInfo.self, forKey: .details)
parameters = try container.decodeIfPresent(String.self, forKey: .parameters)
template = try container.decodeIfPresent(String.self, forKey: .template)
license = try container.decodeIfPresent(String.self, forKey: .license)
}
}
@@ -0,0 +1,15 @@
/// Model discovery and inspection against a running Ollama server.
public protocol OllamaCatalog: Sendable {
/// `GET /api/version`.
func serverVersion() async throws -> String
/// `GET /api/tags`.
func installedModels() async throws -> [InstalledModel]
/// `POST /api/show`.
func show(model: String) async throws -> ModelDetails
/// `GET /api/ps`.
func loadedModels() async throws -> [LoadedModel]
/// Clears the per-digest details cache and the name→digest map after a pull or removal.
func refresh() async
/// Throws when the server is older than the minimum supported version.
func checkMinimumVersion() async throws
}
@@ -0,0 +1,117 @@
import Foundation
/// The concrete catalog client. Model details are cached by digest for the app lifetime;
/// `refresh()` invalidates the cache after a model pull or removal.
public actor OllamaCatalogClient: OllamaCatalog {
private let http: any OllamaHTTPTransport
private let minimumVersion: OllamaVersion
private var detailsByDigest: [String: ModelDetails] = [:]
private var digestByName: [String: String] = [:]
/// Creates a catalog client over an HTTP transport.
public init(http: any OllamaHTTPTransport, minimumVersion: OllamaVersion = .minimumSupported) {
self.http = http
self.minimumVersion = minimumVersion
}
public func serverVersion() async throws -> String {
let response = try await http.send(.init(path: "/api/version"), model: nil)
return try decode(VersionResponse.self, from: response).version
}
public func installedModels() async throws -> [InstalledModel] {
let response = try await http.send(.init(path: "/api/tags"), model: nil)
let models = try decode(TagsResponse.self, from: response).models
digestByName = models.reduce(into: [:]) { result, model in
result[model.normalizedName] = model.digest
}
return models
}
public func show(model: String) async throws -> ModelDetails {
let normalized = InstalledModel.normalizedName(model)
if digestByName[normalized] == nil {
_ = try await installedModels()
}
if let digest = digestByName[normalized], let cached = detailsByDigest[digest] {
return cached
}
let body = try JSONEncoder().encode(ShowRequest(model: model))
let request = OllamaHTTPRequest(method: .post, path: "/api/show", body: body)
let response = try await http.send(request, model: model)
let details = try decode(ModelDetails.self, from: response)
if let digest = digestByName[normalized] {
detailsByDigest[digest] = details
}
return details
}
public func loadedModels() async throws -> [LoadedModel] {
let response = try await http.send(.init(path: "/api/ps"), model: nil)
return try decode(PsResponse.self, from: response).models
}
/// Clears the per-digest details cache and the name→digest map.
public func refresh() async {
detailsByDigest.removeAll()
digestByName.removeAll()
}
/// Throws `OllamaError.unsupportedVersion` when the server is older than the minimum.
public func checkMinimumVersion() async throws {
let found = try await serverVersion()
guard let parsed = OllamaVersion(found), parsed >= minimumVersion else {
throw OllamaError.unsupportedVersion(
found: found,
required: minimumVersion.description
)
}
}
private func decode<Value: Decodable>(
_ type: Value.Type,
from response: OllamaHTTPResponse
) throws -> Value {
do {
return try JSONDecoder().decode(type, from: response.body)
} catch {
throw OllamaError.decoding("Invalid \(type) response")
}
}
}
private struct VersionResponse: Decodable {
let version: String
}
private struct TagsResponse: Decodable {
let models: [InstalledModel]
private enum CodingKeys: String, CodingKey {
case models
}
init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
models = try container.decodeIfPresent([InstalledModel].self, forKey: .models) ?? []
}
}
private struct PsResponse: Decodable {
let models: [LoadedModel]
private enum CodingKeys: String, CodingKey {
case models
}
init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
models = try container.decodeIfPresent([LoadedModel].self, forKey: .models) ?? []
}
}
private struct ShowRequest: Encodable {
let model: String
}
@@ -0,0 +1,187 @@
import Foundation
/// The streaming Ollama chat client. One task reads NDJSON lines; a timeout controller guards
/// first-token, idle and total phases.
public struct OllamaChatClient: OllamaChatting, Sendable {
private let http: OllamaHTTPClient
private let sleeper: any AsyncSleeper
private let timeouts: ChatTimeouts
/// Creates a chat client.
public init(
http: OllamaHTTPClient,
sleeper: any AsyncSleeper = ContinuousClockSleeper(),
timeouts: ChatTimeouts = .standard
) {
self.http = http
self.sleeper = sleeper
self.timeouts = timeouts
}
/// Streams deltas and one final `done` event. Throws `OllamaError` on failure.
public func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error> {
AsyncThrowingStream { continuation in
let context = ChatStreamContext(continuation: continuation)
let task = Task {
await context.waitForStart()
await run(request, context: context)
}
Task {
await context.setTask(task)
}
continuation.onTermination = { @Sendable _ in
task.cancel()
Task {
await context.cancel()
}
}
}
}
private func run(_ request: ChatRequest, context: ChatStreamContext) async {
if Task.isCancelled {
await context.cancel()
return
}
let phase = ChatTimeoutController(sleeper: sleeper)
let total = ChatTimeoutController(sleeper: sleeper)
do {
let body = try JSONEncoder().encode(request)
let httpRequest = OllamaHTTPRequest(method: .post, path: "/api/chat", body: body)
await phase.schedule(.firstToken, after: timeouts.firstToken) { phase in
Task {
await context.fail(OllamaError.timeout(phase))
}
}
await total.schedule(.total, after: timeouts.total) { phase in
Task {
await context.fail(OllamaError.timeout(phase))
}
}
try await http.stream(httpRequest, model: request.model) { line in
try await handle(
line,
request: request,
context: context,
phase: phase,
total: total
)
}
await context.finishIfDone()
} catch let error as OllamaError {
if case .cancelled = error {
await context.cancel()
} else {
await context.fail(error)
}
} catch is CancellationError {
await context.cancel()
} catch {
await context.fail(OllamaError.decoding("Stream failed"))
}
await phase.cancel()
await total.cancel()
}
private func handle(
_ line: String,
request: ChatRequest,
context: ChatStreamContext,
phase: ChatTimeoutController,
total: ChatTimeoutController
) async throws -> StreamLineAction {
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
return .continueStream
}
guard let data = trimmed.data(using: .utf8) else {
throw OllamaError.decoding("Invalid stream line")
}
let object: StreamLine
do {
object = try JSONDecoder().decode(StreamLine.self, from: data)
} catch {
throw OllamaError.decoding("Invalid stream line")
}
if let message = object.error, !message.isEmpty {
throw streamError(message, model: request.model)
}
if let content = object.message?.content, !content.isEmpty {
await phase.schedule(.idle, after: timeouts.idle) { phase in
Task {
await context.fail(OllamaError.timeout(phase))
}
}
await context.emit(.delta(content))
}
if object.done == true {
await phase.cancel()
await total.cancel()
// Unknown done_reason values are passed through unchanged. Logging them at .info
// needs an injected logger in M2/M4.
await context.markDone()
await context.emit(.done(reason: object.doneReason, metrics: object.metrics))
await context.finish()
return .stop
}
return .continueStream
}
private func streamError(_ message: String, model: String) -> OllamaError {
if message.localizedCaseInsensitiveContains("not found") {
return .modelNotInstalled(model)
}
return .server(status: 0, message: message)
}
}
/// One NDJSON object from `/api/chat`.
private struct StreamLine: Decodable {
struct Message: Decodable {
let content: String?
}
let message: Message?
let done: Bool?
let doneReason: String?
let error: String?
let totalDuration: Int64?
let loadDuration: Int64?
let promptEvalCount: Int?
let promptEvalDuration: Int64?
let evalCount: Int?
let evalDuration: Int64?
var metrics: ChatMetrics {
ChatMetrics(
totalDuration: totalDuration,
loadDuration: loadDuration,
promptEvalCount: promptEvalCount,
promptEvalDuration: promptEvalDuration,
evalCount: evalCount,
evalDuration: evalDuration
)
}
private enum CodingKeys: String, CodingKey {
case message
case done
case doneReason = "done_reason"
case error
case totalDuration = "total_duration"
case loadDuration = "load_duration"
case promptEvalCount = "prompt_eval_count"
case promptEvalDuration = "prompt_eval_duration"
case evalCount = "eval_count"
case evalDuration = "eval_duration"
}
}
@@ -0,0 +1,5 @@
/// The streaming chat contract from ARCHITECTURE §8.1.
public protocol OllamaChatting: Sendable {
/// Streams deltas and one final `done` event. Throws `OllamaError` on failure.
func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error>
}
@@ -0,0 +1,26 @@
import Foundation
/// Transport-, policy- and HTTP-level failures from the Ollama client.
///
/// This is the leaf module's error vocabulary. `SprachmittlerCore` maps it to
/// `SprachmittlerError` at the boundary; the leaf never depends on Core.
public enum OllamaError: Error, Sendable, Equatable {
/// The endpoint failed `EndpointPolicy` or a redirect was refused.
case endpointRejected(EndpointRejection)
/// Connection refused, host unreachable or another transport failure.
case unreachable(URL)
/// A 404 whose body says the model was not found.
case modelNotInstalled(String)
/// A 400-class request problem, with a truncated server message.
case badRequest(String)
/// Any other non-2xx status, with a truncated server message.
case server(status: Int, message: String)
/// A timeout in the given phase.
case timeout(TimeoutPhase)
/// The task was cancelled.
case cancelled
/// A response body could not be decoded.
case decoding(String)
/// The Ollama server is older than the minimum supported version.
case unsupportedVersion(found: String, required: String)
}
@@ -0,0 +1,28 @@
import Foundation
/// Extracts a short, non-user-facing message from an Ollama error body.
///
/// The body is `{"error":"…"}`; plain text is accepted as a fallback. The result is capped at
/// 500 characters and is never shown raw to the user or logged in clear.
enum OllamaErrorBody {
static func message(from data: Data) -> String? {
if let envelope = try? JSONDecoder().decode(ErrorEnvelope.self, from: data), !envelope.error.isEmpty {
return truncate(envelope.error)
}
guard let text = String(data: data, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines),
!text.isEmpty
else {
return nil
}
return truncate(text)
}
private static func truncate(_ value: String) -> String {
value.count > 500 ? String(value.prefix(500)) : value
}
private struct ErrorEnvelope: Decodable {
let error: String
}
}
@@ -0,0 +1,197 @@
import Foundation
/// The JSON HTTP client for Ollama. The only module that builds `URLRequest`s and owns a
/// `URLSession` (SP-4, SP-6).
public final class OllamaHTTPClient: OllamaHTTPTransport, Sendable {
/// The validated base URL, e.g. `http://127.0.0.1:11434`.
public let baseURL: URL
let session: URLSession
/// Creates a client with an ephemeral session and a redirect-refusing delegate.
public init(baseURL: URL, allowRemote: Bool = false) throws {
let validated: URL
do {
validated = try EndpointPolicy.validate(baseURL, allowRemote: allowRemote)
} catch let rejection as EndpointRejection {
throw OllamaError.endpointRejected(rejection)
}
self.baseURL = validated
session = URLSession(
configuration: OllamaSessionFactory.makeConfiguration(),
delegate: RedirectRefusingDelegate(),
delegateQueue: nil
)
}
/// Test seam: inject a session with a `URLProtocol` stub.
init(baseURL: URL, session: URLSession) throws {
let validated: URL
do {
validated = try EndpointPolicy.validate(baseURL, allowRemote: false)
} catch let rejection as EndpointRejection {
throw OllamaError.endpointRejected(rejection)
}
self.baseURL = validated
self.session = session
}
deinit {
session.invalidateAndCancel()
}
/// Sends a request and returns a 2xx response. Non-2xx statuses and transport failures are
/// mapped to `OllamaError`.
///
/// - Parameter model: the model tag for a 404 body check; pass it for chat/show requests.
public func send(_ request: OllamaHTTPRequest, model: String? = nil) async throws -> OllamaHTTPResponse {
let url = try makeURL(for: request.path)
let urlRequest = try makeURLRequest(request)
do {
let (data, response) = try await session.data(for: urlRequest)
guard let http = response as? HTTPURLResponse else {
throw OllamaError.decoding("Non-HTTP response")
}
if (300 ..< 400).contains(http.statusCode) {
throw OllamaError.endpointRejected(.redirect)
}
guard (200 ..< 300).contains(http.statusCode) else {
throw httpError(status: http.statusCode, data: data, model: model)
}
return OllamaHTTPResponse(status: http.statusCode, body: data)
} catch let error as OllamaError {
throw error
} catch let error as URLError {
throw transportError(error, url: url)
} catch is CancellationError {
throw OllamaError.cancelled
} catch {
throw OllamaError.decoding("Request failed")
}
}
/// Sends a request and decodes a JSON response.
public func sendJSON<Response: Decodable>(
_ request: OllamaHTTPRequest,
as type: Response.Type,
model: String? = nil
) async throws -> Response {
let response = try await send(request, model: model)
do {
return try JSONDecoder().decode(Response.self, from: response.body)
} catch {
throw OllamaError.decoding("Invalid JSON response")
}
}
/// Streams NDJSON lines from a request. The caller decides when to stop after a `done` line.
func stream(
_ request: OllamaHTTPRequest,
model: String?,
onLine: @escaping @Sendable (String) async throws -> StreamLineAction
) async throws {
let url = try makeURL(for: request.path)
let urlRequest = try makeURLRequest(request)
do {
let (bytes, response) = try await session.bytes(for: urlRequest)
guard let http = response as? HTTPURLResponse else {
throw OllamaError.decoding("Non-HTTP response")
}
try await validateStreamResponse(http, bytes: bytes, model: model)
var lines = bytes.lines.makeAsyncIterator()
while let line = try await lines.next() {
if try await onLine(line) == .stop {
break
}
}
} catch let error as OllamaError {
throw error
} catch let error as URLError {
throw transportError(error, url: url)
} catch is CancellationError {
throw OllamaError.cancelled
} catch {
throw OllamaError.decoding("Stream failed")
}
}
/// Builds the request URL without producing `//` at the base-path boundary.
func makeURL(for path: String) throws -> URL {
guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else {
throw OllamaError.decoding("Invalid base URL")
}
let requestPath = path.hasPrefix("/") ? path : "/" + path
let basePath = components.path
if basePath.isEmpty || basePath == "/" {
components.path = requestPath
} else if basePath.hasSuffix("/") {
components.path = String(basePath.dropLast()) + requestPath
} else {
components.path = basePath + requestPath
}
guard let url = components.url else {
throw OllamaError.decoding("Invalid request URL")
}
return url
}
private func validateStreamResponse(
_ http: HTTPURLResponse,
bytes: URLSession.AsyncBytes,
model: String?
) async throws {
if (300 ..< 400).contains(http.statusCode) {
throw OllamaError.endpointRejected(.redirect)
}
guard (200 ..< 300).contains(http.statusCode) else {
var data = Data()
for try await byte in bytes {
guard data.count < 4096 else { break }
data.append(byte)
}
throw httpError(status: http.statusCode, data: data, model: model)
}
}
private func makeURLRequest(_ request: OllamaHTTPRequest) throws -> URLRequest {
let url = try makeURL(for: request.path)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = request.method.rawValue
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
if let body = request.body {
urlRequest.httpBody = body
urlRequest.setValue(
request.contentType ?? "application/json",
forHTTPHeaderField: "Content-Type"
)
}
return urlRequest
}
private func httpError(status: Int, data: Data, model: String?) -> OllamaError {
let message = OllamaErrorBody.message(from: data) ?? ""
if status == 404, let model, message.localizedCaseInsensitiveContains("not found") {
return .modelNotInstalled(model)
}
if status == 400 {
return .badRequest(message)
}
return .server(status: status, message: message)
}
private func transportError(_ error: URLError, url: URL) -> OllamaError {
switch error.code {
case .cancelled:
.cancelled
case .timedOut:
.timeout(.connect)
case .cannotConnectToHost, .cannotFindHost, .dnsLookupFailed,
.networkConnectionLost, .notConnectedToInternet:
.unreachable(url)
default:
.unreachable(url)
}
}
}
@@ -0,0 +1,32 @@
import Foundation
/// The HTTP methods the Ollama API uses in v1.
public enum OllamaHTTPMethod: String, Sendable {
case get = "GET"
case post = "POST"
}
/// A transport-independent Ollama request.
public struct OllamaHTTPRequest: Sendable, Equatable {
/// The HTTP method.
public let method: OllamaHTTPMethod
/// The path below the configured base URL, e.g. `/api/version`.
public let path: String
/// An optional JSON body.
public let body: Data?
/// The body content type; defaults to `application/json` when a body is present.
public let contentType: String?
/// Creates a request.
public init(
method: OllamaHTTPMethod = .get,
path: String,
body: Data? = nil,
contentType: String? = nil
) {
self.method = method
self.path = path
self.body = body
self.contentType = contentType
}
}
@@ -0,0 +1,15 @@
import Foundation
/// A successful HTTP response from Ollama.
public struct OllamaHTTPResponse: Sendable, Equatable {
/// The HTTP status code.
public let status: Int
/// The response body.
public let body: Data
/// Creates a response value.
public init(status: Int, body: Data) {
self.status = status
self.body = body
}
}
@@ -0,0 +1,7 @@
/// A transport seam so catalog and chat tests can run without a live socket.
public protocol OllamaHTTPTransport: Sendable {
/// Sends one request and returns a 2xx response, throwing `OllamaError` otherwise.
///
/// - Parameter model: the model tag for a 404 body check; pass it for chat/show requests.
func send(_ request: OllamaHTTPRequest, model: String?) async throws -> OllamaHTTPResponse
}
@@ -0,0 +1,21 @@
import Foundation
/// The privacy-preserving `URLSession` configuration for every Ollama request (SP-6).
public enum OllamaSessionFactory {
/// An ephemeral configuration with no cookies, cache or credential storage.
public static func makeConfiguration() -> URLSessionConfiguration {
let configuration = URLSessionConfiguration.ephemeral
configuration.httpCookieStorage = nil
configuration.urlCache = nil
configuration.urlCredentialStorage = nil
configuration.httpShouldSetCookies = false
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
configuration.waitsForConnectivity = false
// Never let URLSession's default 60 s request timeout pre-empt the documented 120 s
// first-token budget (which includes a cold model load). The chat client enforces the
// finer phases.
configuration.timeoutIntervalForRequest = 180
configuration.timeoutIntervalForResource = 180
return configuration
}
}
@@ -0,0 +1,48 @@
import Foundation
/// A comparable Ollama version such as `0.40.18`.
public struct OllamaVersion: Comparable, Sendable, CustomStringConvertible {
/// The numeric components, e.g. `[0, 40, 18]`.
public let components: [Int]
/// The minimum supported server version (ARCHITECTURE §2).
public static let minimumSupported = OllamaVersion(components: [0, 40, 0])
/// Parses a dotted numeric version. Returns nil for non-numeric or empty input.
public init?(_ string: String) {
let withoutBuild = string.split(separator: "+", maxSplits: 1).first.map(String.init) ?? string
let core = withoutBuild.split(separator: "-", maxSplits: 1).first.map(String.init) ?? withoutBuild
let parts = core.split(separator: ".").map { Int($0) }
guard !parts.isEmpty, parts.allSatisfy({ $0 != nil }) else {
return nil
}
components = parts.compactMap(\.self)
}
private init(components: [Int]) {
self.components = components
}
/// The dotted representation.
public var description: String {
components.map(String.init).joined(separator: ".")
}
/// Component-wise comparison, padding the shorter version with zeros.
public static func < (lhs: OllamaVersion, rhs: OllamaVersion) -> Bool {
let count = max(lhs.components.count, rhs.components.count)
for index in 0 ..< count {
let left = index < lhs.components.count ? lhs.components[index] : 0
let right = index < rhs.components.count ? rhs.components[index] : 0
if left != right {
return left < right
}
}
return false
}
/// Equality treats `0.40` and `0.40.0` as the same version.
public static func == (lhs: OllamaVersion, rhs: OllamaVersion) -> Bool {
!(lhs < rhs) && !(rhs < lhs)
}
}
@@ -0,0 +1,9 @@
import Foundation
/// Warm-up is allowed only for a loopback endpoint and only when the user enabled it.
public enum OllamaWarmUpPolicy {
/// Returns true only for a local endpoint with warm-up enabled.
public static func shouldWarmUp(endpoint: URL, enabled: Bool) -> Bool {
enabled && EndpointPolicy.isLoopback(endpoint)
}
}
@@ -0,0 +1,14 @@
/// Runs a warm-up or unload request and discards the streamed output.
public struct OllamaWarmUpRunner: Sendable {
private let chat: any OllamaChatting
/// Creates a runner over a chat client.
public init(chat: any OllamaChatting) {
self.chat = chat
}
/// Runs the request to completion; never returns or stores the output.
public func run(_ request: ChatRequest) async throws {
for try await _ in chat.chat(request) {}
}
}
@@ -0,0 +1,16 @@
import Foundation
/// Cancels every HTTP redirect. The Ollama endpoint is fixed; a redirect could move the request
/// to a different host and leak text. Immutable, stateless, and only implements the delegate
/// method, so `@unchecked Sendable` is safe.
final class RedirectRefusingDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void
) {
completionHandler(nil)
}
}
@@ -1,6 +0,0 @@
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
/// Namespace for the SprachmittlerOllama module.
public enum SprachmittlerOllamaModule {
public static let moduleName = "SprachmittlerOllama"
}
@@ -0,0 +1,5 @@
/// Whether a streaming reader should continue after handling one NDJSON line.
enum StreamLineAction: Sendable, Equatable {
case continueStream
case stop
}
@@ -0,0 +1,11 @@
/// The phase in which an Ollama request timed out.
public enum TimeoutPhase: Sendable, Equatable {
/// TCP connect plus TLS.
case connect
/// Request sent until the first content byte; includes a cold model load.
case firstToken
/// Gap between stream lines once streaming has started.
case idle
/// Hard cap for one chunk.
case total
}