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.
This commit is contained in:
1 parent
26b493e7e5
commit
64078e2f04
80 files changed
+4090
-325
No files matched your search
@@ -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,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
|
||||
Reference in new issue
Block a user