Compare commits

...
3 Commits
Author SHA1 Message Date
schihei 64078e2f04 feat(m2-m3): adapter, text pipeline, double-copy capture and Services (T2.1-T2.7, T3.1-T3.4)
M2: TranslationAdapter/AdapterRegistry with documented Hy-MT3 prompts and publisher sampling; all 102 languages with BCP-47 variants, RTL and dense-script flags; normalisation, NLLanguage detection, content classification and exact-join script-aware chunking; protected-token scanning and output validation; prompt policy with one documented fallback; shared TranslationPipeline with Core error mapping. The CLI now reports sourceLanguage and warning codes.

M3: pure DoubleCopyDetector, 120 ms PasteboardWatcher with 750 ms own-write suppression, SystemPasteboard snapshot/restore and markers, CapturePolicy for the 4000/2000 limits, ServicesProvider and the menu-bar action. T3.5 (10-app manual matrix) remains intentionally open.

Docs: ARCHITECTURE, TRANSLATION_OUTPUT, HYMT3_MODEL (§7 spike), SELECTION_AND_CLIPBOARD, PROGRESS; ADR-016 superseded by ADR-017/018.

Verified: make verify green (format, strict lint, scripts, privacy, Debug+Release signatures, package tests); live 7B CLI en→de/de→en/Markdown/JSON/placeholders; empty input exits 2 and unreachable exits 3.
2026-11-26 13:30:32 +01:00
schihei 26b493e7e5 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.
2026-11-26 13:04:22 +01:00
schihei 7ca5c710ec feat(m0): complete scaffold, logging and signature checks (T0.2-T0.6)
Add os.Logger categories, OSSignposter wrapper and shortHash helper; enforce exact Debug/Release/install signatures; lint tests; update M0 docs and progress.
2026-11-26 12:33:51 +01:00
166 changed files with 7885 additions and 284 deletions

No files matched your search

