Files
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

78 lines
1.9 KiB
Swift

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
}
}