Cotton code
478 lines · 20.1 KB · SwiftRaw
// One dictation or one spoken command, start to end:////   voice.plan → run the live engine → voice.heard (live) for every partial//   and final → at each utterance's end, the second engine re-reads that//   utterance's audio → voice.heard (second) → the core's edits applied;//   voice.touched whenever the person types or selects in the dictated words;//   voice.end when the person taps the mic again.//// The core's answers are applied in the order the hearings were sent (one// chain of calls, so a late answer never overwrites a newer one), and the// second passes run on a chain of their own so a slow model never holds up// the live words. The audio is in memory only (`VoiceTape`) and is dropped// when the session ends.import CottonKitimport Foundationimport Observationimport os@MainActor@Observablepublic final class VoiceSession {    public enum Phase: Equatable, Sendable {        case idle        /// The plan, the permissions, the model loading.        case preparing        case listening        /// The microphone is closed; the last words and second passes settle.        case settling        case failed(VoiceFailure)    }    public private(set) var phase: Phase = .idle    public private(set) var region = VoiceRegion()    public private(set) var level: Double = 0    public private(set) var plan: VoicePlan?    /// Downloads the plan offered that this phone does not hold: the control    /// offers them, with the core's own words for why and how big.    public private(set) var offers: [VoiceDownload] = []    /// Bumps on every change to ``region``, so a host can observe one value.    public private(set) var revision = 0    public private(set) var timings = VoiceTimings()    /// A command the core answered (command mode): the shell opens it.    public var onCommand: ((VoiceCommand) -> Void)?    /// Run before each plan is asked for (Cotton Dev: a walk's languages).    public var prelude: (@MainActor () async -> Void)?    private let core: any CottonCalling    private let store: VoiceModelStore    private let source: VoiceAudioSource    private let capabilities: any CapabilityAuthority    private let engines: VoiceEngineMaker    private var live: (any LiveVoiceEngine)?    private var second: (any SecondVoiceEngine)?    private var input: (any VoiceAudioInput)?    private var tape = VoiceTape()    private var calls: Task<Void, Never>?    private var passes: Task<Void, Never>?    /// The live engine's hearings, in the order it heard them, and the one    /// reader that applies them.    private var hearings: AsyncStream<VoiceHearing>.Continuation?    private var reader: Task<Void, Never>?    private var waitMs = 0    private var lastSelected: (Int, Int)?    private var started = ContinuousClock.now    private var generation = 0    private static let log = Logger(subsystem: "com.cottondb.voice", category: "session")    public init(        core: any CottonCalling,        store: VoiceModelStore = .current,        source: VoiceAudioSource = .microphone,        capabilities: any CapabilityAuthority = SystemCapabilityAuthority(),        engines: VoiceEngineMaker = .system    ) {        self.core = core        self.store = store        self.source = source        self.capabilities = capabilities        self.engines = engines    }    public var isActive: Bool { phase == .preparing || phase == .listening || phase == .settling }    /// A line the control says: the plan's, else the shell's `voice` set.    public func line(_ key: String, _ fills: [String: String] = [:]) -> String {        if var said = plan?.lines[key] {            for (name, value) in fills { said = said.replacingOccurrences(of: "{\(name)}", with: value) }            return said        }        return VoiceLines.line(key, fills)    }    // MARK: Start    /// Tap: plan, ask, load, listen.    public func start(_ request: VoicePlanRequest) async {        guard !isActive else { return }        generation += 1        let mine = generation        surface = request.surface        commandCarried = false        phase = .preparing        region = VoiceRegion()        offers = []        await prelude?()        timings = VoiceTimings()        revision += 1        do {            let plan = try await core.call(CottonMethod.voicePlan, request, as: VoicePlan.self)            guard mine == generation else { return }            self.plan = plan            // One offer per model (the plan lists each file), its size the sum.            var byModel: [String: VoiceDownload] = [:]            var order: [String] = []            for file in plan.downloads where store.readyNow(file.model) == nil {                if var held = byModel[file.model] {                    held.bytes += file.bytes                    byModel[file.model] = held                } else {                    byModel[file.model] = file                    order.append(file.model)                }            }            offers = order.compactMap { byModel[$0] }            if source == .microphone {                let needs: [DeviceCapability] = VoiceEngineChoice.platformRecognisers.contains(plan.live.engine) ? [.microphone, .speech] : [.microphone]                if case .blocked = await capabilities.gate(needs) { throw VoiceFailure.denied }            }            let language = plan.languages.first            let live = try await engines.live(plan.live, language, plan.vocabulary, store)            try await live.prepare()            guard mine == generation else { live.cancel(); return }            self.live = live            if let choice = plan.second {                // A second pass whose model is absent is offered, never awaited:                // the live words go on alone until it is here.                if let engine = try? await engines.second(choice, language, store) {                    self.second = engine                    Task.detached { try? await engine.prepare() }                }            }            if engines.opensAudioSession { try VoiceAudioSession.open() }            tape = VoiceTape()            let tape = self.tape            let input = engines.input(source)            self.input = input            let (stream, continuation) = AsyncStream<VoiceHearing>.makeStream(bufferingPolicy: .unbounded)            hearings = continuation            reader = Task { [weak self] in                for await hearing in stream {                    self?.heard(hearing, pass: .live, generation: mine)                }            }            try await live.start { hearing in continuation.yield(hearing) }            started = .now            phase = .listening            try input.start({ [weak self] chunk in                tape.append(chunk)                live.feed(chunk)                let level = chunk.level                Task { @MainActor in self?.level = level }            }, ended: { [weak self] in                // A recording that has played to its end is a tap on the mic.                Task { @MainActor in _ = await self?.stop() }            })            Self.log.notice("voice: listening \(plan.live.engine, privacy: .public), second \(plan.second?.engine ?? "none", privacy: .public)")        } catch let failure as VoiceFailure {            fail(failure)        } catch let error as CottonCallError {            fail(.core(error.code))        } catch {            fail(.engineUnavailable(error.localizedDescription))        }    }    private func fail(_ failure: VoiceFailure) {        Self.log.error("voice: failed \(String(describing: failure), privacy: .public)")        teardown()        if case .modelMissing(let model) = failure, let offer = plan?.downloads.first(where: { $0.model == model }) {            if !offers.contains(offer) { offers.insert(offer, at: 0) }        }        phase = .failed(failure)    }    // MARK: What was heard    private func heard(_ hearing: VoiceHearing, pass: VoicePass, generation mine: Int) {        guard mine == generation, let session = plan?.session else { return }        let arrived = ContinuousClock.now        if pass == .live, !hearing.text.isEmpty, timings.firstWordMs == nil {            // Speech to first word: the first word's place in the audio is            // when it was spoken; the audio is fed in real time from `started`.            let spokenAt = started.advanced(by: .milliseconds(hearing.words.first?.startMs ?? hearing.startMs))            timings.firstWordMs = max(0, Self.ms(arrived - spokenAt))        }        let ask = VoiceHeard(            session: session, pass: pass, final: hearing.final, text: hearing.text,            words: hearing.words.isEmpty ? nil : hearing.words,            fromMs: hearing.startMs, toMs: hearing.endMs, language: hearing.language)        let previous = calls        calls = Task { [weak self] in            await previous?.value            guard let self else { return }            do {                let answer = try await self.core.call(CottonMethod.voiceHeard, ask, as: VoiceHeardAnswer.self)                self.take(answer, pass: pass, hearing: hearing, generation: mine)            } catch {                Self.log.error("voice.heard failed: \(String(describing: error), privacy: .public)")            }        }        if pass == .live, hearing.final, second != nil {            secondPass(hearing, generation: mine)        }    }    private func take(_ answer: VoiceHeardAnswer, pass: VoicePass, hearing: VoiceHearing, generation mine: Int) {        guard mine == generation else { return }        region.take(settled: answer.settled, tentative: answer.tentative, later: answer.later, edits: answer.edits)        revision += 1        if let wait = answer.waitMs { waitMs = wait }        if let command = answer.command { carry(command) }        let now = ContinuousClock.now        let spokenEnd = started.advanced(by: .milliseconds(hearing.endMs))        switch pass {        case .live where hearing.final:            timings.liveSettledMs.append(max(0, Self.ms(now - spokenEnd)))        case .second:            timings.secondSettledMs.append(max(0, Self.ms(now - spokenEnd)))            if !region.corrected.isEmpty { timings.corrections += 1 }        default:            break        }    }    /// The utterance's audio, read again by the larger model.    private func secondPass(_ hearing: VoiceHearing, generation mine: Int) {        guard let second else { return }        let tape = self.tape        // A little either side, so a clipped first or last word is whole.        let from = max(0, hearing.startMs - 250)        let to = hearing.endMs + 250        let previous = passes        let wait = waitMs        passes = Task { [weak self] in            await previous?.value            if wait > 0 { try? await Task.sleep(for: .milliseconds(wait)) }            let samples = tape.read(fromMs: from, toMs: to)            guard !samples.isEmpty else { return }            do {                var reread = try await second.transcribe(samples, offsetMs: from)                reread.final = true                guard let self else { return }                self.heard(reread, pass: .second, generation: mine)            } catch {                Self.log.error("voice: second pass failed \(String(describing: error), privacy: .public)")            }        }    }    // MARK: The person's typing    /// The field's dictated region now reads `text`; tell the core the range    /// the person touched.    public func typed(_ text: String) {        guard isActive, let session = plan?.session else { return }        guard let touch = region.typed(text) else { return }        revision += 1        let ask = VoiceTouched(session: session, from: touch.from, to: touch.to, text: touch.text)        let mine = generation        let previous = calls        calls = Task { [weak self] in            await previous?.value            guard let self else { return }            do {                // Answered like voice.heard, with the person's change applied.                let answer = try await self.core.call(CottonMethod.voiceTouched, ask, as: VoiceHeardAnswer.self)                guard mine == self.generation else { return }                self.region.acknowledge(touch)                self.region.take(settled: answer.settled, tentative: answer.tentative, later: answer.later, edits: answer.edits)                self.revision += 1            } catch {                Self.log.error("voice.touched failed: \(String(describing: error), privacy: .public)")            }        }    }    /// The person selected inside the dictated words: that range is theirs.    public func selected(from: Int, to: Int) {        guard isActive, let session = plan?.session, to > from, from < region.display.utf16.count else { return }        // What is shown is what the core will hold when it reads this.        let coreFrom = from        let coreTo = min(to, region.display.utf16.count)        guard coreTo > coreFrom, coreFrom != lastSelected?.0 || coreTo != lastSelected?.1 else { return }        lastSelected = (coreFrom, coreTo)        let ask = VoiceTouched(session: session, from: coreFrom, to: coreTo, text: nil)        let previous = calls        calls = Task { [weak self] in            await previous?.value            _ = try? await self?.core.callJSON(CottonMethod.voiceTouched, ask)        }    }    // MARK: End    /// Tap again: close the microphone, let everything settle, and answer    /// what was written.    @discardableResult    public func stop() async -> String {        guard phase == .listening || phase == .preparing else { return region.display }        let mine = generation        phase = .settling        input?.stop()        input = nil        await live?.finish()        // Every hearing the engine gave is applied before the session ends:        // the stream closes, its reader drains it, then the calls and the        // second passes they queued are awaited.        hearings?.finish()        await reader?.value        await calls?.value        await passes?.value        await calls?.value        guard mine == generation else { return region.display }        if let session = plan?.session,           let ended = try? await core.call(CottonMethod.voiceEnd, VoiceSessionRef(session: session), as: VoiceEnded.self) {            // What was tentative settles as heard.            region.take(settled: ended.text, tentative: "", edits: ended.edits)            revision += 1            if let command = ended.command {                carry(command)            } else if plan?.mode == .command, !commandCarried {                Self.log.notice("voice: command mode ended with no command; text \(ended.text.utf16.count, privacy: .public) units")            }        }        let written = region.display        teardown()        phase = .idle        // Where a walk reads how long each step took.        let t = timings        Self.log.notice("voice-timings surface=\(self.surface, privacy: .public) first_word_ms=\(t.firstWordMs ?? -1, privacy: .public) live_settled_ms=\(t.liveSettledMs.map(String.init).joined(separator: ","), privacy: .public) second_settled_ms=\(t.secondSettledMs.map(String.init).joined(separator: ","), privacy: .public) corrections=\(t.corrections, privacy: .public)")        return written    }    /// The surface the session writes into, for the timings line.    private var surface = ""    /// A command is carried out once a session: the final hearing's answer    /// names it, and voice.end names it again.    private var commandCarried = false    private func carry(_ command: VoiceCommand) {        guard !commandCarried else { return }        commandCarried = true        Self.log.notice("voice: command \(command.kind, privacy: .public) table=\(command.table ?? "-", privacy: .public)")        onCommand?(command)    }    /// Discard: nothing is written.    public func cancel() {        generation += 1        if let session = plan?.session {            let core = self.core            Task { _ = try? await core.callJSON(CottonMethod.voiceEnd, VoiceSessionRef(session: session)) }        }        teardown()        region = VoiceRegion()        revision += 1        phase = .idle    }    /// Clear a failure so the control is idle again.    public func dismiss() {        if case .failed = phase { phase = .idle }    }    /// Fetch an offered model; the next tap uses it.    public func download(_ offer: VoiceDownload) async {        await store.download(offer.model, files: plan?.downloads ?? [offer], mobileData: plan?.mobileData ?? "ask")    }    private func teardown() {        input?.stop()        input = nil        live?.cancel()        live = nil        second = nil        hearings?.finish()        hearings = nil        reader?.cancel()        reader = nil        calls = nil        passes = nil        tape.clear()        level = 0        if engines.opensAudioSession { VoiceAudioSession.close() }    }    private static func ms(_ duration: Duration) -> Int {        let (seconds, attoseconds) = duration.components        return Int(seconds) * 1000 + Int(attoseconds / 1_000_000_000_000_000)    }}/// How a session makes its engines and its audio: the system's, or a test's.public struct VoiceEngineMaker: Sendable {    public var live: @MainActor @Sendable (VoiceEngineChoice, String?, [String], VoiceModelStore) async throws -> any LiveVoiceEngine    public var second: @MainActor @Sendable (VoiceEngineChoice, String?, VoiceModelStore) async throws -> any SecondVoiceEngine    public var input: @MainActor @Sendable (VoiceAudioSource) -> any VoiceAudioInput    public var opensAudioSession: Bool    public init(        live: @escaping @MainActor @Sendable (VoiceEngineChoice, String?, [String], VoiceModelStore) async throws -> any LiveVoiceEngine,        second: @escaping @MainActor @Sendable (VoiceEngineChoice, String?, VoiceModelStore) async throws -> any SecondVoiceEngine,        input: @escaping @MainActor @Sendable (VoiceAudioSource) -> any VoiceAudioInput,        opensAudioSession: Bool    ) {        self.live = live        self.second = second        self.input = input        self.opensAudioSession = opensAudioSession    }    public static let system = VoiceEngineMaker(        live: { choice, language, vocabulary, store in            try await VoiceEngines.live(choice, language: language, vocabulary: vocabulary, store: store)        },        second: { choice, language, store in            try await VoiceEngines.second(choice, language: language, store: store)        },        input: { source in            switch source {            case .microphone: MicrophoneInput()            case .recording(let url): RecordingInput(url: url)            }        },        opensAudioSession: true)}/// Speech-to-word timings for one session, measured where they happen.public struct VoiceTimings: Sendable, Equatable {    /// Speech to the first word on screen.    public var firstWordMs: Int?    /// Utterance end to its live final applied, per utterance.    public var liveSettledMs: [Int] = []    /// Utterance end to its second pass applied, per utterance.    public var secondSettledMs: [Int] = []    /// Second passes that changed settled text.    public var corrections = 0    public init() {}}/// The shell's `voice` lines, with the capture set's older dictation lines/// for the keys they already say.public enum VoiceLines {    public static func line(_ key: String, _ fills: [String: String] = [:]) -> String {        for path in ["control.\(key)", "download.\(key)", "command.\(key)", key] {            let said = ShellLines.line("voice", path, fills)            if said != "voice.\(path)" { return said }        }        let said = "voice.\(key)"        if let older = capture[key] { return ShellLines.line("capture", older, fills) }        return said    }    private static let capture: [String: String] = [        "idle": "dictation.listening",        "listening": "dictation.listening",        "settling": "dictation.finishing",        "no_permission": "voice.denied",        "unavailable": "voice.unavailable",        "on_call": "voice.on_call",        "interrupted": "voice.interrupted",        "empty": "voice.empty",        "no_microphone": "meeting.stage.no_microphone",    ]}