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,28 @@
import SprachmittlerOllama
/// Maps the leaf's transport vocabulary to the domain taxonomy at the Core boundary.
public extension SprachmittlerError {
/// Creates a domain error from an `OllamaError`.
init(ollama error: OllamaError) {
switch error {
case let .endpointRejected(reason):
self = .endpointRejected(reason: reason)
case let .unreachable(url):
self = .ollamaUnreachable(url: url)
case let .modelNotInstalled(model):
self = .modelNotInstalled(model: model)
case let .badRequest(message):
self = .badRequest(message: message)
case let .server(status, message):
self = .server(status: status, message: message)
case let .timeout(phase):
self = .timeout(phase: phase)
case .cancelled:
self = .cancelled
case let .decoding(message):
self = .server(status: 0, message: message)
case let .unsupportedVersion(found, required):
self = .ollamaTooOld(found: found, required: required)
}
}
}
@@ -0,0 +1,35 @@
import Foundation
import SprachmittlerOllama
/// The domain error taxonomy from ARCHITECTURE §5.
///
/// Leaf modules throw their own errors (e.g. `OllamaError`); this type is produced at the Core
/// boundary by `SprachmittlerError(ollama:)`. UI code shows `userMessage`, never a raw body.
public enum SprachmittlerError: Error, Sendable, Equatable {
// Capture
case noSelection
case emptyText
case textTooLong(characters: Int, limit: Int)
case pasteboardUnavailable
// Translation
case ollamaUnreachable(url: URL)
case ollamaTooOld(found: String, required: String)
case endpointRejected(reason: EndpointRejection)
case modelNotInstalled(model: String)
case noAdapter(model: String)
case badRequest(message: String)
case server(status: Int, message: String)
case timeout(phase: TimeoutPhase)
case emptyOutput
case truncated
case repetitionLoop
case preambleDetected
case protectedTokenLost(token: String)
// Insertion
case accessibilityNotTrusted
case accessibilityUnsupported(app: String?)
case insertionTargetChanged
case pasteboardRestoreFailed
// General
case cancelled
}
@@ -0,0 +1,34 @@
/// The provisional common-language table for the M1 CLI. T2.3 replaces this with the complete
/// 102-language catalogue from docs/LANGUAGES.md.
public enum HyMT3Languages {
/// English.
public static let english = ModelLanguage(code: "en", modelName: "English")
/// German.
public static let german = ModelLanguage(code: "de", modelName: "German")
/// The common targets exposed by the M1 CLI.
public static let all: [ModelLanguage] = [
english,
german,
ModelLanguage(code: "fr", modelName: "French"),
ModelLanguage(code: "es", modelName: "Spanish"),
ModelLanguage(code: "it", modelName: "Italian"),
ModelLanguage(code: "pt", modelName: "Portuguese"),
ModelLanguage(code: "nl", modelName: "Dutch"),
ModelLanguage(code: "pl", modelName: "Polish"),
ModelLanguage(code: "zh", modelName: "Chinese"),
ModelLanguage(code: "zh-Hant", modelName: "Traditional Chinese"),
ModelLanguage(code: "ja", modelName: "Japanese"),
ModelLanguage(code: "ko", modelName: "Korean"),
ModelLanguage(code: "ar", modelName: "Arabic"),
ModelLanguage(code: "tr", modelName: "Turkish"),
ModelLanguage(code: "ru", modelName: "Russian"),
ModelLanguage(code: "uk", modelName: "Ukrainian"),
]
/// Resolves a BCP-47 code case-insensitively; unknown codes return nil (never a guess).
public static func resolve(_ code: String) -> ModelLanguage? {
let normalized = code.lowercased()
return all.first { $0.code.lowercased() == normalized }
}
}
@@ -0,0 +1,12 @@
/// The provisional Hy-MT3 model tags. The default is decided by the M7 evaluation; this constant
/// is the only place the tag appears outside docs and tests.
public enum HyMT3ModelPreset {
/// The provisional default: Hy-MT3-7B Q4_K_M.
public static let defaultModel = "hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M"
/// The Fast preset: Hy-MT3-1.8B Q4_K_M.
public static let fastModel = "hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M"
/// The settings default for keeping the model warm.
public static let defaultKeepAlive = "30m"
/// The only text used for warm-up. Never user text.
public static let warmUpText = "Hello."
}
@@ -0,0 +1,25 @@
import SprachmittlerOllama
/// The documented Hy-MT3 sampling values from docs/HYMT3_MODEL.md §2.
public enum HyMT3Options {
/// Translation defaults: temperature 0.7, top_p 0.6, top_k 20, repeat_penalty 1.05,
/// num_predict 4096, num_ctx 8192.
public static let translation = ChatOptions(
temperature: 0.7,
topP: 0.6,
topK: 20,
repeatPenalty: 1.05,
numPredict: 4096,
numCtx: 8192
)
/// Warm-up uses the same model settings but only 8 output tokens.
public static let warmUp = ChatOptions(
temperature: 0.7,
topP: 0.6,
topK: 20,
repeatPenalty: 1.05,
numPredict: 8,
numCtx: 8192
)
}
@@ -0,0 +1,12 @@
/// The documented Hy-MT3 prompt templates. v1 uses the Default Translation template.
public enum HyMT3Prompt {
/// The byte-exact Default Translation prompt from docs/HYMT3_MODEL.md §3.
///
/// The prefix depends only on the target language; the source text is appended last so the
/// Ollama prompt cache stays valid.
public static func defaultTranslation(target: ModelLanguage, source: String) -> String {
let prefix = "Translate the following text into \(target.modelName). "
+ "Note that you should **only output the translated result without any additional explanation**:"
return prefix + "\n\n" + source
}
}
@@ -0,0 +1,52 @@
import SprachmittlerOllama
/// Builds the documented Hy-MT3 requests. T2.1/T2.2 replace this with the adapter protocol;
/// until then this is the only place the translation request shape is assembled.
public struct HyMT3RequestFactory: Sendable {
/// The model tag.
public let model: String
/// The Ollama `keep_alive` value.
public let keepAlive: String
/// Creates a factory.
public init(
model: String = HyMT3ModelPreset.defaultModel,
keepAlive: String = HyMT3ModelPreset.defaultKeepAlive
) {
self.model = model
self.keepAlive = keepAlive
}
/// A translation request with the documented prompt and sampling.
public func translationRequest(text: String, target: ModelLanguage) -> ChatRequest {
ChatRequest(
model: model,
messages: [ChatMessage(content: HyMT3Prompt.defaultTranslation(target: target, source: text))],
stream: true,
keepAlive: keepAlive,
options: HyMT3Options.translation
)
}
/// A warm-up request with fixed synthetic text and `num_predict: 8`.
public func warmUpRequest() -> ChatRequest {
ChatRequest(
model: model,
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
stream: true,
keepAlive: keepAlive,
options: HyMT3Options.warmUp
)
}
/// A request that unloads the model after it completes.
public func unloadRequest() -> ChatRequest {
ChatRequest(
model: model,
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
stream: true,
keepAlive: "0",
options: HyMT3Options.warmUp
)
}
}
@@ -0,0 +1,13 @@
/// A BCP-47 code paired with the exact English model-card name used in the prompt.
public struct ModelLanguage: Sendable, Hashable, Codable {
/// The BCP-47 code, e.g. `de` or `zh-Hant`.
public let code: String
/// The exact model-card name, e.g. `German` or `Traditional Chinese`.
public let modelName: String
/// Creates a language pair.
public init(code: String, modelName: String) {
self.code = code
self.modelName = modelName
}
}
@@ -1,6 +0,0 @@
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
/// Namespace for the SprachmittlerEngines module.
public enum SprachmittlerEnginesModule {
public static let moduleName = "SprachmittlerEngines"
}
@@ -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
}
@@ -0,0 +1,57 @@
import Foundation
import SprachmittlerOllama
/// A catalog fake backed by fixed values.
public struct FakeOllamaCatalog: OllamaCatalog, Sendable {
/// The reported server version.
public let version: String
/// The installed models.
public let models: [InstalledModel]
/// Details by model tag.
public let details: [String: ModelDetails]
/// The loaded models.
public let loaded: [LoadedModel]
/// Creates a catalog fake.
public init(
version: String = "0.40.18",
models: [InstalledModel] = [],
details: [String: ModelDetails] = [:],
loaded: [LoadedModel] = []
) {
self.version = version
self.models = models
self.details = details
self.loaded = loaded
}
public func serverVersion() async throws -> String {
version
}
public func installedModels() async throws -> [InstalledModel] {
models
}
public func show(model: String) async throws -> ModelDetails {
guard let details = details[model] else {
throw OllamaError.modelNotInstalled(model)
}
return details
}
public func loadedModels() async throws -> [LoadedModel] {
loaded
}
public func refresh() async {}
public func checkMinimumVersion() async throws {
guard let parsed = OllamaVersion(version), parsed >= .minimumSupported else {
throw OllamaError.unsupportedVersion(
found: version,
required: OllamaVersion.minimumSupported.description
)
}
}
}
@@ -0,0 +1,29 @@
import Foundation
import SprachmittlerOllama
/// A chat fake that emits a fixed event list and records the request through a caller closure.
public struct FakeOllamaChat: OllamaChatting, Sendable {
/// The events emitted for every chat call.
public let events: [ChatEvent]
/// Called synchronously with each request.
public let onRequest: @Sendable (ChatRequest) -> Void
/// Creates a fake chat.
public init(
events: [ChatEvent] = [.done(reason: "stop", metrics: .empty)],
onRequest: @escaping @Sendable (ChatRequest) -> Void = { _ in }
) {
self.events = events
self.onRequest = onRequest
}
public func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error> {
onRequest(request)
return AsyncThrowingStream { continuation in
for event in events {
continuation.yield(event)
}
continuation.finish()
}
}
}
@@ -0,0 +1,26 @@
import Foundation
import SprachmittlerOllama
/// A transport fake for catalog and chat tests. It records every request and answers through a
/// caller-supplied handler.
public actor FakeOllamaHTTPTransport: OllamaHTTPTransport {
/// The reply function.
public typealias Handler = @Sendable (OllamaHTTPRequest) throws -> OllamaHTTPResponse
private let handler: Handler
/// Every request seen, in order.
public private(set) var requests: [OllamaHTTPRequest] = []
/// The model argument supplied with each request, in order.
public private(set) var models: [String?] = []
/// Creates a fake with the given reply handler.
public init(handler: @escaping Handler) {
self.handler = handler
}
public func send(_ request: OllamaHTTPRequest, model: String?) async throws -> OllamaHTTPResponse {
requests.append(request)
models.append(model)
return try handler(request)
}
}
@@ -0,0 +1,64 @@
import Foundation
import SprachmittlerOllama
/// A manual sleeper for timeout tests: no real time passes. Tests wait for a pending duration
/// and advance it explicitly.
public actor ManualSleeper: AsyncSleeper {
private struct Waiter {
let duration: Duration
let continuation: CheckedContinuation<Void, any Error>
}
private var waiters: [UUID: Waiter] = [:]
private var observers: [Duration: [CheckedContinuation<Void, Never>]] = [:]
/// Creates a manual sleeper.
public init() {}
public func sleep(for duration: Duration) async throws {
if Task.isCancelled {
throw CancellationError()
}
let id = UUID()
try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
waiters[id] = Waiter(duration: duration, continuation: continuation)
let pending = observers.removeValue(forKey: duration) ?? []
pending.forEach { $0.resume() }
}
} onCancel: {
Task {
await self.cancel(id)
}
}
}
/// Suspends until a sleep for `duration` is waiting.
public func waitUntilPending(_ duration: Duration) async {
if waiters.values.contains(where: { $0.duration == duration }) {
return
}
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
observers[duration, default: []].append(continuation)
}
}
/// Resumes every sleep waiting for `duration`.
public func advance(matching duration: Duration) {
let matching = waiters.filter { $0.value.duration == duration }
for (id, waiter) in matching {
waiters.removeValue(forKey: id)
waiter.continuation.resume()
}
}
/// The number of sleepers currently waiting for `duration`.
public func pendingCount(_ duration: Duration) -> Int {
waiters.values.filter { $0.duration == duration }.count
}
private func cancel(_ id: UUID) {
guard let waiter = waiters.removeValue(forKey: id) else { return }
waiter.continuation.resume(throwing: CancellationError())
}
}
@@ -1,6 +0,0 @@
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
/// Namespace for the SprachmittlerTestSupport module.
public enum SprachmittlerTestSupportModule {
public static let moduleName = "SprachmittlerTestSupport"
}
@@ -0,0 +1,25 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
/// The CLI composition root. Concrete clients are created only here (CODING_STANDARDS).
struct CLIEnvironment: Sendable {
let baseURL: URL
let allowRemote: Bool
func makeHTTPClient() throws -> OllamaHTTPClient {
try OllamaHTTPClient(baseURL: baseURL, allowRemote: allowRemote)
}
func makeCatalog() throws -> any OllamaCatalog {
try OllamaCatalogClient(http: makeHTTPClient())
}
func makeChatClient() throws -> OllamaChatClient {
try OllamaChatClient(http: makeHTTPClient())
}
func makeRequestFactory(model: String) -> HyMT3RequestFactory {
HyMT3RequestFactory(model: model)
}
}
@@ -0,0 +1,83 @@
import ArgumentParser
import Foundation
import SprachmittlerOllama
enum CLIError {
static func perform(_ operation: () async throws -> Void) async throws {
do {
try await operation()
} catch let exit as ExitCode {
throw exit
} catch let error as OllamaError {
writeError(message(for: error))
throw ExitCode(exitCode(for: error))
} catch let rejection as EndpointRejection {
// Defensive: EndpointPolicy may be called directly outside OllamaHTTPClient.
writeError(message(for: rejection))
throw ExitCode(2)
} catch let validation as ValidationError {
writeError(String(describing: validation))
throw ExitCode(2)
} catch {
writeError("Error: \(error)")
throw ExitCode(1)
}
}
/// 2 = endpoint/usage, 3 = unreachable, 4 = model missing, 1 = other runtime failure.
static func exitCode(for error: OllamaError) -> Int32 {
switch error {
case .endpointRejected:
2
case .unreachable:
3
case .modelNotInstalled:
4
default:
1
}
}
static func message(for error: OllamaError) -> String {
switch error {
case let .endpointRejected(reason):
"Endpoint rejected: \(message(for: reason))"
case let .unreachable(url):
"Ollama is not reachable at \(url.absoluteString)."
case let .modelNotInstalled(model):
"Model not installed: \(model)"
case .badRequest:
"Ollama rejected the request."
case let .server(status, _):
"Ollama returned HTTP \(status)."
case .timeout:
"Timed out while talking to Ollama."
case .cancelled:
"Cancelled."
case .decoding:
"Ollama returned an unreadable response."
case let .unsupportedVersion(found, required):
"Ollama \(found) is too old; \(required) or newer is required."
}
}
static func message(for rejection: EndpointRejection) -> String {
switch rejection {
case .scheme:
"Only http and https endpoints are supported."
case .form:
"The endpoint must not contain credentials, a query or a fragment."
case .remoteNotAllowed:
"Remote endpoints are disabled; use --allow-remote or a loopback endpoint."
case .remoteRequiresHTTPS:
"Remote endpoints require HTTPS."
case .redirect:
"The endpoint redirected; redirects are refused."
}
}
/// Diagnostics go to stderr so `translate --json` keeps stdout machine-readable.
private static func writeError(_ message: String) {
FileHandle.standardError.write(Data((message + "\n").utf8))
}
}
@@ -0,0 +1,51 @@
import SprachmittlerOllama
enum CLIOutput {
static func models(_ summaries: [ModelSummary]) -> String {
guard !summaries.isEmpty else {
return "No Hy-MT3 models installed."
}
return summaries.map { summary in
var lines = [summary.model.name]
lines.append(" digest: \(summary.model.digest.prefix(12))")
lines.append(" capabilities: \(summary.capabilities.joined(separator: ", "))")
if let details = summary.model.details {
if let family = details.family {
lines.append(" family: \(family)")
}
if let parameters = details.parameterSize {
lines.append(" parameters: \(parameters)")
}
if let quantization = details.quantizationLevel {
lines.append(" quantization: \(quantization)")
}
}
return lines.joined(separator: "\n")
}.joined(separator: "\n\n")
}
static func show(_ details: ModelDetails) -> String {
var lines = [
"capabilities: \(details.capabilities.joined(separator: ", "))",
]
if let info = details.details {
if let family = info.family {
lines.append("family: \(family)")
}
if let parameters = info.parameterSize {
lines.append("parameters: \(parameters)")
}
if let quantization = info.quantizationLevel {
lines.append("quantization: \(quantization)")
}
}
lines.append("license: \(details.license ?? "unknown")")
if let parameters = details.parameters {
lines.append("parameters:\n\(parameters)")
}
if let template = details.template {
lines.append("template:\n\(template)")
}
return lines.joined(separator: "\n")
}
}
@@ -0,0 +1,17 @@
import ArgumentParser
import Foundation
struct EndpointOptions: ParsableArguments {
@Option(name: .long, help: "Ollama base URL (default http://127.0.0.1:11434).")
var endpoint = "http://127.0.0.1:11434"
@Flag(name: .long, help: "Allow a remote HTTPS endpoint.")
var allowRemote = false
func makeEnvironment() throws -> CLIEnvironment {
guard let url = URL(string: endpoint) else {
throw ValidationError("Invalid endpoint URL: \(endpoint)")
}
return CLIEnvironment(baseURL: url, allowRemote: allowRemote)
}
}
@@ -0,0 +1,6 @@
import SprachmittlerOllama
struct ModelSummary: Sendable, Equatable {
let model: InstalledModel
let capabilities: [String]
}
@@ -0,0 +1,20 @@
import ArgumentParser
import SprachmittlerOllama
struct ModelsCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "models",
abstract: "List installed Hy-MT3 models and their capabilities."
)
@OptionGroup var endpoint: EndpointOptions
func run() async throws {
try await CLIError.perform {
let environment = try endpoint.makeEnvironment()
let catalog = try environment.makeCatalog()
let summaries = try await ModelsRunner(catalog: catalog).run()
print(CLIOutput.models(summaries))
}
}
}
@@ -0,0 +1,15 @@
import SprachmittlerOllama
struct ModelsRunner: Sendable {
let catalog: any OllamaCatalog
func run() async throws -> [ModelSummary] {
let models = try await catalog.installedModels()
var summaries: [ModelSummary] = []
for model in models where model.isHyMT3 {
let details = try await catalog.show(model: model.name)
summaries.append(ModelSummary(model: model, capabilities: details.capabilities))
}
return summaries
}
}
@@ -0,0 +1,23 @@
import ArgumentParser
import SprachmittlerOllama
struct ShowCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "show",
abstract: "Show an installed model's capabilities, parameters and template."
)
@Argument(help: "Installed model tag.")
var model: String
@OptionGroup var endpoint: EndpointOptions
func run() async throws {
try await CLIError.perform {
let environment = try endpoint.makeEnvironment()
let catalog = try environment.makeCatalog()
let details = try await ShowRunner(catalog: catalog).run(model: model)
print(CLIOutput.show(details))
}
}
}
@@ -0,0 +1,9 @@
import SprachmittlerOllama
struct ShowRunner: Sendable {
let catalog: any OllamaCatalog
func run(model: String) async throws -> ModelDetails {
try await catalog.show(model: model)
}
}
@@ -1,21 +1,15 @@
import ArgumentParser
import SprachmittlerCore
import SprachmittlerEval
/// Headless harness for Sprachmittler. Subcommands are added in T1.6 (models, show, translate),
/// T2.7 (detect, prompt inspection) and T7.1 (eval). See docs/IMPLEMENTATION_PLAN.md.
/// Headless harness for Sprachmittler. See docs/IMPLEMENTATION_PLAN.md T1.6, T2.7 and T7.1.
@main
struct SprachmittlerCLI: ParsableCommand {
struct SprachmittlerCLI: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "sprachmittler-cli",
abstract: "Headless translator and test harness for Sprachmittler.",
subcommands: []
subcommands: [
ModelsCommand.self,
ShowCommand.self,
TranslateCommand.self,
]
)
func run() throws {
print(
"sprachmittler-cli: no subcommands implemented yet "
+ "(\(SprachmittlerCoreModule.moduleName), \(SprachmittlerEvalModule.moduleName))"
)
}
}
@@ -0,0 +1,79 @@
import ArgumentParser
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
struct TranslateCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "translate",
abstract: "Translate text with a local Hy-MT3 model."
)
@Option(name: .long, help: "Text to translate.")
var text: String?
@Option(name: .long, help: "File to read UTF-8 text from.")
var file: String?
@Option(name: .long, help: "Target BCP-47 code, e.g. de.")
var target: String
@Option(name: .long, help: "Model tag.")
var model = HyMT3ModelPreset.defaultModel
@Flag(name: .long, help: "Emit the JSON schema instead of plain text.")
var json = false
@Flag(name: .long, help: "Include the source text in JSON (debugging only).")
var includeSource = false
@OptionGroup var endpoint: EndpointOptions
func validate() throws {
if (text == nil) == (file == nil) {
throw ValidationError("Use exactly one of --text or --file.")
}
if HyMT3Languages.resolve(target) == nil {
let supported = HyMT3Languages.all.map(\.code).joined(separator: ", ")
throw ValidationError("Unknown target language '\(target)'. Supported: \(supported)")
}
}
func run() async throws {
guard let language = HyMT3Languages.resolve(target) else {
throw ValidationError("Unknown target language '\(target)'.")
}
let source = try sourceText()
try await CLIError.perform {
let environment = try endpoint.makeEnvironment()
let chat = try environment.makeChatClient()
let runner = TranslateRunner(
chat: chat,
factory: environment.makeRequestFactory(model: model)
)
let outcome = try await runner.run(text: source, target: language)
if json {
let data = try outcome.jsonData(includeSource: includeSource, source: source)
print(String(data: data, encoding: .utf8) ?? "{}")
} else {
print(outcome.translation)
}
}
}
/// Returns `--text` or the UTF-8 contents of `--file`; validation guarantees one is present.
func sourceText() throws -> String {
if let text {
return text
}
guard let file else {
throw ValidationError("Use exactly one of --text or --file.")
}
do {
return try String(contentsOfFile: file, encoding: .utf8)
} catch {
throw ValidationError("Could not read \(file): \(error.localizedDescription)")
}
}
}
@@ -0,0 +1,38 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
struct TranslateOutcome: Sendable, Equatable {
let translation: String
let model: String
let target: ModelLanguage
let metrics: ChatMetrics
let firstTokenMs: Int?
let totalMs: Int
let sourceCharacters: Int
/// The CLI JSON contract from docs/TRANSLATION_OUTPUT.md §10. `sourceLanguage` stays null
/// until T2.4; warnings stay empty until T2.5.
func jsonData(includeSource: Bool, source: String) throws -> Data {
let timing: [String: Any] = [
"firstTokenMs": firstTokenMs.map { $0 as Any } ?? NSNull(),
"totalMs": totalMs,
"promptTokens": metrics.promptEvalCount.map { $0 as Any } ?? NSNull(),
"outputTokens": metrics.evalCount.map { $0 as Any } ?? NSNull(),
]
var object: [String: Any] = [
"schema": "sprachmittler-translation-v1",
"sourceLanguage": NSNull(),
"targetLanguage": target.code,
"model": model,
"sourceCharacters": sourceCharacters,
"translation": translation,
"warnings": [String](),
"timing": timing,
]
if includeSource {
object["source"] = source
}
return try JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys])
}
}
@@ -0,0 +1,40 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
struct TranslateRunner: Sendable {
let chat: any OllamaChatting
let factory: HyMT3RequestFactory
func run(text: String, target: ModelLanguage) async throws -> TranslateOutcome {
let request = factory.translationRequest(text: text, target: target)
let started = Date()
var firstDelta: Date?
var translation = ""
var metrics = ChatMetrics.empty
for try await event in chat.chat(request) {
switch event {
case let .delta(delta):
if firstDelta == nil {
firstDelta = Date()
}
translation += delta
case let .done(_, doneMetrics):
metrics = doneMetrics
}
}
let totalMs = max(0, Int(Date().timeIntervalSince(started) * 1000))
let firstTokenMs = firstDelta.map { max(0, Int($0.timeIntervalSince(started) * 1000)) }
return TranslateOutcome(
translation: translation,
model: request.model,
target: target,
metrics: metrics,
firstTokenMs: firstTokenMs,
totalMs: totalMs,
sourceCharacters: text.count
)
}
}