+28 -7
View File
@@ -1,19 +1,40 @@
import AppKit
import os
import SprachmittlerCore
/// Lifecycle glue: composition root, Services provider, double-copy watcher, termination.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
private let loggers = Loggers(subsystem: Bundle.main.bundleIdentifier ?? "Sprachmittler")
private var environment: AppEnvironment?
func applicationDidFinishLaunching(_ notification: Notification) {
// Build AppEnvironment here (composition root): settings, Ollama services, session,
// double-copy watcher and panel controller. Start the watcher only after explicit consent.
//
// The Services provider is wired here once SprachmittlerCapture.ServicesProvider exists:
// NSApp.servicesProvider = servicesProvider
// NSUpdateDynamicServices()
loggers.logger(.session).notice("Sprachmittler launched")
let environment = AppEnvironment()
self.environment = environment
environment.start { [weak self] captured in
self?.handle(captured)
}
NSApp.servicesProvider = environment.servicesProvider
NSUpdateDynamicServices()
}
func applicationWillTerminate(_ notification: Notification) {
// Cancel in-flight translations, stop the pasteboard watcher and close the panel.
environment?.stop()
environment = nil
}
/// Menu-bar action: translate the current clipboard text.
func captureClipboardText() {
environment?.captureClipboardText()
}
private func handle(_ captured: CapturedText) {
// The M4 session will replace this log-only sink. Log counts and source only.
loggers.logger(.capture).notice(
"Captured \(captured.text.count) characters from \(captured.source.rawValue, privacy: .public)"
)
}
}
+77
View File
@@ -0,0 +1,77 @@
import Foundation
import SprachmittlerCapture
import SprachmittlerCore
/// The app composition root for capture. It owns the watcher, pasteboard and Services provider.
@MainActor
final class AppEnvironment {
let pasteboard: SystemPasteboard
let watcher: PasteboardWatcher
private var onCapture: ((CapturedText) -> Void)?
/// The most recent capture, kept in memory only for the M4 panel.
private(set) var lastCaptured: CapturedText?
/// The most recent capture rejection, for the M4 panel and diagnostics.
private(set) var lastCaptureFailure: CaptureValidation?
/// The Services provider, created lazily so it can capture `self` weakly.
lazy var servicesProvider = ServicesProvider { [weak self] captured in
Task { @MainActor in
self?.deliver(captured)
}
}
/// Creates the capture stack.
init() {
let pasteboard = SystemPasteboard()
self.pasteboard = pasteboard
watcher = PasteboardWatcher(pasteboard: pasteboard)
}
/// Starts the watcher and delivers every capture to `onCapture`.
func start(onCapture: @escaping (CapturedText) -> Void) {
self.onCapture = onCapture
watcher.start { [weak self] event in
self?.handle(event)
}
}
/// Stops the watcher and releases the in-memory text.
func stop() {
watcher.stop()
lastCaptured = nil
}
/// Reads the clipboard once for the menu-bar item.
func captureClipboardText() {
guard !pasteboard.containsOwnWriteMarkers(),
let text = pasteboard.string(),
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
else {
return
}
deliver(CapturedText(text: text, capturedAt: Date(), source: .menu))
}
private func handle(_ event: PasteboardWatcherEvent) {
switch event {
case let .captured(captured):
deliver(captured)
case .textTooLong, .noText, .ignoredOwnWrite:
break
}
}
private func deliver(_ captured: CapturedText) {
switch CapturePolicy.validate(captured.text) {
case .valid:
lastCaptureFailure = nil
case let failure:
lastCaptureFailure = failure
return
}
lastCaptured = captured
onCapture?(captured)
}
}
+9 -9
View File
@@ -8,17 +8,17 @@ struct SprachmittlerApp: App {
var body: some Scene {
MenuBarExtra("Sprachmittler", systemImage: "translate") {
// Replaced by MenuBar/StatusMenu.swift.
Button("Translate Clipboard Text") {}
.disabled(true)
Divider()
Button("Set up Sprachmittler…") {}
.disabled(true)
SettingsLink {
Text("Settings…")
Button(String(localized: "Translate Clipboard Text")) {
(NSApp.delegate as? AppDelegate)?.captureClipboardText()
}
Divider()
Button("Quit Sprachmittler") {
Button(String(localized: "Set up Sprachmittler…")) {}
.disabled(true)
SettingsLink {
Text(String(localized: "Settings…"))
}
Divider()
Button(String(localized: "Quit Sprachmittler")) {
NSApplication.shared.terminate(nil)
}
.keyboardShortcut("q")
+3 -1
View File
@@ -42,7 +42,9 @@ app: build-app
install: build-app
@pkill -x Sprachmittler 2>/dev/null || true
ditto "$(APP_PATH)" "$(INSTALL_DIR)/Sprachmittler.app"
codesign --force --sign - "$(INSTALL_DIR)/Sprachmittler.app"
codesign --force --sign - --options runtime \
--entitlements App/Sprachmittler.entitlements "$(INSTALL_DIR)/Sprachmittler.app"
scripts/check-signature.sh "$(INSTALL_DIR)/Sprachmittler.app" install
open "$(INSTALL_DIR)/Sprachmittler.app"
fixtures:
+23 -4
View File
@@ -48,13 +48,19 @@ let package = Package(
.target(name: "SprachmittlerEval", dependencies: ["SprachmittlerCore"], swiftSettings: strictSettings),
// Fakes shared by tests (FakePasteboard, FakeClock, FakeOllamaTransport, FakeTextInserter, …).
.target(name: "SprachmittlerTestSupport", dependencies: ["SprachmittlerCore"], swiftSettings: strictSettings),
.target(
name: "SprachmittlerTestSupport",
dependencies: ["SprachmittlerCore", "SprachmittlerCapture", "SprachmittlerOllama"],
swiftSettings: strictSettings
),
.executableTarget(
name: "sprachmittler-cli",
dependencies: [
"SprachmittlerCore",
"SprachmittlerEngines",
"SprachmittlerEval",
"SprachmittlerOllama",
.product(name: "ArgumentParser", package: "swift-argument-parser"),
],
swiftSettings: strictSettings
@@ -67,17 +73,20 @@ let package = Package(
),
.testTarget(
name: "SprachmittlerOllamaTests",
dependencies: ["SprachmittlerOllama"],
dependencies: ["SprachmittlerOllama", "SprachmittlerTestSupport"],
resources: [.copy("Fixtures")]
),
.testTarget(
name: "SprachmittlerEnginesTests",
dependencies: ["SprachmittlerEngines"],
dependencies: ["SprachmittlerEngines", "SprachmittlerOllama", "SprachmittlerText"],
resources: [.copy("Fixtures")]
),
.testTarget(
name: "SprachmittlerCoreTests",
dependencies: ["SprachmittlerCore", "SprachmittlerTestSupport"]
dependencies: [
"SprachmittlerCore", "SprachmittlerEngines", "SprachmittlerOllama", "SprachmittlerText",
"SprachmittlerTestSupport",
]
),
.testTarget(
name: "SprachmittlerCaptureTests",
@@ -87,6 +96,16 @@ let package = Package(
name: "SprachmittlerEvalTests",
dependencies: ["SprachmittlerEval", "SprachmittlerTestSupport"]
),
.testTarget(
name: "SprachmittlerCLITests",
dependencies: [
"sprachmittler-cli",
"SprachmittlerCore",
"SprachmittlerEngines",
"SprachmittlerOllama",
"SprachmittlerTestSupport",
]
),
// Opt-in tests against a real local Ollama: SPRACHMITTLER_LIVE=1 swift test --filter SprachmittlerLiveTests
.testTarget(name: "SprachmittlerLiveTests", dependencies: ["SprachmittlerCore"]),
]
@@ -0,0 +1,26 @@
import Foundation
/// One pasteboard item's type-to-data map. The key is the raw pasteboard type.
public struct ClipboardItemData: Sendable, Equatable {
/// The item's data, keyed by pasteboard type.
public let data: [String: Data]
/// Creates an item snapshot.
public init(data: [String: Data]) {
self.data = data
}
}
/// A full pasteboard snapshot used only for the Replace paste fallback.
public struct ClipboardSnapshot: Sendable, Equatable {
/// Every item, in pasteboard order.
public let items: [ClipboardItemData]
/// The `changeCount` when the snapshot was taken.
public let changeCount: Int
/// Creates a snapshot.
public init(items: [ClipboardItemData], changeCount: Int) {
self.items = items
self.changeCount = changeCount
}
}
@@ -0,0 +1,82 @@
import Foundation
/// The double-copy state machine result (`docs/SELECTION_AND_CLIPBOARD.md` §2).
public enum DoubleCopyOutcome: Sendable, Equatable {
/// No trigger.
case none
/// A valid double copy; the value is normalised line endings and trimmed, internal whitespace kept.
case captured(String)
/// The change had no usable text; the state was reset.
case empty
}
/// The pure double-copy state machine. It has no pasteboard or timer dependency.
public struct DoubleCopyDetector: Sendable {
/// Detector configuration.
public struct Configuration: Sendable, Equatable {
/// The two-copy window; 500 ms by default (range 300–1000).
public let window: TimeInterval
/// Creates a configuration.
public init(window: TimeInterval = 0.5) {
self.window = window
}
}
private struct Candidate {
let changeCount: Int
let text: String
let date: Date
}
private let configuration: Configuration
private var candidate: Candidate?
/// Creates a detector.
public init(configuration: Configuration = Configuration()) {
self.configuration = configuration
}
/// Records one changed pasteboard value and returns the outcome.
public mutating func record(changeCount: Int, text: String?, at date: Date) -> DoubleCopyOutcome {
guard let text else {
candidate = nil
return .empty
}
let normalized = text
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
.trimmingCharacters(in: .whitespacesAndNewlines)
guard normalized.contains(where: { !$0.isWhitespace }) else {
candidate = nil
return .empty
}
if let candidate {
if candidate.changeCount == changeCount {
return .none
}
let elapsed = date.timeIntervalSince(candidate.date)
if candidate.text == normalized, elapsed >= 0, elapsed <= configuration.window {
self.candidate = nil
return .captured(normalized)
}
}
candidate = Candidate(changeCount: changeCount, text: normalized, date: date)
return .none
}
/// Forgets the remembered copy. Call when the session starts or the window expires.
public mutating func reset() {
candidate = nil
}
/// Clears the remembered copy once the two-copy window has passed, so no text is retained
/// longer than necessary.
public mutating func expire(at date: Date) {
guard let candidate, date.timeIntervalSince(candidate.date) > configuration.window else {
return
}
self.candidate = nil
}
}
@@ -0,0 +1,25 @@
import Foundation
/// The pasteboard operations `SprachmittlerCapture` needs. Tests use a fake; the app uses
/// `SystemPasteboard`. Every member is main-actor isolated because `NSPasteboard` is.
@MainActor
public protocol PasteboardAccessing: AnyObject {
/// The current pasteboard change count.
var changeCount: Int { get }
/// The plain-text string, read only after `changeCount` changed.
func string() -> String?
/// True when the pasteboard contains our own marker or a transient/concealed marker.
func containsOwnWriteMarkers() -> Bool
/// Snapshots every item and type, forcing lazy data.
func snapshot() -> ClipboardSnapshot?
/// Restores a snapshot only when `changeCount` still matches the recorded value.
func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches: Int) -> Bool
/// Writes `text` with the own/transient/concealed markers and returns the new change count.
@discardableResult
func write(_ text: String) -> Int
}
@@ -0,0 +1,35 @@
import Foundation
/// A source of pasteboard poll ticks. Production uses a 120 ms timer; tests drive it manually.
public protocol PasteboardTicking: Sendable {
/// A stream of ticks. Cancelling the consuming task must terminate the stream.
func ticks() -> AsyncStream<Void>
}
/// The production 120 ms ticker (`docs/SELECTION_AND_CLIPBOARD.md` §2).
public struct TimerPasteboardTicker: PasteboardTicking {
/// The poll interval.
public let interval: Duration
/// Creates a ticker.
public init(interval: Duration = .milliseconds(120)) {
self.interval = interval
}
public func ticks() -> AsyncStream<Void> {
AsyncStream { continuation in
let task = Task {
while !Task.isCancelled {
do {
try await Task.sleep(for: interval)
} catch {
break
}
continuation.yield(())
}
continuation.finish()
}
continuation.onTermination = { _ in task.cancel() }
}
}
}
@@ -0,0 +1,125 @@
import Foundation
import SprachmittlerCore
/// A pasteboard watcher event.
public enum PasteboardWatcherEvent: Sendable, Equatable {
/// A validated double copy.
case captured(CapturedText)
/// The copied text is above the script-aware limit.
case textTooLong(characters: Int, limit: Int)
/// The change had no usable text.
case noText
/// A change was our own write or the marker/suppression window.
case ignoredOwnWrite
}
/// Polls `changeCount`, reads the string only after a change, and emits double copies.
///
/// This type never reads the pasteboard in the background: `poll` first compares `changeCount`
/// and only then reads the string.
@MainActor
public final class PasteboardWatcher {
/// The own-write suppression window.
public static let suppressionWindow: TimeInterval = 0.75
private let pasteboard: any PasteboardAccessing
private let ticker: any PasteboardTicking
private let now: @MainActor () -> Date
private var detector: DoubleCopyDetector
private var lastChangeCount: Int
private var suppressUntil = Date.distantPast
private var task: Task<Void, Never>?
/// True while the poll task is running.
public private(set) var isRunning = false
/// Creates a watcher. The initial change count is recorded without reading any string.
public init(
pasteboard: any PasteboardAccessing,
configuration: DoubleCopyDetector.Configuration = DoubleCopyDetector.Configuration(),
ticker: any PasteboardTicking = TimerPasteboardTicker(),
now: @escaping @MainActor () -> Date = { Date() }
) {
self.pasteboard = pasteboard
detector = DoubleCopyDetector(configuration: configuration)
self.ticker = ticker
self.now = now
lastChangeCount = pasteboard.changeCount
}
/// Starts polling. Calling it twice is a no-op.
public func start(onEvent: @escaping @MainActor (PasteboardWatcherEvent) -> Void) {
guard task == nil else { return }
lastChangeCount = pasteboard.changeCount
detector.reset()
isRunning = true
let ticker = ticker
task = Task { [weak self] in
for await _ in ticker.ticks() {
guard let self else { break }
if let event = poll(at: now()) {
onEvent(event)
}
}
}
}
/// Stops polling and releases the in-memory copies.
public func stop() {
task?.cancel()
task = nil
isRunning = false
detector.reset()
}
/// Polls once. Public so component tests can avoid real time.
@discardableResult
public func poll(at date: Date) -> PasteboardWatcherEvent? {
let count = pasteboard.changeCount
guard count != lastChangeCount else {
detector.expire(at: date)
return nil
}
lastChangeCount = count
if date < suppressUntil {
return .ignoredOwnWrite
}
if pasteboard.containsOwnWriteMarkers() {
suppressUntil = date.addingTimeInterval(Self.suppressionWindow)
detector.reset()
return .ignoredOwnWrite
}
guard let string = pasteboard.string() else {
detector.reset()
return .noText
}
switch detector.record(changeCount: count, text: string, at: date) {
case .none:
return nil
case .empty:
return .noText
case let .captured(text):
let limit = CaptureLimits.characters(for: text)
guard text.count <= limit else {
detector.reset()
return .textTooLong(characters: text.count, limit: limit)
}
detector.reset()
return .captured(CapturedText(text: text, capturedAt: date, source: .doubleCopy))
}
}
/// Marks a clipboard write by this app so the watcher suppresses it and the next changes.
public func noteOwnWrite(at date: Date) {
suppressUntil = date.addingTimeInterval(Self.suppressionWindow)
detector.reset()
}
/// Clears the remembered copy without stopping the watcher.
public func clear() {
detector.reset()
}
}
@@ -0,0 +1,41 @@
import AppKit
import Foundation
import SprachmittlerCore
/// The Services entry point (`docs/SELECTION_AND_CLIPBOARD.md` §6).
///
/// The system supplies the pasteboard, so this path needs no Accessibility permission and no
/// polling. `AppDelegate` installs this object as `NSApp.servicesProvider`.
///
/// `@unchecked Sendable` is safe: the only stored value is an immutable `@Sendable` closure, and
/// AppKit invokes the selector on the main thread.
public final class ServicesProvider: NSObject, @unchecked Sendable {
/// The captured-text handler. The app hops to the main actor itself.
public typealias Handler = @Sendable (CapturedText) -> Void
private let handler: Handler
/// Creates a provider.
public init(handler: @escaping Handler) {
self.handler = handler
super.init()
}
/// The `NSMessage = translateSelection` selector from Info.plist.
@objc
@MainActor
public func translateSelection(
_ pasteboard: NSPasteboard,
userData: String,
error: AutoreleasingUnsafeMutablePointer<NSString>
) {
guard !SystemPasteboard.containsOwnWriteMarkers(in: pasteboard),
let text = pasteboard.string(forType: .string),
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
else {
error.pointee = "No text was selected." as NSString
return
}
handler(CapturedText(text: text, capturedAt: Date(), source: .services))
}
}
@@ -0,0 +1,78 @@
import AppKit
import Foundation
/// The production pasteboard adapter. This is the only type that touches `NSPasteboard.general`.
@MainActor
public final class SystemPasteboard: PasteboardAccessing {
private nonisolated static let ownType = NSPasteboard.PasteboardType("com.schihei.sprachmittler.own")
private nonisolated static let transientType = NSPasteboard.PasteboardType("org.nspasteboard.TransientType")
private nonisolated static let concealedType = NSPasteboard.PasteboardType("org.nspasteboard.ConcealedType")
private let pasteboard: NSPasteboard
/// Creates an adapter for the general pasteboard.
public init(pasteboard: NSPasteboard = .general) {
self.pasteboard = pasteboard
}
public var changeCount: Int {
pasteboard.changeCount
}
public func string() -> String? {
pasteboard.string(forType: .string)
}
public func containsOwnWriteMarkers() -> Bool {
Self.containsOwnWriteMarkers(in: pasteboard)
}
/// True when a pasteboard carries our own or a transient/concealed marker.
public nonisolated static func containsOwnWriteMarkers(in pasteboard: NSPasteboard) -> Bool {
let types = pasteboard.types ?? []
return types.contains(ownType)
|| types.contains(transientType)
|| types.contains(concealedType)
}
public func snapshot() -> ClipboardSnapshot? {
let items = pasteboard.pasteboardItems ?? []
let snapshots = items.map { item -> ClipboardItemData in
var data: [String: Data] = [:]
for type in item.types {
// `data(forType:)` forces lazy providers now; an unresolved provider is skipped.
if let value = item.data(forType: type) {
data[type.rawValue] = value
}
}
return ClipboardItemData(data: data)
}
return ClipboardSnapshot(items: snapshots, changeCount: pasteboard.changeCount)
}
public func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches expected: Int) -> Bool {
guard pasteboard.changeCount == expected else { return false }
pasteboard.clearContents()
guard !snapshot.items.isEmpty else { return true }
let items = snapshot.items.map { snapshotItem -> NSPasteboardItem in
let item = NSPasteboardItem()
for (type, data) in snapshotItem.data {
item.setData(data, forType: NSPasteboard.PasteboardType(type))
}
return item
}
return pasteboard.writeObjects(items)
}
@discardableResult
public func write(_ text: String) -> Int {
pasteboard.clearContents()
pasteboard.setString(text, forType: .string)
let marker = Data()
pasteboard.setData(marker, forType: Self.ownType)
pasteboard.setData(marker, forType: Self.transientType)
pasteboard.setData(marker, forType: Self.concealedType)
return pasteboard.changeCount
}
}
@@ -0,0 +1,9 @@
import SprachmittlerText
/// The capture character limit for a text, based on its script (`docs/TRANSLATION_OUTPUT.md` §3).
public enum CaptureLimits {
/// 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts.
public static func characters(for text: String) -> Int {
Chunker().limit(for: text)
}
}
@@ -0,0 +1,25 @@
import SprachmittlerText
/// The result of validating a captured text before any translation request.
public enum CaptureValidation: Sendable, Equatable {
/// The text may be translated.
case valid
/// The text has no non-whitespace character.
case empty
/// The text exceeds the script-aware limit.
case textTooLong(characters: Int, limit: Int)
}
/// Applies the capture rules shared by double copy, the menu and Services.
public enum CapturePolicy {
/// Validates non-emptiness and the 4000/2000 script-aware limit.
public static func validate(_ text: String) -> CaptureValidation {
guard text.contains(where: { !$0.isWhitespace }) else { return .empty }
let limit = CaptureLimits.characters(for: text)
let characters = text.count
guard characters <= limit else {
return .textTooLong(characters: characters, limit: limit)
}
return .valid
}
}
@@ -0,0 +1,10 @@
import SprachmittlerText
/// Capture-side text helpers. Kept in Core so `SprachmittlerCapture` never imports the text
/// module directly (ARCHITECTURE §4).
public enum CaptureText {
/// Double-copy comparison: line endings and outer trimming only.
public static func normalizeForComparison(_ text: String) -> String {
TextNormalization.normalizeForComparison(text)
}
}
@@ -0,0 +1,28 @@
import Foundation
/// Where a captured text came from (`docs/ARCHITECTURE.md` §5).
public enum CaptureSource: String, Sendable, Codable, Equatable {
/// The double-copy gesture.
case doubleCopy
/// The Services menu.
case services
/// The menu-bar item.
case menu
}
/// A non-empty text captured for translation.
public struct CapturedText: Sendable, Equatable {
/// The captured text.
public let text: String
/// When it was captured.
public let capturedAt: Date
/// Where it came from.
public let source: CaptureSource
/// Creates a captured text.
public init(text: String, capturedAt: Date, source: CaptureSource) {
self.text = text
self.capturedAt = capturedAt
self.source = source
}
}
@@ -0,0 +1,40 @@
import Foundation
import SprachmittlerText
/// The target of a Replace action (`docs/SELECTION_AND_CLIPBOARD.md` §4).
public struct InsertionTarget: Sendable, Equatable {
/// The process that owned the selection.
public let pid: pid_t
/// The bundle identifier, when available.
public let bundleID: String?
/// The selected text at capture time, when available.
public let selectedText: String?
/// When the target was captured.
public let capturedAt: Date
/// Creates an insertion target.
public init(pid: pid_t, bundleID: String?, selectedText: String?, capturedAt: Date) {
self.pid = pid
self.bundleID = bundleID
self.selectedText = selectedText
self.capturedAt = capturedAt
}
}
/// How a Replace action succeeded.
public enum InsertionMethod: String, Sendable, Equatable {
/// Accessibility direct replacement.
case accessibility
/// Synthetic paste.
case paste
}
/// The outcome of a Replace action.
public enum InsertionOutcome: Sendable, Equatable {
/// The selection was replaced.
case replaced(using: InsertionMethod)
/// Nothing was inserted; the translation is on the clipboard.
case copiedOnly
/// The insertion failed.
case failed(SprachmittlerError)
}
@@ -0,0 +1,8 @@
import SprachmittlerEngines
/// A BCP-47 language code. Codes are stored as their canonical string form.
public typealias LanguageCode = String
/// The UI-facing name for a target language. The value type lives in `SprachmittlerEngines` because
/// it carries the exact model-card name used by prompts (ADR-014, ADR-017).
public typealias TargetLanguage = SprachmittlerEngines.ModelLanguage
@@ -0,0 +1,21 @@
/// Log categories from ARCHITECTURE §15.
public enum LogCategory: String, CaseIterable, Sendable {
/// Double-copy detection and capture.
case capture
/// Pasteboard polling and own-write suppression.
case pasteboard
/// Translation session lifecycle.
case session
/// Ollama HTTP client.
case ollama
/// Prompt and adapter construction.
case engine
/// Output validation.
case validate
/// Accessibility or paste insertion.
case insert
/// Panel presentation.
case panel
/// Settings persistence.
case settings
}
@@ -0,0 +1,15 @@
import CryptoKit
import Foundation
/// Privacy-safe helpers for log values (SP-2).
public enum LogRedaction {
/// Returns the first 12 lowercase hex characters of the SHA-256 digest of `value`.
///
/// Use this for identifiers that must be correlatable across log lines without revealing
/// the original text. Always log the result with `privacy: .private`; SECURITY_PRIVACY
/// §Logging requires the private qualifier for correlation hashes as well.
public static func shortHash(_ value: String) -> String {
let digest = SHA256.hash(data: Data(value.utf8))
return digest.prefix(6).map { String(format: "%02x", $0) }.joined()
}
}
@@ -0,0 +1,31 @@
import os
/// Factory for the app's `os.Logger` and `OSSignposter` instances.
///
/// The subsystem is supplied by the composition root (the app bundle identifier or the CLI
/// subsystem); this module never hard-codes one.
///
/// ## Leaf modules
/// `SprachmittlerOllama` and `SprachmittlerEngines` cannot import Core. When they gain logging,
/// the composition root passes `Logger` values created here into their initializers. A leaf that
/// needs signposts uses an `OSSignposter` with the literal names from ARCHITECTURE §15. Do not
/// add a Core dependency to a leaf module.
public struct Loggers: Sendable {
/// The `os.Logger` subsystem, normally the app bundle identifier.
public let subsystem: String
/// Creates a factory for the given subsystem.
public init(subsystem: String) {
self.subsystem = subsystem
}
/// Returns the logger for one ARCHITECTURE §15 category.
public func logger(_ category: LogCategory) -> Logger {
Logger(subsystem: subsystem, category: category.rawValue)
}
/// Returns the signposter for one ARCHITECTURE §15 category.
public func signposts(_ category: LogCategory) -> Signposts {
Signposts(subsystem: subsystem, category: category)
}
}
@@ -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,13 @@
import os
/// A started signpost interval.
///
/// The value is intentionally not `Sendable`: an interval must begin and end on the same task.
/// Obtain one from ``Signposts/begin(_:)`` and pass it to ``Signposts/end(_:)``.
public struct SignpostInterval {
/// The interval name.
public let name: SignpostName
let state: OSSignpostIntervalState
let signposter: OSSignposter
}
@@ -0,0 +1,33 @@
/// Signpost interval names from ARCHITECTURE §15.
public enum SignpostName: String, CaseIterable, Sendable {
/// Double-copy detection, from the second copy to a captured text.
case capture
/// Panel presentation.
case panel
/// An Ollama request, from send to the final delta.
case request
/// The first translation token.
case firstToken
/// The full translation of one chunk.
case translate
/// Output validation.
case validate
/// Writing the translation to the clipboard.
case copy
/// Accessibility or paste insertion.
case insert
/// `OSSignposter.beginInterval` requires a `StaticString`, so each case maps to its own literal.
public var literal: StaticString {
switch self {
case .capture: "capture"
case .panel: "panel"
case .request: "request"
case .firstToken: "firstToken"
case .translate: "translate"
case .validate: "validate"
case .copy: "copy"
case .insert: "insert"
}
}
}
@@ -0,0 +1,29 @@
import os
/// Thin wrapper around `OSSignposter` that uses the names from ARCHITECTURE §15.
///
/// Leaf modules cannot import Core; the composition root can pass an `OSSignposter` directly to
/// them, using the literal names in ARCHITECTURE §15.
public struct Signposts: Sendable {
private let signposter: OSSignposter
init(subsystem: String, category: LogCategory) {
signposter = OSSignposter(subsystem: subsystem, category: category.rawValue)
}
/// Starts an interval; pair it with ``end(_:)`` on the same task.
public func begin(_ name: SignpostName) -> SignpostInterval {
let state = signposter.beginInterval(name.literal)
return SignpostInterval(name: name, state: state, signposter: signposter)
}
/// Ends an interval started by ``begin(_:)``.
public func end(_ interval: SignpostInterval) {
interval.signposter.endInterval(interval.name.literal, interval.state)
}
/// Emits a single signpost event.
public func event(_ name: SignpostName) {
signposter.emitEvent(name.literal)
}
}
@@ -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,322 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
import SprachmittlerText
/// Timing for one completed translation (`docs/ARCHITECTURE.md` §5).
public struct TranslationTiming: Sendable, Equatable {
/// Time to the first delta, when one arrived.
public let firstTokenMs: Int?
/// Total time.
public let totalMs: Int
/// Prompt tokens reported by Ollama, summed over attempts.
public let promptTokens: Int?
/// Output tokens reported by Ollama, summed over attempts.
public let outputTokens: Int?
/// Creates a timing value.
public init(firstTokenMs: Int?, totalMs: Int, promptTokens: Int?, outputTokens: Int?) {
self.firstTokenMs = firstTokenMs
self.totalMs = totalMs
self.promptTokens = promptTokens
self.outputTokens = outputTokens
}
}
/// The result of the documented translation pipeline.
public struct PipelineResult: Sendable, Equatable {
/// The translation after T1 only.
public let translation: String
/// Validation warnings and guard findings from the output validator.
public let warnings: [TranslationWarning]
/// The advisory source language, when detection succeeded.
public let sourceLanguage: String?
/// Timing counters.
public let timing: TranslationTiming
/// How many chunks were translated.
public let chunkCount: Int
/// Creates a result.
public init(
translation: String,
warnings: [TranslationWarning],
sourceLanguage: String?,
timing: TranslationTiming,
chunkCount: Int
) {
self.translation = translation
self.warnings = warnings
self.sourceLanguage = sourceLanguage
self.timing = timing
self.chunkCount = chunkCount
}
}
/// Translates text with the documented prompt, chunking and validation.
///
/// This type is shared by the CLI and the M4 session. It never edits the model output beyond T1
/// and it retries only once, only when a protected token was lost.
public struct TranslationPipeline: Sendable {
private let chat: any OllamaChatting
private let registry: AdapterRegistry
private let detector: any LanguageDetecting
private let chunker: Chunker
private let scanner: ProtectedTokenScanner
private let validator: OutputValidator
private let policy: PromptPolicy
private let clock: @Sendable () -> Date
/// Creates a pipeline. Concrete clients come from the composition root.
public init(
chat: any OllamaChatting,
registry: AdapterRegistry,
detector: any LanguageDetecting = NaturalLanguageDetector(),
chunker: Chunker = Chunker(),
scanner: ProtectedTokenScanner = ProtectedTokenScanner(),
validator: OutputValidator = OutputValidator(),
policy: PromptPolicy = PromptPolicy(),
clock: @escaping @Sendable () -> Date = { Date() }
) {
self.chat = chat
self.registry = registry
self.detector = detector
self.chunker = chunker
self.scanner = scanner
self.validator = validator
self.policy = policy
self.clock = clock
}
/// Translates `text` into `target` with `model`.
public func translate(
text: String,
target: ModelLanguage,
model: String,
keepAlive: String
) async throws -> PipelineResult {
let normalized = TextNormalization.normalizeInput(text)
guard !normalized.isEmpty else {
throw SprachmittlerError.emptyText
}
guard registry.adapter(for: model) != nil else {
throw SprachmittlerError.noAdapter(model: model)
}
let started = clock()
let detection = detector.detect(normalized)
let content = ContentClassifier(scanner: scanner).classify(normalized)
let tokens = scanner.scan(normalized)
let chunks = chunker.chunks(for: normalized)
let context = TranslationContext(
content: content,
target: target,
model: model,
keepAlive: keepAlive,
tokens: tokens
)
let accumulator = try await translateAll(chunks, context: context)
let final = TextNormalization.normalizeOutput(accumulator.joined)
let validation = validator.validate(
source: normalized,
translation: final,
doneReason: accumulator.sawLength ? "length" : nil,
tokens: tokens
)
var warnings = accumulator.warnings
warnings.append(contentsOf: validation.warnings)
if let detection, LanguageMatching.isSameLanguage(detection, target: target) {
warnings.append(.sameLanguage(source: detection.code, target: target.code))
}
let elapsed = max(0, Int(clock().timeIntervalSince(started) * 1000))
let firstTokenMs = accumulator.firstTokenAt.map { max(0, Int($0.timeIntervalSince(started) * 1000)) }
return PipelineResult(
translation: final,
warnings: deduplicated(warnings),
sourceLanguage: detection?.code,
timing: TranslationTiming(
firstTokenMs: firstTokenMs,
totalMs: elapsed,
promptTokens: accumulator.promptTokens,
outputTokens: accumulator.outputTokens
),
chunkCount: chunks.count
)
}
private struct TranslationContext {
let content: ContentClass
let target: ModelLanguage
let model: String
let keepAlive: String
let tokens: [ProtectedToken]
}
private struct Accumulator {
var firstTokenAt: Date?
var promptTokens: Int?
var outputTokens: Int?
var joined = ""
var warnings: [TranslationWarning] = []
var sawLength = false
}
private func translateAll(_ chunks: [TextChunk], context: TranslationContext) async throws -> Accumulator {
var accumulator = Accumulator()
do {
for chunk in chunks {
try Task.checkCancellation()
let result = try await translateChunk(chunk, context: context)
if accumulator.firstTokenAt == nil {
accumulator.firstTokenAt = result.firstTokenAt
}
accumulator.promptTokens = sum(accumulator.promptTokens, result.promptTokens)
accumulator.outputTokens = sum(accumulator.outputTokens, result.outputTokens)
if result.looped {
accumulator.warnings.append(.repetitionLoop)
}
if result.doneReason == "length" {
accumulator.sawLength = true
}
accumulator.joined += result.text + chunk.separatorAfter
}
} catch is CancellationError {
throw SprachmittlerError.cancelled
}
return accumulator
}
private struct ChunkTranslation {
let text: String
let doneReason: String?
let looped: Bool
let firstTokenAt: Date?
let promptTokens: Int?
let outputTokens: Int?
}
private func translateChunk(
_ chunk: TextChunk,
context: TranslationContext
) async throws -> ChunkTranslation {
let chunkTokens = context.tokens.filter { chunk.text.contains($0.value) }
var prompt = policy.initialPrompt(for: context.content)
var retried = false
var response = StreamResult(
text: "",
doneReason: nil,
metrics: .empty,
firstTokenAt: nil,
looped: false
)
var promptTokens: Int?
var outputTokens: Int?
while true {
let request = try registry.makeRequest(
AdapterRequest(
text: chunk.text,
target: context.target,
model: context.model,
keepAlive: context.keepAlive,
prompt: prompt
)
)
let attempt = try await stream(request)
response = attempt
promptTokens = sum(promptTokens, attempt.metrics.promptEvalCount)
outputTokens = sum(outputTokens, attempt.metrics.evalCount)
let translated = TextNormalization.normalizeOutput(attempt.text)
let missing = validator.missingTokens(
source: chunk.text,
translation: translated,
tokens: chunkTokens
)
let retryPrompt = missing.isEmpty
? nil
: policy.retryPrompt(for: context.content, lostToken: missing[0])
if !retried, let retryPrompt {
retried = true
prompt = retryPrompt
continue
}
break
}
return ChunkTranslation(
text: TextNormalization.normalizeOutput(response.text),
doneReason: response.doneReason,
looped: response.looped,
firstTokenAt: response.firstTokenAt,
promptTokens: promptTokens,
outputTokens: outputTokens
)
}
private struct StreamResult {
let text: String
let doneReason: String?
let metrics: ChatMetrics
let firstTokenAt: Date?
let looped: Bool
}
private func stream(_ request: ChatRequest) async throws -> StreamResult {
var text = ""
var doneReason: String?
var metrics = ChatMetrics.empty
var firstTokenAt: Date?
var repetition = RepetitionDetector()
var looped = false
do {
for try await event in chat.chat(request) {
try Task.checkCancellation()
switch event {
case let .delta(delta):
if firstTokenAt == nil {
firstTokenAt = clock()
}
text += delta
if repetition.append(delta) {
looped = true
}
case let .done(reason, doneMetrics):
doneReason = reason
metrics = doneMetrics
}
if looped {
break
}
}
} catch let error as OllamaError {
throw SprachmittlerError(ollama: error)
} catch is CancellationError {
throw SprachmittlerError.cancelled
}
return StreamResult(
text: text,
doneReason: doneReason,
metrics: metrics,
firstTokenAt: firstTokenAt,
looped: looped
)
}
private func sum(_ current: Int?, _ next: Int?) -> Int? {
switch (current, next) {
case let (current?, next?): current + next
case let (current?, nil): current
case let (nil, next?): next
case (nil, nil): nil
}
}
private func deduplicated(_ warnings: [TranslationWarning]) -> [TranslationWarning] {
var seen = Set<TranslationWarning>()
return warnings.filter { seen.insert($0).inserted }
}
}
@@ -0,0 +1,5 @@
import SprachmittlerEngines
/// Validation warnings are defined in `SprachmittlerEngines`, where validation lives, and
/// re-exported here for the session and UI layers.
public typealias TranslationWarning = SprachmittlerEngines.TranslationWarning
@@ -0,0 +1,52 @@
import SprachmittlerOllama
/// The Hy-MT3 adapter: exact documented prompt, publisher sampling, no system message, no
/// thinking and an explicit 8192-token context (`docs/HYMT3_MODEL.md` §1–§3).
public struct HyMT3Adapter: TranslationAdapter {
/// The stable adapter identifier.
public let identifier = "hy-mt3"
/// The adapter version.
public let version = 1
/// Creates the adapter.
public init() {}
/// Matches every Hy-MT3 tag, including 7B, 1.8B and 30B-A3B conversions.
public func supports(model: String) -> Bool {
HyMT3ModelPreset.isHyMT3(model)
}
/// Builds one documented request. There is exactly one user message and no system message.
public func makeRequest(_ request: AdapterRequest) -> ChatRequest {
let content = HyMT3Prompt.text(for: request.prompt, target: request.target, source: request.text)
return ChatRequest(
model: request.model,
messages: [ChatMessage(content: content)],
stream: true,
keepAlive: request.keepAlive,
options: request.sampling.chatOptions()
)
}
/// A warm-up request with fixed synthetic text and `num_predict: 8` (T1.5).
public func warmUpRequest(model: String, keepAlive: String) -> 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(model: String) -> ChatRequest {
ChatRequest(
model: model,
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
stream: true,
keepAlive: "0",
options: HyMT3Options.warmUp
)
}
}
@@ -0,0 +1,202 @@
import Foundation
/// The complete Hy-MT3 language catalogue from `docs/LANGUAGES.md`.
///
/// `modelName` is the exact English name from the model card and is the only value that may enter
/// a prompt. BCP-47 variants collapse to the canonical entry; unknown codes return nil.
public enum HyMT3Languages {
/// English.
public static let english = lang("en", "English")
/// German.
public static let german = lang("de", "German")
/// All 102 supported languages, in the documentation's order.
public static let all: [ModelLanguage] = [
// Supported since Hy-MT2 (33)
lang("zh", "Chinese", display: "Chinese (Simplified)", dense: true),
english,
lang("fr", "French"),
lang("pt", "Portuguese"),
lang("es", "Spanish"),
lang("ja", "Japanese", dense: true),
lang("tr", "Turkish"),
lang("ru", "Russian"),
lang("ar", "Arabic", rtl: true, dense: true),
lang("ko", "Korean", dense: true),
lang("th", "Thai", dense: true),
lang("it", "Italian"),
german,
lang("vi", "Vietnamese"),
lang("ms", "Malay"),
lang("id", "Indonesian"),
lang("tl", "Filipino"),
lang("hi", "Hindi", dense: true),
lang("zh-Hant", "Traditional Chinese", dense: true),
lang("pl", "Polish"),
lang("cs", "Czech"),
lang("nl", "Dutch"),
lang("km", "Khmer", dense: true),
lang("my", "Burmese", dense: true),
lang("fa", "Persian", rtl: true, dense: true),
lang("gu", "Gujarati", dense: true),
lang("ur", "Urdu", rtl: true, dense: true),
lang("te", "Telugu", dense: true),
lang("mr", "Marathi", dense: true),
lang("he", "Hebrew", rtl: true, dense: true),
lang("bn", "Bengali", dense: true),
lang("ta", "Tamil", dense: true),
lang("uk", "Ukrainian"),
// Chinese minority languages and dialects (5)
lang("bo", "Tibetan", dense: true),
lang("mn", "Traditional Mongolian", dense: true),
lang("yue", "Cantonese", dense: true),
lang("kk", "Arabic Kazakh", rtl: true, dense: true),
lang("ug", "Uyghur", rtl: true, dense: true),
// Newly supported in Hy-MT3 (64)
lang("el", "Greek"),
lang("cy", "Welsh"),
lang("si", "Sinhala", dense: true),
lang("ro", "Romanian"),
lang("ca", "Catalan"),
lang("pa", "Punjabi", dense: true),
lang("hu", "Hungarian"),
lang("gl", "Galician"),
lang("sd", "Sindhi", rtl: true, dense: true),
lang("bg", "Bulgarian"),
lang("eu", "Basque"),
lang("as", "Assamese", dense: true),
lang("sr", "Serbian"),
lang("af", "Afrikaans"),
lang("or", "Odia", dense: true),
lang("hr", "Croatian"),
lang("lb", "Luxembourgish"),
lang("kn", "Kannada", dense: true),
lang("sk", "Slovak"),
lang("mt", "Maltese"),
lang("ml", "Malayalam", dense: true),
lang("sl", "Slovenian"),
lang("eo", "Esperanto"),
lang("sa", "Sanskrit", dense: true),
lang("sq", "Albanian"),
lang("yi", "Yiddish", rtl: true, dense: true),
lang("lo", "Lao", dense: true),
lang("mk", "Macedonian"),
lang("hy", "Armenian"),
lang("jv", "Javanese"),
lang("be", "Belarusian"),
lang("ka", "Georgian"),
lang("su", "Sundanese"),
lang("lt", "Lithuanian"),
lang("az", "Azerbaijani"),
lang("ceb", "Cebuano"),
lang("lv", "Latvian"),
lang("uz", "Uzbek"),
lang("war", "Waray"),
lang("et", "Estonian"),
lang("ky", "Kyrgyz"),
lang("sw", "Swahili"),
lang("fi", "Finnish"),
lang("tk", "Turkmen"),
lang("am", "Amharic", dense: true),
lang("sv", "Swedish"),
lang("tg", "Tajik"),
lang("so", "Somali"),
lang("da", "Danish"),
lang("tt", "Tatar"),
lang("mg", "Malagasy"),
lang("nb", "Norwegian"),
lang("ba", "Bashkir"),
lang("ht", "Haitian Creole"),
lang("nn", "Norwegian Nynorsk"),
lang("ku", "Kurdish"),
lang("kk-Cyrl", "Cyrillic Kazakh"),
lang("is", "Icelandic"),
lang("ckb", "Central Kurdish", rtl: true, dense: true),
lang("mn-Cyrl", "Cyrillic Mongolian"),
lang("ga", "Irish"),
lang("ps", "Pashto", rtl: true, dense: true),
lang("gd", "Scottish Gaelic"),
lang("ne", "Nepali", dense: true),
]
/// The 15 common targets from `docs/LANGUAGES.md` §5, in display order.
public static let common: [ModelLanguage] = [
"en", "de", "fr", "es", "it", "pt", "nl", "pl", "zh", "ja", "ko", "ar", "tr", "ru", "uk",
].compactMap { byCode[$0] }
/// The number of catalogue entries; the model card documents 102.
public static var count: Int {
all.count
}
private static let byCode: [String: ModelLanguage] = Dictionary(
all.map { ($0.code.lowercased(), $0) },
uniquingKeysWith: { first, _ in first }
)
private static let aliases: [String: String] = [
"zh-hans": "zh", "zh-cn": "zh", "zh-sg": "zh",
"zh-tw": "zh-Hant", "zh-hk": "zh-Hant", "zh-tr": "zh-Hant",
"pt-br": "pt", "pt-pt": "pt",
"no": "nb", "fil": "tl", "iw": "he", "in": "id",
"kk-kz": "kk-Cyrl",
]
/// Resolves a BCP-47 code case-insensitively. Variants collapse to the canonical entry;
/// unknown codes return nil and are never guessed (`docs/LANGUAGES.md` §4).
public static func resolve(_ code: String) -> ModelLanguage? {
let normalized = code
.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: "_", with: "-")
.lowercased()
guard !normalized.isEmpty else { return nil }
if let exact = byCode[normalized] {
return exact
}
if let alias = aliases[normalized], let language = byCode[alias.lowercased()] {
return language
}
if normalized.hasPrefix("zh-hant") {
return byCode["zh-hant"]
}
if normalized.hasPrefix("zh") {
return byCode["zh"]
}
if normalized.hasPrefix("kk-cyrl") {
return byCode["kk-cyrl"]
}
if normalized.hasPrefix("mn-cyrl") {
return byCode["mn-cyrl"]
}
if let separator = normalized.firstIndex(of: "-") {
let base = String(normalized[..<separator])
return byCode[base]
}
return nil
}
/// All right-to-left languages.
public static var rightToLeft: [ModelLanguage] {
all.filter(\.isRTL)
}
private static func lang(
_ code: String,
_ modelName: String,
display: String? = nil,
rtl: Bool = false,
dense: Bool = false
) -> ModelLanguage {
ModelLanguage(
code: code,
modelName: modelName,
displayName: display,
isRTL: rtl,
usesDenseScript: dense
)
}
}
@@ -0,0 +1,17 @@
/// 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."
/// True for any Hy-MT3 conversion tag. The registry uses this through `HyMT3Adapter`.
public static func isHyMT3(_ model: String) -> Bool {
model.lowercased().contains("hy-mt3")
}
}
@@ -0,0 +1,10 @@
import SprachmittlerOllama
/// Documented Hy-MT3 option sets (`docs/HYMT3_MODEL.md` §2).
public enum HyMT3Options {
/// Warm-up uses the publisher sampling but only 8 output tokens. The publisher values come
/// from `SamplingOptions`, so there is one source of truth.
public static let warmUp = SamplingOptions.publisherDefault
.merging(SamplingOverrides(numPredict: 8))
.chatOptions()
}
@@ -0,0 +1,61 @@
/// The documented Hy-MT3 prompt templates (`docs/HYMT3_MODEL.md` §3–§4).
///
/// These are the only prompt strings in the app. The Default template is canonical for v1; the
/// Delimiters and Structured Data 1 templates are the only documented fallbacks (ADR-012).
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
}
/// The byte-exact Delimiters prompt, the single documented fallback for a lost token.
public static func delimiters(target: ModelLanguage, source: String) -> String {
let instruction = "Please accurately translate the following text into \(target.modelName). "
+ "You must **retain the exact same number of delimiters in the translation. Strictly do "
+ "not omit, escape, or translate these symbols, and pay close attention to their placement**."
return instruction + "\n\n" + source
}
/// The byte-exact Structured Data 1 prompt for JSON, HTML or Markdown.
public static func structuredData1(
format: StructuredFormat,
target: ModelLanguage,
source: String
) -> String {
let type = format.rawValue
let preservation = "1. **Structure Preservation:** You MUST preserve the original \(type) data "
+ "structure, nesting, hierarchy, and indentation exactly as they are."
let nonTranslation = "3. **Strict Non-Translation:** NEVER translate or alter code tags, keys, "
+ "properties, object names, or variable placeholders. Leave them exactly in their original "
+ "English/code form."
return [
"### Task",
"Translate the user-facing text within the following \(type) data into \(target.modelName).",
"",
"### Strict Rules",
preservation,
"2. **Selective Translation:** Translate ONLY the visible, user-facing text content/values.",
nonTranslation,
"",
"### Source Data",
source,
].joined(separator: "\n")
}
/// Builds the prompt for a variant.
public static func text(for variant: PromptVariant, target: ModelLanguage, source: String) -> String {
switch variant {
case .defaultTranslation:
defaultTranslation(target: target, source: source)
case .delimiters:
delimiters(target: target, source: source)
case let .structuredData1(format):
structuredData1(format: format, target: target, source: source)
}
}
}
@@ -0,0 +1,21 @@
import SprachmittlerText
/// Family-neutral same-language check used by the pipeline. The canonical-code mapping stays in
/// Engines, next to the catalogue that defines it.
public enum LanguageMatching {
/// True when detection is confident and every alternative resolves to the target language.
public static func isSameLanguage(_ detection: LanguageDetection, target: ModelLanguage) -> Bool {
guard detection.confidence >= 0.5, !detection.alternatives.isEmpty else { return false }
let targetCode = HyMT3Languages.resolve(target.code)?.code ?? target.code
var agreed = false
for code in detection.alternatives {
guard let language = HyMT3Languages.resolve(code),
language.code.caseInsensitiveCompare(targetCode) == .orderedSame
else {
return false
}
agreed = true
}
return agreed
}
}
@@ -0,0 +1,48 @@
import Foundation
/// A BCP-47 code paired with the exact English model-card name used in the prompt.
///
/// `modelName` is never localised: it is inserted into the prompt byte for byte
/// (`docs/LANGUAGES.md` §4). Use `localizedDisplayName` for UI labels.
public struct ModelLanguage: Sendable, Hashable, Codable, Identifiable {
/// The canonical BCP-47 code, e.g. `de`, `zh-Hant` or `kk-Cyrl`.
public let code: String
/// The exact model-card name, e.g. `German` or `Traditional Chinese`.
public let modelName: String
/// The English display name, used as a fallback when `Locale` has no localised name.
public let displayName: String
/// True for right-to-left scripts.
public let isRTL: Bool
/// True for scripts that use the smaller chunk limit.
public let usesDenseScript: Bool
/// `Identifiable` conformance for UI lists.
public var id: String {
code
}
/// The display name in the current UI locale, never used in a prompt. When the locale only
/// has a generic name (for example “Chinese”), the catalogue's more specific name wins.
public var localizedDisplayName: String {
let localized = Locale.current.localizedString(forLanguageCode: code)
if let localized, localized.caseInsensitiveCompare(modelName) != .orderedSame {
return localized
}
return displayName
}
/// Creates a language entry.
public init(
code: String,
modelName: String,
displayName: String? = nil,
isRTL: Bool = false,
usesDenseScript: Bool = false
) {
self.code = code
self.modelName = modelName
self.displayName = displayName ?? modelName
self.isRTL = isRTL
self.usesDenseScript = usesDenseScript
}
}
@@ -0,0 +1,42 @@
import Foundation
/// Normalises numeric tokens for the semantic check in `docs/TRANSLATION_OUTPUT.md` §9.
///
/// Locale separators legitimately change during translation, so `1.5`, `1,5` and `1 5` may all
/// represent the same value. Thousands separators are removed and the decimal separator becomes
/// `.`. This never edits the translation; it only decides whether a warning is shown.
public enum NumericTokenNormalizer {
private static let regex = try? NSRegularExpression(pattern: "\\d+(?:[.,\\s]\\d+)*")
/// The normalised numeric values in `text`, in source order.
public static func numbers(in text: String) -> [String] {
guard let regex else { return [] }
let nsText = text as NSString
let matches = regex.matches(in: text, range: NSRange(location: 0, length: nsText.length))
return matches.map { normalize(nsText.substring(with: $0.range)) }
}
/// Normalises one numeric token.
public static func normalize(_ raw: String) -> String {
var value = raw.filter { !$0.isWhitespace }
guard !value.isEmpty else { return value }
let hasComma = value.contains(",")
let hasDot = value.contains(".")
if hasComma, hasDot, let comma = value.lastIndex(of: ","), let dot = value.lastIndex(of: ".") {
let decimal = comma > dot ? comma : dot
let integer = value[..<decimal].filter { $0 != "," && $0 != "." }
let fraction = value[value.index(after: decimal)...].filter { $0 != "," && $0 != "." }
value = String(integer) + "." + String(fraction)
} else if hasComma || hasDot {
let separator: Character = hasComma ? "," : "."
let parts = value.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
if parts.count == 2, parts[1].count == 3, parts[0] != "0", !parts[0].isEmpty {
value = parts[0] + parts[1]
} else if separator == "," {
value = parts.joined(separator: ".")
}
}
return value
}
}
@@ -0,0 +1,101 @@
import SprachmittlerText
/// The completed validation of one translation.
public struct OutputValidation: Sendable, Equatable {
/// Every warning found, in a stable order.
public let warnings: [TranslationWarning]
/// True when at least one warning should disable Replace by default.
public var blocksReplacement: Bool {
warnings.contains(where: \.blocksReplacement)
}
/// Creates a validation result.
public init(warnings: [TranslationWarning]) {
self.warnings = warnings
}
/// A clean result.
public static let clean = OutputValidation(warnings: [])
}
/// Validation from `docs/TRANSLATION_OUTPUT.md` §4–§7. It never edits the output.
public struct OutputValidator: Sendable {
private let preambleDetector: PreambleDetector
/// Creates a validator.
public init(preambleDetector: PreambleDetector = PreambleDetector()) {
self.preambleDetector = preambleDetector
}
/// Validates a T1-normalised translation.
public func validate(
source: String,
translation: String,
doneReason: String?,
tokens: [ProtectedToken],
includeRepetition: Bool = true
) -> OutputValidation {
if translation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return OutputValidation(warnings: [.emptyOutput])
}
var warnings: [TranslationWarning] = []
if doneReason == "length" {
warnings.append(.truncated)
}
if includeRepetition, RepetitionDetector.detectsLoop(in: translation) {
warnings.append(.repetitionLoop)
}
if let line = preambleDetector.firstLine(in: translation) {
warnings.append(.preambleDetected(firstLine: line))
}
for token in uniqueTokens(tokens) where count(of: token.value, in: source) != count(
of: token.value,
in: translation
) {
warnings.append(.missingProtectedToken(token.value))
}
let sourceNumbers = Set(NumericTokenNormalizer.numbers(in: source))
let translatedNumbers = Set(NumericTokenNormalizer.numbers(in: translation))
if !sourceNumbers.isSubset(of: translatedNumbers) {
warnings.append(.numericMismatch)
}
return OutputValidation(warnings: deduplicated(warnings))
}
/// The protected tokens whose occurrence count differs between source and translation.
public func missingTokens(
source: String,
translation: String,
tokens: [ProtectedToken]
) -> [ProtectedToken] {
uniqueTokens(tokens).filter {
count(of: $0.value, in: source) != count(of: $0.value, in: translation)
}
}
private func uniqueTokens(_ tokens: [ProtectedToken]) -> [ProtectedToken] {
var seen = Set<ProtectedToken>()
return tokens.filter { seen.insert($0).inserted }
}
private func deduplicated(_ warnings: [TranslationWarning]) -> [TranslationWarning] {
var seen = Set<TranslationWarning>()
return warnings.filter { seen.insert($0).inserted }
}
private func count(of needle: String, in haystack: String) -> Int {
guard !needle.isEmpty else { return 0 }
var count = 0
var searchRange = haystack.startIndex ..< haystack.endIndex
while let range = haystack.range(of: needle, range: searchRange) {
count += 1
searchRange = range.upperBound ..< haystack.endIndex
}
return count
}
}
@@ -0,0 +1,28 @@
/// Detects a likely model preamble without rewriting it (`docs/TRANSLATION_OUTPUT.md` §6).
public struct PreambleDetector: Sendable {
/// The maximum first-line length for a preamble.
public static let maximumFirstLineLength = 80
/// Creates a detector.
public init() {}
/// Returns the suspicious first line, or nil.
///
/// The heuristic is deliberately simple: a first non-empty line of at most 80 characters
/// ending in `:` or `:`, followed by a blank line and at least one more non-empty line.
public func firstLine(in text: String) -> String? {
let lines = text.components(separatedBy: "\n")
guard let firstIndex = lines.firstIndex(where: { !$0.trimmingCharacters(in: .whitespaces).isEmpty })
else {
return nil
}
let line = lines[firstIndex].trimmingCharacters(in: .whitespaces)
guard line.count <= Self.maximumFirstLineLength, line.hasSuffix(":") || line.hasSuffix(":"),
firstIndex + 1 < lines.count,
lines[firstIndex + 1].trimmingCharacters(in: .whitespaces).isEmpty else { return nil }
let hasMoreText = lines[(firstIndex + 2)...].contains {
!$0.trimmingCharacters(in: .whitespaces).isEmpty
}
return hasMoreText ? line : nil
}
}
@@ -0,0 +1,32 @@
import SprachmittlerText
/// Chooses the documented prompt template (`docs/TRANSLATION_OUTPUT.md` §1, ADR-012).
///
/// v1 starts with Default Translation for everything. Structured Data 1 and Delimiters are used
/// only as the single fallback after a protected token was lost.
public struct PromptPolicy: Sendable {
/// Creates a policy.
public init() {}
/// The initial prompt for a content class. v1 always returns Default Translation.
public func initialPrompt(for content: ContentClass) -> PromptVariant {
_ = content
return .defaultTranslation
}
/// The one fallback prompt for a lost protected token, or nil when no documented fallback
/// applies. The caller enforces the one-retry limit.
public func retryPrompt(for content: ContentClass, lostToken: ProtectedToken) -> PromptVariant? {
switch content {
case .json:
return .structuredData1(format: .json)
case .html:
return .structuredData1(format: .html)
case .markdown:
return .structuredData1(format: .markdown)
case .code, .delimited, .plain:
_ = lostToken
return .delimiters
}
}
}
@@ -0,0 +1,19 @@
/// The documented formats for Structured Data 1.
public enum StructuredFormat: String, Sendable, Equatable, CaseIterable {
/// JSON data.
case json = "JSON"
/// HTML markup.
case html = "HTML"
/// Markdown text.
case markdown = "Markdown"
}
/// One of the documented prompt templates (`docs/HYMT3_MODEL.md` §4).
public enum PromptVariant: Sendable, Equatable {
/// The canonical Default Translation template.
case defaultTranslation
/// The Delimiters template; used once when a protected token is lost in plain text.
case delimiters
/// Structured Data 1 with the matching format; used once for structured text.
case structuredData1(format: StructuredFormat)
}
@@ -0,0 +1,71 @@
/// Detects repetition loops in a streaming translation (`docs/TRANSLATION_OUTPUT.md` §7).
public struct RepetitionDetector: Sendable {
/// The repeated-line threshold.
public static let minimumLineLength = 8
/// How many identical consecutive lines count as a loop.
public static let lineRepeatThreshold = 6
/// The repeated-window length.
public static let windowLength = 64
/// How many identical windows count as a loop.
public static let windowRepeatThreshold = 8
/// How much trailing text is inspected for window loops.
public static let windowSearchLength = 2048
private var buffer = ""
/// Creates a detector.
public init() {}
/// Appends a delta and returns true when a loop is detected.
public mutating func append(_ delta: String) -> Bool {
buffer += delta
if buffer.count > Self.windowSearchLength * 2 {
buffer = String(buffer.suffix(Self.windowSearchLength))
}
return Self.detectsLoop(in: buffer)
}
/// Checks a complete or partial output for a loop.
public static func detectsLoop(in text: String) -> Bool {
hasRepeatedLine(in: text) || hasRepeatedWindow(in: text)
}
private static func hasRepeatedLine(in text: String) -> Bool {
let lines = text
.components(separatedBy: "\n")
.suffix(12)
.map { $0.trimmingCharacters(in: .whitespaces) }
guard !lines.isEmpty else { return false }
var run = 1
for index in 1 ..< lines.count {
if !lines[index].isEmpty, lines[index].count >= minimumLineLength, lines[index] == lines[index - 1] {
run += 1
if run >= lineRepeatThreshold {
return true
}
} else {
run = 1
}
}
return false
}
private static func hasRepeatedWindow(in text: String) -> Bool {
guard text.count >= windowLength else { return false }
let search = String(text.suffix(windowSearchLength))
let window = String(text.suffix(windowLength))
guard search.count >= windowLength * windowRepeatThreshold else { return false }
var count = 0
var range = search.startIndex ..< search.endIndex
while let found = search.range(of: window, range: range) {
count += 1
if count >= windowRepeatThreshold {
return true
}
range = found.upperBound ..< search.endIndex
}
return false
}
}
@@ -0,0 +1,107 @@
import SprachmittlerOllama
/// The documented Hy-MT3 sampling values (`docs/HYMT3_MODEL.md` §2).
public struct SamplingOptions: Sendable, Equatable {
/// `temperature`.
public var temperature: Double
/// `top_p`.
public var topP: Double
/// `top_k`.
public var topK: Int
/// `repeat_penalty`.
public var repeatPenalty: Double
/// `num_predict`.
public var numPredict: Int
/// `num_ctx`.
public var numCtx: Int
/// Creates sampling values.
public init(
temperature: Double = 0.7,
topP: Double = 0.6,
topK: Int = 20,
repeatPenalty: Double = 1.05,
numPredict: Int = 4096,
numCtx: Int = 8192
) {
self.temperature = temperature
self.topP = topP
self.topK = topK
self.repeatPenalty = repeatPenalty
self.numPredict = numPredict
self.numCtx = numCtx
}
/// The publisher's recommendation for 1.8B and 7B.
public static let publisherDefault = SamplingOptions()
/// Applies explicit overrides on top of these values. Publisher values are always sent; a
/// model default is never relied on, because `/api/show` exposes no sampling defaults.
public func merging(_ overrides: SamplingOverrides) -> SamplingOptions {
var merged = self
if let value = overrides.temperature {
merged.temperature = value
}
if let value = overrides.topP {
merged.topP = value
}
if let value = overrides.topK {
merged.topK = value
}
if let value = overrides.repeatPenalty {
merged.repeatPenalty = value
}
if let value = overrides.numPredict {
merged.numPredict = value
}
if let value = overrides.numCtx {
merged.numCtx = value
}
return merged
}
/// The exact Ollama option names sent on the wire.
public func chatOptions() -> ChatOptions {
ChatOptions(
temperature: temperature,
topP: topP,
topK: topK,
repeatPenalty: repeatPenalty,
numPredict: numPredict,
numCtx: numCtx
)
}
}
/// Optional per-setting overrides. Only the documented six sampling keys exist.
public struct SamplingOverrides: Sendable, Equatable {
/// `temperature` override.
public var temperature: Double?
/// `top_p` override.
public var topP: Double?
/// `top_k` override.
public var topK: Int?
/// `repeat_penalty` override.
public var repeatPenalty: Double?
/// `num_predict` override.
public var numPredict: Int?
/// `num_ctx` override.
public var numCtx: Int?
/// Creates overrides.
public init(
temperature: Double? = nil,
topP: Double? = nil,
topK: Int? = nil,
repeatPenalty: Double? = nil,
numPredict: Int? = nil,
numCtx: Int? = nil
) {
self.temperature = temperature
self.topP = topP
self.topK = topK
self.repeatPenalty = repeatPenalty
self.numPredict = numPredict
self.numCtx = numCtx
}
}
@@ -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,78 @@
import SprachmittlerOllama
import SprachmittlerText
/// One translation request before a model family adapter shapes it.
public struct AdapterRequest: Sendable, Equatable {
/// The chunk text.
public let text: String
/// The target language.
public let target: ModelLanguage
/// The installed model tag.
public let model: String
/// The Ollama `keep_alive` value.
public let keepAlive: String
/// The documented prompt template.
public let prompt: PromptVariant
/// The sampling values.
public let sampling: SamplingOptions
/// Creates a request.
public init(
text: String,
target: ModelLanguage,
model: String,
keepAlive: String,
prompt: PromptVariant = .defaultTranslation,
sampling: SamplingOptions = .publisherDefault
) {
self.text = text
self.target = target
self.model = model
self.keepAlive = keepAlive
self.prompt = prompt
self.sampling = sampling
}
}
/// A model family adapter: the only type that knows how to turn a translation into a request.
public protocol TranslationAdapter: Sendable {
/// A stable identifier, e.g. `hy-mt3`.
var identifier: String { get }
/// The adapter version; bump when the request shape changes.
var version: Int { get }
/// True when this adapter handles `model`.
func supports(model: String) -> Bool
/// Builds the documented request for one chunk.
func makeRequest(_ request: AdapterRequest) -> ChatRequest
}
/// The adapters available in the app, in priority order.
public struct AdapterRegistry: Sendable {
private let adapters: [any TranslationAdapter]
/// Creates a registry. The production root passes `[HyMT3Adapter()]`.
public init(adapters: [any TranslationAdapter]) {
self.adapters = adapters
}
/// The first adapter that supports `model`, or nil.
public func adapter(for model: String) -> (any TranslationAdapter)? {
adapters.first { $0.supports(model: model) }
}
/// Builds a request or throws `AdapterError.noAdapter` for an unknown family. Never guesses.
public func makeRequest(_ request: AdapterRequest) throws -> ChatRequest {
guard let adapter = adapter(for: request.model) else {
throw AdapterError.noAdapter(model: request.model)
}
return adapter.makeRequest(request)
}
}
/// Errors raised while choosing an adapter.
public enum AdapterError: Error, Sendable, Equatable {
/// No adapter handles this model family.
case noAdapter(model: String)
}
@@ -0,0 +1,45 @@
/// A non-fatal validation finding shown in the panel and the CLI JSON output.
public enum TranslationWarning: Sendable, Equatable, Hashable {
/// A short first line ending in a colon was followed by a blank line and more text.
case preambleDetected(firstLine: String)
/// `done_reason` was `length`.
case truncated
/// The output repeated a line or window too many times.
case repetitionLoop
/// A protected token from the source is missing or changed in the translation.
case missingProtectedToken(String)
/// The translation was empty after T1.
case emptyOutput
/// The detected source language is the target language.
case sameLanguage(source: String, target: String)
/// A source number is absent from the translation.
case numericMismatch
/// One chunk failed; the panel keeps the partial translation.
case chunkFailed(index: Int)
}
public extension TranslationWarning {
/// A stable code for JSON output and diagnostics.
var code: String {
switch self {
case .preambleDetected: "preambleDetected"
case .truncated: "truncated"
case .repetitionLoop: "repetitionLoop"
case .missingProtectedToken: "missingProtectedToken"
case .emptyOutput: "emptyOutput"
case .sameLanguage: "sameLanguage"
case .numericMismatch: "numericMismatch"
case .chunkFailed: "chunkFailed"
}
}
/// Blocking warnings disable Replace by default (`docs/TRANSLATION_OUTPUT.md` §4–§7).
var blocksReplacement: Bool {
switch self {
case .preambleDetected, .truncated, .repetitionLoop, .missingProtectedToken, .emptyOutput, .chunkFailed:
true
case .sameLanguage, .numericMismatch:
false
}
}
}
@@ -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,76 @@
import Foundation
import SprachmittlerCapture
/// A main-actor pasteboard fake for watcher and snapshot tests.
@MainActor
public final class FakePasteboard: PasteboardAccessing {
public private(set) var changeCount: Int
public private(set) var text: String?
public private(set) var items: [ClipboardItemData]
public private(set) var hasOwnWriteMarkers: Bool
public private(set) var stringReadCount = 0
public private(set) var snapshotCount = 0
public private(set) var writtenTexts: [String] = []
public var restoreSucceeds = true
public var snapshotSucceeds = true
public init(
changeCount: Int = 0,
text: String? = nil,
items: [ClipboardItemData] = [],
hasOwnWriteMarkers: Bool = false
) {
self.changeCount = changeCount
self.text = text
self.items = items
self.hasOwnWriteMarkers = hasOwnWriteMarkers
}
/// Simulates another app copying text.
public func simulateCopy(_ text: String?) {
self.text = text
hasOwnWriteMarkers = false
changeCount += 1
}
/// Simulates a copy that carries a transient/own marker.
public func simulateOwnMarkerCopy(_ text: String?) {
self.text = text
hasOwnWriteMarkers = true
changeCount += 1
}
public func string() -> String? {
stringReadCount += 1
return text
}
public func containsOwnWriteMarkers() -> Bool {
hasOwnWriteMarkers
}
public func snapshot() -> ClipboardSnapshot? {
guard snapshotSucceeds else { return nil }
snapshotCount += 1
return ClipboardSnapshot(items: items, changeCount: changeCount)
}
public func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches expected: Int) -> Bool {
guard restoreSucceeds, changeCount == expected else { return false }
items = snapshot.items
text = snapshot.items.first?.data["public.utf8-plain-text"]
.flatMap { String(data: $0, encoding: .utf8) }
hasOwnWriteMarkers = false
changeCount += 1
return true
}
@discardableResult
public func write(_ text: String) -> Int {
writtenTexts.append(text)
self.text = text
hasOwnWriteMarkers = true
changeCount += 1
return changeCount
}
}
@@ -0,0 +1,55 @@
import Foundation
import SprachmittlerCapture
/// A manual ticker for watcher tests. No real time passes.
///
/// `@unchecked Sendable` is safe: every mutable field is guarded by `lock`.
public final class ManualPasteboardTicker: PasteboardTicking, @unchecked Sendable {
private let lock = NSLock()
private var continuation: AsyncStream<Void>.Continuation?
private var terminated = false
private var started = false
/// Creates a manual ticker.
public init() {}
public func ticks() -> AsyncStream<Void> {
AsyncStream { continuation in
lock.lock()
self.continuation = continuation
started = true
lock.unlock()
continuation.onTermination = { [weak self] _ in
self?.markTerminated()
}
}
}
/// True once the watcher has subscribed.
public var isStarted: Bool {
lock.lock()
defer { lock.unlock() }
return started
}
/// Emits one tick.
public func tick() {
lock.lock()
let continuation = continuation
lock.unlock()
continuation?.yield(())
}
/// True once the stream has terminated.
public var isTerminated: Bool {
lock.lock()
defer { lock.unlock() }
return terminated
}
private func markTerminated() {
lock.lock()
terminated = true
lock.unlock()
}
}
@@ -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,243 @@
import Foundation
/// Splits text at paragraph, sentence, word and grapheme boundaries with script-aware limits.
///
/// Joining `chunks(for:)` with `reassemble(_:)` always returns the input exactly. The chunker does
/// not trim, normalise or invent separators; call `TextNormalization.normalizeInput` first.
public struct Chunker: Sendable {
/// The limit for Latin, Cyrillic and Greek text.
public let latinLimit: Int
/// The limit for CJK, Arabic, Thai, Indic and other dense scripts.
public let denseLimit: Int
/// Creates a chunker.
public init(latinLimit: Int = 4000, denseLimit: Int = 2000) {
self.latinLimit = latinLimit
self.denseLimit = denseLimit
}
/// The character limit that applies to `text`.
public func limit(for text: String) -> Int {
TextScript.isDense(text) ? denseLimit : latinLimit
}
/// Splits `text` into chunks of at most the script-aware limit.
public func chunks(for text: String) -> [TextChunk] {
guard !text.isEmpty else { return [] }
let limit = max(1, limit(for: text))
var pieces: [(text: String, separator: String)] = []
for unit in paragraphUnits(text) {
split(unit.text, trailing: unit.separator, limit: limit, into: &pieces)
}
return pack(mergingLeadingEmpty(pieces), limit: limit)
}
/// Reassembles chunks into the original text.
public static func reassemble(_ chunks: [TextChunk]) -> String {
chunks.sorted { $0.index < $1.index }.reduce(into: "") { result, chunk in
result += chunk.text
result += chunk.separatorAfter
}
}
// MARK: - Splitting
private func split(
_ text: String,
trailing: String,
limit: Int,
into pieces: inout [(text: String, separator: String)]
) {
if text.count <= limit {
pieces.append((text, trailing))
return
}
let sentences = sentenceUnits(text)
if sentences.count > 1 {
splitSubunits(sentences, trailing: trailing, limit: limit, into: &pieces)
return
}
let words = wordUnits(text)
if words.count > 1 {
splitSubunits(words, trailing: trailing, limit: limit, into: &pieces)
return
}
splitGraphemes(text, trailing: trailing, into: &pieces)
}
private func splitSubunits(
_ units: [(text: String, separator: String)],
trailing: String,
limit: Int,
into pieces: inout [(text: String, separator: String)]
) {
for (offset, unit) in units.enumerated() {
let separator = offset == units.count - 1 ? unit.separator + trailing : unit.separator
split(unit.text, trailing: separator, limit: limit, into: &pieces)
}
}
private func splitGraphemes(
_ text: String,
trailing: String,
into pieces: inout [(text: String, separator: String)]
) {
let characters = Array(text)
for (offset, character) in characters.enumerated() {
let separator = offset == characters.count - 1 ? trailing : ""
pieces.append((String(character), separator))
}
}
// MARK: - Units
private func paragraphUnits(_ text: String) -> [(text: String, separator: String)] {
guard let regex = try? NSRegularExpression(pattern: "\\n[ \\t]*\\n(?:[ \\t]*\\n)*") else {
return [(text, "")]
}
let nsText = text as NSString
let matches = regex.matches(in: text, range: NSRange(location: 0, length: nsText.length))
guard !matches.isEmpty else { return [(text, "")] }
var units: [(String, String)] = []
var cursor = 0
for match in matches {
let body = nsText.substring(with: NSRange(location: cursor, length: match.range.location - cursor))
let separator = nsText.substring(with: match.range)
units.append((body, separator))
cursor = match.range.location + match.range.length
}
let tail = nsText.substring(from: cursor)
units.append((tail, ""))
return units
}
private func sentenceUnits(_ text: String) -> [(text: String, separator: String)] {
let terminators: Set<Character> = [".", "!", "?", "。", "!", "?", "…"]
let closers: Set<Character> = ["\"", "'", "”", "’", ")", "]", "}"]
let characters = Array(text)
var units: [(String, String)] = []
var start = 0
var index = 0
while index < characters.count {
guard terminators.contains(characters[index]) else {
index += 1
continue
}
var end = index + 1
while end < characters.count, terminators.contains(characters[end]) {
end += 1
}
while end < characters.count, closers.contains(characters[end]) {
end += 1
}
guard end < characters.count, characters[end].isWhitespace else {
index = end
continue
}
var separatorEnd = end
while separatorEnd < characters.count, characters[separatorEnd].isWhitespace {
separatorEnd += 1
}
let body = String(characters[start ..< end])
let separator = String(characters[end ..< separatorEnd])
units.append((body, separator))
start = separatorEnd
index = separatorEnd
}
if start < characters.count {
units.append((String(characters[start...]), ""))
}
return units.isEmpty ? [(text, "")] : units
}
private func wordUnits(_ text: String) -> [(text: String, separator: String)] {
let characters = Array(text)
var units: [(String, String)] = []
var start = 0
var index = 0
while index < characters.count {
guard characters[index].isWhitespace else {
index += 1
continue
}
let body = String(characters[start ..< index])
var end = index
while end < characters.count, characters[end].isWhitespace {
end += 1
}
let separator = String(characters[index ..< end])
units.append((body, separator))
start = end
index = end
}
if start < characters.count {
units.append((String(characters[start...]), ""))
}
return units.isEmpty ? [(text, "")] : units
}
// MARK: - Packing
/// Keeps a leading empty body's separator (for example a text starting with `\n\n` or a long
/// over-limit text starting with whitespace) by attaching it to the first non-empty piece.
private func mergingLeadingEmpty(
_ pieces: [(text: String, separator: String)]
) -> [(text: String, separator: String)] {
var result = pieces
var prefix = ""
while let first = result.first, first.text.isEmpty {
prefix += first.separator
result.removeFirst()
}
guard !result.isEmpty else {
return prefix.isEmpty ? [] : [(prefix, "")]
}
var first = result[0]
first.text = prefix + first.text
result[0] = first
return result
}
private func pack(
_ pieces: [(text: String, separator: String)],
limit: Int
) -> [TextChunk] {
var chunks: [TextChunk] = []
var current = ""
var trailing = ""
var lastSeparator = ""
var index = 0
func emit() {
guard !current.isEmpty else { return }
chunks.append(TextChunk(index: index, text: current, separatorAfter: trailing))
index += 1
current = ""
trailing = ""
lastSeparator = ""
}
for piece in pieces {
if current.isEmpty {
current = piece.text
} else if current.count + lastSeparator.count + piece.text.count <= limit {
current += lastSeparator + piece.text
} else {
emit()
current = piece.text
}
trailing = piece.separator
lastSeparator = piece.separator
}
emit()
return chunks
}
}
@@ -0,0 +1,15 @@
/// The source-content classes from `docs/ARCHITECTURE.md` §9.1.
public enum ContentClass: String, Sendable, Equatable, CaseIterable {
/// Ordinary prose.
case plain
/// Markdown, including headings, lists, tables and fenced code.
case markdown
/// JSON data.
case json
/// HTML markup.
case html
/// Code without Markdown prose.
case code
/// Many placeholders, URLs or delimiters.
case delimited
}
@@ -0,0 +1,53 @@
import Foundation
/// A simple content classifier used only to choose a documented prompt fallback.
public struct ContentClassifier: Sendable {
private let scanner: ProtectedTokenScanner
private static let tagRegex = try? NSRegularExpression(pattern: "</?[A-Za-z][^>]*>")
/// Creates a classifier.
public init(scanner: ProtectedTokenScanner = ProtectedTokenScanner()) {
self.scanner = scanner
}
/// Classifies `text` as plain, Markdown, JSON, HTML, code or delimiter-heavy.
public func classify(_ text: String) -> ContentClass {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return .plain }
if isJSON(trimmed) {
return .json
}
if isHTML(trimmed) {
return .html
}
let fenced = trimmed.components(separatedBy: "```").count > 1
let markdownMarkers = trimmed.components(separatedBy: "\n").filter { line in
let trimmedLine = line.trimmingCharacters(in: .whitespaces)
return trimmedLine.hasPrefix("#") || trimmedLine.hasPrefix("- ") || trimmedLine.hasPrefix("* ")
|| trimmedLine.hasPrefix("> ") || trimmedLine.hasPrefix("|") || trimmedLine.hasPrefix("[")
|| trimmedLine.hasPrefix("![")
}.count
if markdownMarkers >= 1 || fenced {
return fenced && markdownMarkers == 0 ? .code : .markdown
}
let tokens = scanner.scan(trimmed)
if tokens.count >= 3 {
return .delimited
}
return .plain
}
private func isJSON(_ text: String) -> Bool {
guard text.hasPrefix("{") || text.hasPrefix("["), let data = text.data(using: .utf8) else { return false }
return (try? JSONSerialization.jsonObject(with: data)) != nil
}
private func isHTML(_ text: String) -> Bool {
guard let tagRegex = Self.tagRegex else { return false }
let range = NSRange(location: 0, length: (text as NSString).length)
return tagRegex.numberOfMatches(in: text, range: range) >= 2
}
}
@@ -0,0 +1,51 @@
import Foundation
import NaturalLanguage
/// One language hypothesis from `NLLanguageRecognizer`.
public struct LanguageDetection: Sendable, Equatable {
/// The dominant BCP-47 language code, e.g. `en` or `de`.
public let code: String
/// The recogniser confidence in `code`, from 0 to 1.
public let confidence: Double
/// Candidate codes ordered by confidence, including `code` first.
public let alternatives: [String]
/// Creates a detection value.
public init(code: String, confidence: Double, alternatives: [String]) {
self.code = code
self.confidence = confidence
self.alternatives = alternatives
}
}
/// Source-language detection. Advisory only: it never blocks translation.
public protocol LanguageDetecting: Sendable {
/// Detects the dominant language of `text`, or returns nil for empty/undecidable text.
func detect(_ text: String) -> LanguageDetection?
}
/// `NLLanguageRecognizer`-backed detection (`docs/TRANSLATION_OUTPUT.md` §8).
public struct NaturalLanguageDetector: LanguageDetecting {
/// Creates a detector.
public init() {}
/// Detects the dominant language. Short or mixed text usually reports low confidence.
public func detect(_ text: String) -> LanguageDetection? {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return nil }
let recognizer = NLLanguageRecognizer()
recognizer.processString(trimmed)
guard let dominant = recognizer.dominantLanguage else { return nil }
let hypotheses = recognizer.languageHypotheses(withMaximum: 3)
let ordered = hypotheses.sorted { lhs, rhs in
lhs.value == rhs.value ? lhs.key.rawValue < rhs.key.rawValue : lhs.value > rhs.value
}.map(\.key.rawValue)
let alternatives = ordered.isEmpty ? [dominant.rawValue] : ordered
return LanguageDetection(
code: dominant.rawValue,
confidence: Double(hypotheses[dominant] ?? 0),
alternatives: alternatives
)
}
}
@@ -0,0 +1,39 @@
import Foundation
/// A protected token that must survive translation (`docs/TRANSLATION_OUTPUT.md` §4).
public struct ProtectedToken: Sendable, Equatable, Hashable {
/// The token kind.
public let kind: ProtectedTokenKind
/// The exact text that must appear in the translation.
public let value: String
/// Creates a protected token.
public init(kind: ProtectedTokenKind, value: String) {
self.kind = kind
self.value = value
}
}
/// The protected-token kinds from `docs/TRANSLATION_OUTPUT.md` §4.
public enum ProtectedTokenKind: String, Sendable, Equatable, CaseIterable {
/// `https://…`, `http://…`, `www.…`
case url
/// `name@example.com`
case email
/// `{{name}}`, `{{ name }}`
case mustache
/// `${name}`
case templateLiteral
/// `%s`, `%d`, `%1$@`, `%02d`
case printf
/// `` `code` ``
case codeSpan
/// A fenced code block.
case fencedCode
/// `<a href="…">`, `</div>`
case htmlTag
/// A quoted JSON key followed by `:`.
case jsonKey
/// `/Users/…`, `C:\…`
case filePath
}
@@ -0,0 +1,91 @@
import Foundation
/// Finds URLs, e-mail addresses, placeholders, code spans, HTML tags, JSON keys and paths that
/// must survive translation (`docs/TRANSLATION_OUTPUT.md` §4).
public struct ProtectedTokenScanner: Sendable {
private struct Rule {
let kind: ProtectedTokenKind
let regex: NSRegularExpression
let group: Int
}
private static let rules: [Rule] = {
func rule(
_ kind: ProtectedTokenKind,
_ pattern: String,
group: Int = 0,
options: NSRegularExpression.Options = []
) -> Rule? {
guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else {
return nil
}
return Rule(kind: kind, regex: regex, group: group)
}
let rules: [Rule?] = [
rule(.fencedCode, "```[\\s\\S]*?```"),
rule(.codeSpan, "`[^`\\n]+`"),
rule(.htmlTag, "</?[A-Za-z][^>\\n]*>"),
rule(.url, "(?:https?://|www\\.)[^\\s<>\"']+"),
rule(.email, "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"),
rule(.mustache, "\\{\\{\\s*[^{}\\n]+\\s*\\}\\}"),
rule(.templateLiteral, "\\$\\{[^{}\\n]+\\}"),
rule(.printf, "%(?:\\d+\\$)?[-+0#]*\\d*(?:\\.\\d+)?[sd@]"),
rule(.jsonKey, "(\"(?:[^\"\\\\]|\\\\.)*\")\\s*:", group: 1),
rule(.filePath, "(?:/(?:Users|home|var|usr|opt|tmp)/[^\\s,;:\"'<>]+|[A-Za-z]:\\\\[^\\s,;:\"'<>]+)"),
]
return rules.compactMap(\.self)
}()
/// Creates a scanner.
public init() {}
/// Scans `text` and returns the protected tokens in source order, without duplicates.
public func scan(_ text: String) -> [ProtectedToken] {
let nsText = text as NSString
let fullRange = NSRange(location: 0, length: nsText.length)
var occupied: [NSRange] = []
var tokens: [(range: NSRange, token: ProtectedToken)] = []
for rule in Self.rules {
for match in rule.regex.matches(in: text, options: [], range: fullRange) {
let range = match.range(at: rule.group)
guard range.location != NSNotFound else { continue }
if occupied.contains(where: { NSIntersectionRange($0, range).length > 0 }) {
continue
}
var value = nsText.substring(with: range)
if rule.kind == .url {
value = trimURLTail(value)
if value.count < 4 {
continue
}
}
let token = ProtectedToken(kind: rule.kind, value: value)
if tokens.contains(where: { $0.token == token }) {
continue
}
tokens.append((range, token))
occupied.append(range)
}
}
return tokens.sorted { $0.range.location < $1.range.location }.map(\.token)
}
/// Removes sentence punctuation that a URL pattern may have swallowed. A balanced closing
/// parenthesis is kept, so Wikipedia-style URLs remain intact.
private func trimURLTail(_ value: String) -> String {
var result = value
while let last = result.last, ".,;:!?".contains(last) {
result.removeLast()
}
while let last = result.last, ")]}".contains(last) {
let open: Character = last == ")" ? "(" : (last == "]" ? "[" : "{")
let opens = result.filter { $0 == open }.count
let closes = result.filter { $0 == last }.count
guard closes > opens else { break }
result.removeLast()
}
return result
}
}
@@ -0,0 +1,16 @@
/// One chunk of a translation, with the separator that followed it in the source.
public struct TextChunk: Sendable, Equatable {
/// The zero-based chunk index.
public let index: Int
/// The chunk text.
public let text: String
/// The source separator after this chunk (`"\n\n"`, `" "` or `""`).
public let separatorAfter: String
/// Creates a chunk.
public init(index: Int, text: String, separatorAfter: String) {
self.index = index
self.text = text
self.separatorAfter = separatorAfter
}
}
@@ -0,0 +1,43 @@
import Foundation
/// Input and output normalisation from `docs/TRANSLATION_OUTPUT.md` §2 and §5.
public enum TextNormalization {
/// N1–N3: line endings to `\n`, strip BOM/NUL/C0 controls (except tab and newline),
/// strip U+200B, keep ZWJ/ZWNJ, NFC, then trim outer whitespace (N2).
public static func normalizeInput(_ text: String) -> String {
let unified = unifyLineEndings(text)
let filtered = unified.unicodeScalars.filter { scalar in
switch scalar.value {
case 0, 0xFEFF, 0x200B:
return false
default:
break
}
if scalar.properties.generalCategory == .control {
return scalar.value == 0x09 || scalar.value == 0x0A
}
return true
}
let cleaned = String(String.UnicodeScalarView(filtered))
return cleaned.precomposedStringWithCanonicalMapping.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// T1: strip NUL, normalise line endings, trim outer whitespace. Internal text is untouched.
public static func normalizeOutput(_ text: String) -> String {
unifyLineEndings(text)
.replacingOccurrences(of: "\0", with: "")
.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// Comparison normalisation for the double-copy rule: line endings and outer trimming only.
/// Internal whitespace is deliberately preserved.
public static func normalizeForComparison(_ text: String) -> String {
unifyLineEndings(text).trimmingCharacters(in: .whitespacesAndNewlines)
}
private static func unifyLineEndings(_ text: String) -> String {
text
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
}
}
@@ -0,0 +1,41 @@
/// Dense-script detection for the chunk limit (`docs/TRANSLATION_OUTPUT.md` §3).
///
/// The limit is script-based, not language-based: one CJK, Arabic, Thai or Indic character is
/// enough to select the smaller limit. Latin, Cyrillic and Greek stay on the larger limit.
public enum TextScript {
private static let denseRanges: [ClosedRange<UInt32>] = [
0x0590 ... 0x05FF, // Hebrew
0x0600 ... 0x06FF, // Arabic
0x0750 ... 0x077F, // Arabic Supplement
0x0900 ... 0x097F, // Devanagari
0x0980 ... 0x09FF, // Bengali
0x0A00 ... 0x0A7F, // Gurmukhi
0x0A80 ... 0x0AFF, // Gujarati
0x0B00 ... 0x0B7F, // Oriya
0x0B80 ... 0x0BFF, // Tamil
0x0C00 ... 0x0C7F, // Telugu
0x0C80 ... 0x0CFF, // Kannada
0x0D00 ... 0x0D7F, // Malayalam
0x0D80 ... 0x0DFF, // Sinhala
0x0E00 ... 0x0E7F, // Thai
0x0E80 ... 0x0EFF, // Lao
0x0F00 ... 0x0FFF, // Tibetan
0x1000 ... 0x109F, // Myanmar
0x1200 ... 0x137F, // Ethiopic
0x1780 ... 0x17FF, // Khmer
0x1800 ... 0x18AF, // Mongolian
0x2E80 ... 0x9FFF, // CJK, Hiragana, Katakana and Hangul compatibility
0xA960 ... 0xA97F, // Hangul Jamo Extended-A
0xAC00 ... 0xD7AF, // Hangul syllables
0xF900 ... 0xFAFF, // CJK compatibility ideographs
0xFE30 ... 0xFE4F, // CJK compatibility forms
0xFF66 ... 0xFFDC, // Half-width Katakana and Hangul
]
/// True when `text` contains at least one dense-script scalar.
public static func isDense(_ text: String) -> Bool {
text.unicodeScalars.contains { scalar in
denseRanges.contains { $0.contains(scalar.value) }
}
}
}
@@ -0,0 +1,33 @@
import Foundation
import SprachmittlerCore
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 makeRegistry() -> AdapterRegistry {
AdapterRegistry(adapters: [HyMT3Adapter()])
}
func makePipeline() throws -> TranslationPipeline {
try TranslationPipeline(
chat: makeChatClient(),
registry: makeRegistry()
)
}
}
@@ -0,0 +1,135 @@
import ArgumentParser
import Foundation
import SprachmittlerCore
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 let domain as SprachmittlerError {
writeError(message(for: domain))
throw ExitCode(exitCode(for: domain))
} catch {
writeError("Error: \(error)")
throw ExitCode(1)
}
}
/// 2 = endpoint/usage, 3 = unreachable, 4 = model missing, 1 = other runtime failure.
static func exitCode(for error: SprachmittlerError) -> Int32 {
switch error {
case .endpointRejected, .noAdapter, .emptyText, .textTooLong, .badRequest:
2
case .ollamaUnreachable:
3
case .modelNotInstalled:
4
default:
1
}
}
static func message(for error: SprachmittlerError) -> String {
switch error {
case let .ollamaUnreachable(url):
"Ollama is not reachable at \(url.absoluteString)."
case let .modelNotInstalled(model):
"Model not installed: \(model)"
case let .noAdapter(model):
"No translation adapter for \(model)."
case let .endpointRejected(reason):
"Endpoint rejected: \(message(for: reason))"
default:
genericMessage(for: error)
}
}
private static func genericMessage(for error: SprachmittlerError) -> String {
switch error {
case .emptyText:
"No text to translate."
case let .textTooLong(characters, limit):
"Text is too long (\(characters) characters; limit \(limit))."
case let .timeout(phase):
"Timed out while talking to Ollama (\(phase))."
case let .server(status, _):
"Ollama returned HTTP \(status)."
case .badRequest:
"Ollama rejected the request."
case .cancelled:
"Cancelled."
default:
"Translation failed."
}
}
/// 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
}
}
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff. Show more