Open source CapCut alternative.
TypeScript
Wire Gemini Live command session
David Lef0408c60baca
diff --git a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swiftnew file mode 100644index 00000000..ae04d542--- /dev/null+++ b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift@@ -0,0 +1,188 @@+import DonkeyAI+import DonkeyContracts+import DonkeyHarness+import DonkeyRuntime+import Foundation++/// Drives the always-on Gemini Live session for the app: streams text (and+/// optionally audio) into the session, executes the model's tool calls against+/// the Donkey Command Layer, and surfaces anything the model didn't handle with+/// a tool call back to the normal command pipeline.+///+/// Entirely gated by `GeminiLiveConfiguration.enabled`; when disabled, nothing+/// here runs and the existing pipeline is unchanged.+@MainActor+final class GeminiLiveVoiceController {+ private let configuration: GeminiLiveConfiguration+ private let systemInstruction: String+ private let registry: HarnessToolRegistry+ private var session: GeminiLiveSession?+ private var eventTask: Task<Void, Never>?++ /// Invoked for transcripts/requests the model did not satisfy with a tool+ /// call (e.g. a complex request). Wire this to the overlay's submit path.+ var onComplexRequest: ((String) -> Void)?+ /// Invoked after a Command Layer tool runs, with a short status summary, so+ /// the UI can reflect that the model acted.+ var onActed: ((String) -> Void)?+ /// Invoked when optional microphone streaming should start (`true`) or stop+ /// (`false`). Always paired — a `true` is always followed by a `false` when+ /// the session disconnects or stops — so the mic owner never gets stuck on.+ var onAudioStreamingChanged: ((Bool) -> Void)?++ var isEnabled: Bool { configuration.enabled }+ var isAudioEnabled: Bool { configuration.audioEnabled }+ /// True once the session is live and accepting input.+ private(set) var isConnected = false+ private var isAudioStreaming = false++ init(+ configuration: GeminiLiveConfiguration = .fromEnvironment(),+ systemInstruction: String = GeminiLiveVoiceController.defaultSystemInstruction+ ) {+ self.configuration = configuration+ self.systemInstruction = systemInstruction+ let services = HarnessBuiltInToolServices(commandExecutor: DonkeyCommandBackends.makeExecutor())+ self.registry = HarnessToolRegistry(+ tools: BuiltInHarnessToolExecutors.tools(+ descriptors: DonkeyCommandLayer.descriptors,+ services: services+ )+ )+ }++ func start() async {+ guard configuration.enabled, session == nil else { return }+ let session = GeminiLiveSession(+ systemInstruction: systemInstruction,+ connectionProvider: Self.makeConnectionProvider()+ )+ self.session = session+ eventTask = Task { [weak self] in+ for await event in session.events {+ await self?.handle(event)+ }+ }+ do {+ try await session.connect()+ isConnected = true+ updateAudioStreaming()+ } catch {+ await stop()+ }+ }++ func stop() async {+ eventTask?.cancel()+ eventTask = nil+ await session?.close()+ session = nil+ isConnected = false+ updateAudioStreaming()+ }++ /// Drive the mic-owner callback from the single source of truth (connected ++ /// audio enabled), so continuous listening is always torn down on disconnect.+ private func updateAudioStreaming() {+ let shouldStream = isConnected && configuration.audioEnabled+ guard shouldStream != isAudioStreaming else { return }+ isAudioStreaming = shouldStream+ onAudioStreamingChanged?(shouldStream)+ }++ /// Send a typed/spoken text turn (the always-available input).+ func sendText(_ text: String) async {+ guard let session else { return }+ try? await session.sendText(text)+ }++ /// Stream optional microphone audio (resampled to the Live input format).+ func sendAudioFrames(_ samples: [Float], sampleRate: Double) async {+ guard configuration.audioEnabled, let session else { return }+ let pcm16 = GeminiLivePCM.pcm16Mono16k(from: samples, sourceRate: Int(sampleRate))+ guard !pcm16.isEmpty else { return }+ try? await session.sendAudioChunk(pcm16)+ }++ // MARK: - Event handling++ private func handle(_ event: AIRealtimeEvent) async {+ switch event {+ case .connected:+ isConnected = true+ updateAudioStreaming()+ case .toolCalls(let calls):+ await execute(calls)+ case .finalTranscript(let text):+ onComplexRequest?(text)+ case .closed:+ isConnected = false+ updateAudioStreaming()+ default:+ break+ }+ }++ private func execute(_ calls: [AIRealtimeToolCall]) async {+ guard let session else { return }+ var results: [AIRealtimeToolResult] = []+ for call in calls {+ let toolCall = HarnessToolCall(id: call.id, name: call.name, input: call.arguments)+ let result = await registry.execute(+ toolCall,+ taskID: "gemini-live",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appControl, .input, .appLookup]+ )+ onActed?(result.summary)+ // Forward the full execution detail (stdout/stderr/exitCode/reason,+ // plus tool-specific facts) so the model can read output and+ // self-correct on failure. `executor` is internal noise.+ var response = result.metadata+ response.removeValue(forKey: "executor")+ response["status"] = result.status.rawValue+ response["summary"] = result.summary+ // Surface a clarification gate (e.g. music.play asking what to play)+ // so the model asks the user instead of guessing or stalling.+ if result.status == .waitingForUser, let question = result.question {+ response["needsUserInput"] = "true"+ response["question"] = question+ }+ results.append(AIRealtimeToolResult(+ id: call.id,+ name: call.name,+ response: response+ ))+ }+ try? await session.sendToolResults(results)+ }++ // MARK: - Auth++ /// Vertex AI: the backend mints a short-lived OAuth token from its+ /// service-account credentials and returns the websocket endpoint + model+ /// path. Re-invoked on every (re)connect so the token stays fresh.+ private static func makeConnectionProvider() -> @Sendable () async throws -> GeminiLiveConnection {+ return {+ let backend = DonkeyBackendInferenceClient(+ configuration: try DonkeyBackendInferenceConfiguration.fromEnvironment()+ )+ let minted = try await backend.mintLiveConnection()+ guard let url = URL(string: minted.websocketUrl) else {+ throw GeminiLiveError.invalidURL+ }+ return GeminiLiveConnection(url: url, bearerToken: minted.token, model: minted.model)+ }+ }++ // Cross-tool policy only. Each tool's purpose, parameters, examples, and+ // safety constraints live in its registered function declaration (see+ // CommandLayerFunctionDeclarations / DonkeyCommandLayer), not here.+ static let defaultSystemInstruction = """+ You are Donkey, a fast macOS assistant. Act directly and immediately with the \+ registered tools, preferring shell_exec for anything the more specific tools \+ don't cover. Discover before guessing rather than inventing names or values. \+ Read each tool's returned output and retry or adjust on failure. Only look at \+ the screen when a task depends on what is currently visible. Keep replies short.+ """+}diff --git a/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swift b/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swiftindex 44a402a4..842317a7 100644--- a/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swift+++ b/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swift@@ -11,11 +11,15 @@ final class MicrophoneWaveformMeter {private var isRunning = falseprivate var isStarting = falseprivate var isRecordingAudio = false+ private var isContinuousListening = falseprivate var capturedSamples: [Float] = []private var capturedSampleRateHz = 0private var capturedStartedAt: Date?var onLevelsChanged: (([Double]) -> Void)?+ /// Optional streaming hook: mono float32 samples + their sample rate, delivered+ /// per audio buffer. Used to stream microphone audio into a realtime session.+ var onAudioFrames: (([Float], Double) -> Void)?func start() {guard !isRunning, !isStarting else { return }@@ -37,7 +41,24 @@ final class MicrophoneWaveformMeter {}}+ /// Keep the mic engine running continuously so audio frames stream into a+ /// realtime session beyond the voice-capture window. Used when Live audio+ /// input is enabled.+ func startContinuousListening() {+ isContinuousListening = true+ start()+ }++ func stopContinuousListening() {+ isContinuousListening = false+ stop()+ }+func stop() {+ // While continuously listening, ignore UI-driven stops so the always-on+ // audio stream survives the prompt closing. Tear down via+ // `stopContinuousListening()`.+ guard !isContinuousListening else { return }guard isRunning || isStarting || isRecordingAudio || engine != nil else { return }engine?.inputNode.removeTap(onBus: 0)@@ -148,6 +169,12 @@ final class MicrophoneWaveformMeter {capturedSamples.append(contentsOf: samples)}+ private func emitAudioFrames(_ samples: [Float], sampleRate: Double) {+ guard !samples.isEmpty, sampleRate > 0 else { return }++ onAudioFrames?(samples, sampleRate)+ }+private func publishSilence() {levels = Array(repeating: 0.08, count: barCount)publishLevels()@@ -161,10 +188,12 @@ final class MicrophoneWaveformMeter {{ [weak meter] buffer, _ inlet level = Self.normalizedLevel(from: buffer)let samples = Self.monoSamples(from: buffer)+ let sampleRate = buffer.format.sampleRate- Task { @MainActor [weak meter, samples, level] in+ Task { @MainActor [weak meter, samples, level, sampleRate] inmeter?.appendAudioSamples(samples)meter?.append(level)+ meter?.emitAudioFrames(samples, sampleRate: sampleRate)}}}diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swiftindex 59851b28..d65b4f37 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift@@ -62,6 +62,16 @@ final class UserQueryOverlayController {microphoneWaveformMeter.onLevelsChanged = { [weak model] levels inmodel?.updateVoiceWaveformLevels(levels)}+ microphoneWaveformMeter.onAudioFrames = { [weak model] samples, sampleRate in+ model?.streamLiveAudioFrames(samples, sampleRate: sampleRate)+ }+ model.onLiveAudioStreamingChanged = { [weak self] isStreaming in+ if isStreaming {+ self?.microphoneWaveformMeter.startContinuousListening()+ } else {+ self?.microphoneWaveformMeter.stopContinuousListening()+ }+ }}func show() {diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swiftindex 922172b0..65759435 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift@@ -21,11 +21,15 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {@Published private(set) var spawnStates: [UserQuerySpawnState] = []@Published private(set) var selectedSpawnID: String?var agentVisualizationPresenter: ((PointerCoachCursorGuideRequest, String?) -> Void)?+ /// Fired when the Live session's optional audio streaming should start/stop,+ /// so the mic owner can keep the engine running continuously.+ var onLiveAudioStreamingChanged: ((Bool) -> Void)?private let commandHandler: any UserQueryCommandHandlingprivate let taskStore: any UserQueryTaskStoringprivate let followUpResolver: any UserQueryFollowUpResolvingprivate let voiceTranscriber: LocalVoiceTranscriptionAdapter+ private let liveController: GeminiLiveVoiceControllerprivate var updateChecker: any DonkeyUpdateCheckingprivate let documentReviewController: DocumentFormFillReviewWindowControllerprivate let appCatalogRefreshLoop: LocalAppDynamicCatalogRefreshLoop@@ -45,12 +49,14 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {),updateChecker: any DonkeyUpdateChecking = SparkleUpdateController(),documentReviewController: DocumentFormFillReviewWindowController = DocumentFormFillReviewWindowController(),+ liveController: GeminiLiveVoiceController = GeminiLiveVoiceController(),theme: UserQueryTheme = UserQueryOverlayModel.bundledTheme()) {self.commandHandler = commandHandlerself.taskStore = taskStoreself.followUpResolver = followUpResolverself.voiceTranscriber = voiceTranscriber+ self.liveController = liveControllerself.updateChecker = updateCheckerself.documentReviewController = documentReviewControllerself.appCatalogRefreshLoop = LocalAppDynamicCatalogRefreshLoop(@@ -79,6 +85,39 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {SQLiteAgentMemoryStore.shared?.prewarmDefaultLocalItemsInBackground()appCatalogRefreshLoop.start()checkForUpdates()+ startLiveSessionIfEnabled()+ }++ /// Bring up the always-on Gemini Live session. It self-gates on configuration+ /// and only becomes `isConnected` if it can authenticate, so when it is not+ /// configured the existing command pipeline is used unchanged.+ private func startLiveSessionIfEnabled() {+ guard liveController.isEnabled else { return }+ liveController.onComplexRequest = { [weak self] text in+ // Anything the Live model didn't satisfy with a tool call runs through+ // the full local pipeline (never back through Live — no loop).+ self?.runLocalCommand(text, source: .typedPrompt)+ }+ liveController.onActed = { [weak self] summary in+ guard let self else { return }+ self.promptState.leadingSignalLevel = .ready+ self.promptState.promptText = summary+ }+ // Forward start/stop of optional audio streaming to the mic owner. The+ // controller emits a paired false on disconnect/stop, so continuous+ // listening is always torn down.+ liveController.onAudioStreamingChanged = { [weak self] active in+ self?.onLiveAudioStreamingChanged?(active)+ }+ Task { [liveController] in await liveController.start() }+ }++ /// Stream optional microphone audio into the Live session (no-op unless audio+ /// is enabled and the session is connected).+ func streamLiveAudioFrames(_ samples: [Float], sampleRate: Double) {+ Task { [liveController] in+ await liveController.sendAudioFrames(samples, sampleRate: sampleRate)+ }}func activate() {@@ -172,6 +211,32 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}private func submitCommand(_ text: String, source: AppHarnessTurnSource = .typedPrompt) {+ // Gemini Live is the always-on brain when connected: text always goes to+ // it (tool-first). When audio is streaming, a batch voice transcript is+ // redundant — the model already heard it — so drop it.+ if liveController.isConnected {+ if source == .voiceTranscript, liveController.isAudioEnabled {+ clearSubmissionInputs()+ promptState.isActive = false+ promptState.isVoiceInputActive = false+ return+ }+ routeToLiveSession(text)+ return+ }+ runLocalCommand(text, source: source)+ }++ private func routeToLiveSession(_ text: String) {+ clearSubmissionInputs()+ promptState.isActive = false+ promptState.isVoiceInputActive = false+ promptState.leadingSignalLevel = .thinking+ promptState.promptText = "On it"+ Task { [liveController] in await liveController.sendText(text) }+ }++ private func runLocalCommand(_ text: String, source: AppHarnessTurnSource = .typedPrompt) {let candidates = followUpCandidates()let promptFollowUpTarget = promptSubmissionFollowUpTarget()let spawnID: String?diff --git a/apps/Donkey/Sources/DonkeyAI/AIRealtimeSession.swift b/apps/Donkey/Sources/DonkeyAI/AIRealtimeSession.swiftnew file mode 100644index 00000000..ed40dddb--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/AIRealtimeSession.swift@@ -0,0 +1,62 @@+import Foundation++/// A single tool/function call requested by a realtime model.+public struct AIRealtimeToolCall: Equatable, Sendable {+ public var id: String+ public var name: String+ public var arguments: [String: String]++ public init(id: String, name: String, arguments: [String: String]) {+ self.id = id+ self.name = name+ self.arguments = arguments+ }+}++/// The client's response to a realtime tool call.+public struct AIRealtimeToolResult: Equatable, Sendable {+ public var id: String+ public var name: String+ public var response: [String: String]++ public init(id: String, name: String, response: [String: String]) {+ self.id = id+ self.name = name+ self.response = response+ }+}++/// Events streamed up from a realtime session.+public enum AIRealtimeEvent: Equatable, Sendable {+ case connected+ case partialTranscript(String)+ case finalTranscript(String)+ case toolCalls([AIRealtimeToolCall])+ case audioOut(Data)+ /// User barged in; discard any buffered output audio.+ case interrupted+ case generationComplete+ /// Server will close the socket soon; reconnect within `timeLeftMS`.+ case goAway(timeLeftMS: Int)+ /// Opaque handle to resume this session after a reconnect.+ case resumptionHandle(String)+ case closed(reason: String?)+}++/// Transport-agnostic, bidirectional realtime session (parallel to the+/// request/response `AIHTTPClient`; this one is a persistent socket).+public protocol AIRealtimeSession: Sendable {+ /// Ordered stream of events from the session.+ var events: AsyncStream<AIRealtimeEvent> { get }++ func connect() async throws+ /// Stream a chunk of 16kHz mono PCM16 little-endian audio.+ func sendAudioChunk(_ pcm16: Data) async throws+ /// Send a text turn.+ func sendText(_ text: String) async throws+ /// Send a JPEG image (e.g. a screenshot) as in-band visual context.+ func sendImage(_ jpeg: Data) async throws+ /// Reply to one or more tool calls.+ func sendToolResults(_ results: [AIRealtimeToolResult]) async throws+ func close() async+}diff --git a/apps/Donkey/Sources/DonkeyAI/CommandLayerFunctionDeclarations.swift b/apps/Donkey/Sources/DonkeyAI/CommandLayerFunctionDeclarations.swiftnew file mode 100644index 00000000..8988ec37--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/CommandLayerFunctionDeclarations.swift@@ -0,0 +1,40 @@+import DonkeyHarness+import Foundation++/// Maps Donkey Command Layer tool descriptors to Gemini Live function+/// declarations so the always-on session can call them directly.+public enum CommandLayerFunctionDeclarations {+ /// Function declarations for every Command Layer tool.+ public static func declarations() -> [[String: Any]] {+ declarations(from: DonkeyCommandLayer.descriptors)+ }++ public static func declarations(from descriptors: [HarnessToolDescriptor]) -> [[String: Any]] {+ descriptors.map(declaration(from:))+ }++ static func declaration(from descriptor: HarnessToolDescriptor) -> [String: Any] {+ var properties: [String: Any] = [:]+ var required: [String] = []+ let optional = Set(descriptor.optionalInputKeys)+ for (name, description) in descriptor.inputSchema {+ properties[name] = ["type": "string", "description": description]+ // Requiredness comes from the structured descriptor, not prose.+ if !optional.contains(name) {+ required.append(name)+ }+ }+ var parameters: [String: Any] = [+ "type": "object",+ "properties": properties+ ]+ if !required.isEmpty {+ parameters["required"] = required.sorted()+ }+ return [+ "name": descriptor.name,+ "description": descriptor.summary,+ "parameters": parameters+ ]+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swiftindex a9fd929c..cc0a6e7f 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift@@ -120,6 +120,17 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {return try JSONDecoder().decode(RemoteInferenceModelList.self, from: data)}+ /// Mint a short-lived Gemini Live (Vertex AI) connection: an OAuth access+ /// token plus the websocket endpoint and fully-qualified model path. The+ /// long-lived service-account credential stays on the backend.+ public func mintLiveConnection() async throws -> RemoteLiveConnection {+ var request = makeRequest(path: "/api/inference/live-token/")+ request.httpMethod = "POST"+ request.httpBody = Data("{}".utf8)+ let data = try await send(request)+ return try JSONDecoder().decode(RemoteLiveConnection.self, from: data)+ }+public func completeChat(_ completionRequest: RemoteInferenceChatCompletionRequest) async throws -> RemoteInferenceJSONValue {diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swift b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swiftnew file mode 100644index 00000000..bfa660f2--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swift@@ -0,0 +1,59 @@+import Foundation++/// Configuration for the always-on Gemini Live session.+///+/// Gemini Live is the command brain: it always receives text input; audio is an+/// optional second input controlled by `audioEnabled`. The whole feature is gated+/// by `enabled` so the existing text/transcription pipeline is unchanged when it+/// is not configured.+///+/// Authentication is always Vertex AI OAuth: the Donkey backend mints a+/// short-lived access token (and supplies the endpoint + model) via+/// `POST /api/inference/live-token/`. There is no client-held API-key path.+public struct GeminiLiveConfiguration: Equatable, Sendable {+ /// Whether the Gemini Live brain is active at all. When false, callers keep+ /// the existing intent pipeline.+ public var enabled: Bool+ /// Whether microphone audio is streamed into the session (optional input).+ public var audioEnabled: Bool++ public init(enabled: Bool, audioEnabled: Bool = false) {+ self.enabled = enabled+ self.audioEnabled = audioEnabled+ }++ /// Build from environment.+ ///+ /// - `GEMINI_LIVE_ENABLED` (bool) — the always-on Live session, **on by+ /// default**; set to a falsey value to opt out.+ /// - `GEMINI_LIVE_AUDIO` (bool) — also stream microphone audio (optional).+ ///+ /// The model id is owned by the backend (`GEMINI_LIVE_MODEL` there); the+ /// client never selects it.+ public static func fromEnvironment(+ _ environment: [String: String] = ProcessInfo.processInfo.environment+ ) -> GeminiLiveConfiguration {+ GeminiLiveConfiguration(+ enabled: boolValue(environment["GEMINI_LIVE_ENABLED"], default: true),+ audioEnabled: boolValue(environment["GEMINI_LIVE_AUDIO"])+ )+ }++ private static func trimmed(_ value: String?) -> String? {+ let trimmedValue = value?.trimmingCharacters(in: .whitespacesAndNewlines)+ return trimmedValue?.isEmpty == false ? trimmedValue : nil+ }++ private static func boolValue(_ value: String?, default defaultValue: Bool = false) -> Bool {+ switch trimmed(value)?.lowercased() {+ case .none:+ return defaultValue+ case "1", "true", "yes", "on":+ return true+ case "0", "false", "no", "off":+ return false+ default:+ return defaultValue+ }+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiLivePCM.swift b/apps/Donkey/Sources/DonkeyAI/GeminiLivePCM.swiftnew file mode 100644index 00000000..b80c7f68--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/GeminiLivePCM.swift@@ -0,0 +1,35 @@+import Foundation++/// Audio conversion for Gemini Live input: mono float32 samples → raw 16kHz+/// PCM16 little-endian (no WAV header, which is what the Live socket expects).+public enum GeminiLivePCM {+ public static let targetSampleRate = 16_000++ /// Convert mono float32 samples at `sourceRate` to raw 16kHz PCM16 LE.+ public static func pcm16Mono16k(from samples: [Float], sourceRate: Int) -> Data {+ let resampled = resample(samples, sourceRate: sourceRate, targetRate: targetSampleRate)+ var data = Data(capacity: resampled.count * MemoryLayout<Int16>.size)+ for sample in resampled {+ let clamped = min(max(sample, -1), 1)+ var value = Int16(clamped * Float(Int16.max)).littleEndian+ data.append(Data(bytes: &value, count: MemoryLayout<Int16>.size))+ }+ return data+ }++ /// Linear-interpolation resample (matches the local transcription path).+ static func resample(_ samples: [Float], sourceRate: Int, targetRate: Int) -> [Float] {+ guard sourceRate > 0, targetRate > 0, sourceRate != targetRate else { return samples }+ guard samples.count > 1 else { return samples }++ let outputCount = max(1, Int((Double(samples.count) * Double(targetRate) / Double(sourceRate)).rounded()))+ let sourceStep = Double(sourceRate) / Double(targetRate)+ return (0..<outputCount).map { outputIndex in+ let sourcePosition = Double(outputIndex) * sourceStep+ let lowerIndex = min(samples.count - 1, Int(sourcePosition.rounded(.down)))+ let upperIndex = min(samples.count - 1, lowerIndex + 1)+ let fraction = Float(sourcePosition - Double(lowerIndex))+ return samples[lowerIndex] + (samples[upperIndex] - samples[lowerIndex]) * fraction+ }+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiLiveProtocol.swift b/apps/Donkey/Sources/DonkeyAI/GeminiLiveProtocol.swiftnew file mode 100644index 00000000..8944d4bf--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/GeminiLiveProtocol.swift@@ -0,0 +1,183 @@+import Foundation++/// Builders and parsers for the Gemini Live `BidiGenerateContent` websocket+/// protocol. Uses `JSONSerialization` rather than fully-typed Codable because+/// the Live wire schema is still evolving; we build exactly the messages we send+/// and tolerantly parse the fields we care about.+public enum GeminiLiveProtocol {+ /// Audio Gemini Live expects on input: 16kHz mono PCM16 little-endian.+ public static let inputAudioMimeType = "audio/pcm;rate=16000"+ public static let imageMimeType = "image/jpeg"++ // MARK: - Outbound messages++ /// First message: declares model, modalities, tools, and session policies.+ public static func setupMessage(+ model: String,+ systemInstruction: String,+ functionDeclarations: [[String: Any]],+ includeAudioResponse: Bool,+ resumptionHandle: String?+ ) -> Data {+ // Vertex passes a fully-qualified `projects/.../models/...` path; the+ // Developer API wants a bare id prefixed with `models/`.+ let modelName = model.contains("/") ? model : "models/\(model)"+ var setup: [String: Any] = [+ "model": modelName,+ "generationConfig": [+ "responseModalities": includeAudioResponse ? ["AUDIO"] : ["TEXT"]+ ],+ "systemInstruction": ["parts": [["text": systemInstruction]]],+ // Keep long sessions alive past the hard duration limits.+ "contextWindowCompression": ["slidingWindow": [:]],+ // Always request transcripts so text input/output stay observable.+ "inputAudioTranscription": [:],+ "outputAudioTranscription": [:]+ ]+ if !functionDeclarations.isEmpty {+ setup["tools"] = [["functionDeclarations": functionDeclarations]]+ }+ var resumption: [String: Any] = [:]+ if let resumptionHandle, !resumptionHandle.isEmpty {+ resumption["handle"] = resumptionHandle+ }+ setup["sessionResumption"] = resumption+ return encode(["setup": setup])+ }++ /// A text turn from the user.+ public static func clientTextMessage(_ text: String) -> Data {+ encode([+ "clientContent": [+ "turns": [["role": "user", "parts": [["text": text]]]],+ "turnComplete": true+ ]+ ])+ }++ /// A streamed media chunk (audio or image) as realtime input.+ public static func realtimeMediaMessage(base64Data: String, mimeType: String) -> Data {+ encode([+ "realtimeInput": [+ "mediaChunks": [["mimeType": mimeType, "data": base64Data]]+ ]+ ])+ }++ /// Responses to one or more tool calls.+ public static func toolResponseMessage(_ results: [AIRealtimeToolResult]) -> Data {+ let functionResponses = results.map { result -> [String: Any] in+ [+ "id": result.id,+ "name": result.name,+ "response": result.response+ ]+ }+ return encode(["toolResponse": ["functionResponses": functionResponses]])+ }++ // MARK: - Inbound parsing++ /// Parse a server frame into zero or more realtime events.+ public static func parseServerEvents(_ data: Data) -> [AIRealtimeEvent] {+ guard let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {+ return []+ }+ var events: [AIRealtimeEvent] = []++ if root["setupComplete"] != nil {+ events.append(.connected)+ }++ if let toolCall = root["toolCall"] as? [String: Any],+ let functionCalls = toolCall["functionCalls"] as? [[String: Any]] {+ let calls = functionCalls.compactMap { call -> AIRealtimeToolCall? in+ guard let name = call["name"] as? String else { return nil }+ let id = (call["id"] as? String) ?? name+ let args = (call["args"] as? [String: Any]) ?? [:]+ return AIRealtimeToolCall(id: id, name: name, arguments: stringifyArguments(args))+ }+ if !calls.isEmpty {+ events.append(.toolCalls(calls))+ }+ }++ if let serverContent = root["serverContent"] as? [String: Any] {+ if (serverContent["interrupted"] as? Bool) == true {+ events.append(.interrupted)+ }+ if let inputTranscription = serverContent["inputTranscription"] as? [String: Any],+ let text = inputTranscription["text"] as? String, !text.isEmpty {+ events.append(.partialTranscript(text))+ }+ if let modelTurn = serverContent["modelTurn"] as? [String: Any],+ let parts = modelTurn["parts"] as? [[String: Any]] {+ for part in parts {+ if let inlineData = part["inlineData"] as? [String: Any],+ let base64 = inlineData["data"] as? String,+ let audio = Data(base64Encoded: base64) {+ events.append(.audioOut(audio))+ }+ }+ }+ if (serverContent["generationComplete"] as? Bool) == true {+ events.append(.generationComplete)+ }+ if (serverContent["turnComplete"] as? Bool) == true {+ if let outputTranscription = serverContent["outputTranscription"] as? [String: Any],+ let text = outputTranscription["text"] as? String, !text.isEmpty {+ events.append(.finalTranscript(text))+ }+ }+ }++ if let resumptionUpdate = root["sessionResumptionUpdate"] as? [String: Any],+ let handle = resumptionUpdate["newHandle"] as? String, !handle.isEmpty {+ events.append(.resumptionHandle(handle))+ }++ if let goAway = root["goAway"] as? [String: Any] {+ events.append(.goAway(timeLeftMS: durationMS(goAway["timeLeft"])))+ }++ return events+ }++ // MARK: - Helpers++ private static func stringifyArguments(_ args: [String: Any]) -> [String: String] {+ var result: [String: String] = [:]+ for (key, value) in args {+ switch value {+ case let string as String:+ result[key] = string+ case let bool as Bool:+ result[key] = bool ? "true" : "false"+ case let number as NSNumber:+ result[key] = number.stringValue+ default:+ if let data = try? JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed]),+ let string = String(data: data, encoding: .utf8) {+ result[key] = string+ }+ }+ }+ return result+ }++ /// Parse Live duration values, which arrive as `"5s"` strings or numbers.+ private static func durationMS(_ value: Any?) -> Int {+ if let number = value as? NSNumber {+ return Int(number.doubleValue * 1000)+ }+ if let string = value as? String {+ let seconds = Double(string.replacingOccurrences(of: "s", with: "")) ?? 0+ return Int(seconds * 1000)+ }+ return 0+ }++ private static func encode(_ object: [String: Any]) -> Data {+ (try? JSONSerialization.data(withJSONObject: object)) ?? Data()+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiLiveSession.swift b/apps/Donkey/Sources/DonkeyAI/GeminiLiveSession.swiftnew file mode 100644index 00000000..19552234--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/GeminiLiveSession.swift@@ -0,0 +1,217 @@+import DonkeyHarness+import Foundation++public enum GeminiLiveError: Error, Equatable, Sendable {+ case invalidURL+ case notConnected+ case missingAuthToken+}++/// Everything needed to open one Gemini Live websocket: the endpoint URL (with+/// any auth query param already applied), an optional OAuth bearer token, and the+/// model id/path. Built per-connect so OAuth tokens stay fresh across reconnects.+public struct GeminiLiveConnection: Equatable, Sendable {+ public var url: URL+ public var bearerToken: String?+ public var model: String++ public init(url: URL, bearerToken: String?, model: String) {+ self.url = url+ self.bearerToken = bearerToken+ self.model = model+ }+}++/// Decoded response from the backend `POST /api/inference/live-token/` route.+public struct RemoteLiveConnection: Codable, Equatable, Sendable {+ public var token: String+ public var websocketUrl: String+ public var model: String+ public var expiresAt: String?+ public var project: String?+ public var location: String?+}++/// Always-on Gemini Live session over `URLSessionWebSocketTask`.+///+/// Connects directly to Google. Text input is always available; audio/image are+/// optional streamed inputs. Tool calls surface as `AIRealtimeEvent.toolCalls`+/// for the controller to execute against the Command Layer. Handles session+/// resumption and `goAway`-driven reconnects transparently.+public actor GeminiLiveSession: AIRealtimeSession {+ public nonisolated let events: AsyncStream<AIRealtimeEvent>+ private let continuation: AsyncStream<AIRealtimeEvent>.Continuation++ private let systemInstruction: String+ private let functionDescriptors: [HarnessToolDescriptor]+ private let connectionProvider: @Sendable () async throws -> GeminiLiveConnection+ private let urlSession: URLSession++ private var task: URLSessionWebSocketTask?+ private var resumptionHandle: String?+ private var isClosed = false+ private var generation = 0+ private var isReconnecting = false+ private var reconnectAttempts = 0+ private static let maxReconnectAttempts = 6++ public init(+ systemInstruction: String,+ functionDescriptors: [HarnessToolDescriptor] = DonkeyCommandLayer.descriptors,+ connectionProvider: @escaping @Sendable () async throws -> GeminiLiveConnection,+ urlSession: URLSession = .shared+ ) {+ self.systemInstruction = systemInstruction+ self.functionDescriptors = functionDescriptors+ self.connectionProvider = connectionProvider+ self.urlSession = urlSession+ (events, continuation) = AsyncStream<AIRealtimeEvent>.makeStream()+ }++ public func connect() async throws {+ isClosed = false+ try await openSocket()+ }++ public func sendText(_ text: String) async throws {+ try await send(GeminiLiveProtocol.clientTextMessage(text))+ }++ public func sendAudioChunk(_ pcm16: Data) async throws {+ try await send(GeminiLiveProtocol.realtimeMediaMessage(+ base64Data: pcm16.base64EncodedString(),+ mimeType: GeminiLiveProtocol.inputAudioMimeType+ ))+ }++ public func sendImage(_ jpeg: Data) async throws {+ try await send(GeminiLiveProtocol.realtimeMediaMessage(+ base64Data: jpeg.base64EncodedString(),+ mimeType: GeminiLiveProtocol.imageMimeType+ ))+ }++ public func sendToolResults(_ results: [AIRealtimeToolResult]) async throws {+ try await send(GeminiLiveProtocol.toolResponseMessage(results))+ }++ public func close() async {+ isClosed = true+ task?.cancel(with: .goingAway, reason: nil)+ task = nil+ continuation.yield(.closed(reason: nil))+ continuation.finish()+ }++ // MARK: - Connection lifecycle++ private func openSocket() async throws {+ guard !isClosed else { throw GeminiLiveError.notConnected }+ // Built fresh each connect so OAuth tokens stay valid across reconnects.+ let connection = try await connectionProvider()+ guard !isClosed else { throw GeminiLiveError.notConnected }++ var request = URLRequest(url: connection.url)+ if let bearer = connection.bearerToken, !bearer.isEmpty {+ request.setValue("Bearer \(bearer)", forHTTPHeaderField: "Authorization")+ }++ // Tear down any prior socket before replacing it so it can't leak or+ // keep a half-open connection alive.+ task?.cancel(with: .goingAway, reason: nil)++ generation += 1+ let myGeneration = generation+ let socket = urlSession.webSocketTask(with: request)+ task = socket+ socket.resume()++ let setup = GeminiLiveProtocol.setupMessage(+ model: connection.model,+ systemInstruction: systemInstruction,+ functionDeclarations: CommandLayerFunctionDeclarations.declarations(from: functionDescriptors),+ includeAudioResponse: false,+ resumptionHandle: resumptionHandle+ )+ try await socket.send(.data(setup))++ Task { [weak self] in await self?.receiveLoop(generation: myGeneration) }+ }++ private func receiveLoop(generation myGeneration: Int) async {+ while !isClosed, generation == myGeneration, let socket = task {+ do {+ let message = try await socket.receive()+ let data: Data+ switch message {+ case .data(let payload):+ data = payload+ case .string(let text):+ data = Data(text.utf8)+ @unknown default:+ continue+ }+ for event in GeminiLiveProtocol.parseServerEvents(data) {+ handle(event)+ }+ } catch {+ if !isClosed, generation == myGeneration {+ await handleDisconnect(reason: error.localizedDescription)+ }+ return+ }+ }+ }++ private func handle(_ event: AIRealtimeEvent) {+ switch event {+ case .connected:+ // A successful handshake clears the reconnect backoff.+ reconnectAttempts = 0+ case .resumptionHandle(let handle):+ resumptionHandle = handle+ case .goAway:+ Task { [weak self] in await self?.handleDisconnect(reason: "goAway") }+ default:+ break+ }+ continuation.yield(event)+ }++ /// Reconnect transparently with exponential backoff, reusing the stored+ /// resumption handle. A single reconnect runs at a time; after a bounded+ /// number of failed attempts the session closes instead of looping forever.+ private func handleDisconnect(reason: String) async {+ guard !isClosed, !isReconnecting else { return }+ isReconnecting = true+ defer { isReconnecting = false }++ while !isClosed {+ if reconnectAttempts >= Self.maxReconnectAttempts {+ isClosed = true+ continuation.yield(.closed(reason: "reconnect limit reached after \(reason)"))+ continuation.finish()+ return+ }+ try? await Task.sleep(nanoseconds: Self.reconnectDelayNanoseconds(attempt: reconnectAttempts))+ reconnectAttempts += 1+ guard !isClosed else { return }+ do {+ try await openSocket()+ return // connected; reconnectAttempts resets when `.connected` arrives+ } catch {+ continue // back off and retry+ }+ }+ }++ private static func reconnectDelayNanoseconds(attempt: Int) -> UInt64 {+ let seconds = min(0.5 * pow(2.0, Double(attempt)), 30.0) + Double.random(in: 0...0.3)+ return UInt64(seconds * 1_000_000_000)+ }++ private func send(_ data: Data) async throws {+ guard let socket = task else { throw GeminiLiveError.notConnected }+ try await socket.send(.data(data))+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swiftnew file mode 100644index 00000000..72855025--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift@@ -0,0 +1,118 @@+import DonkeyAI+import DonkeyHarness+import Foundation+import Testing++@Suite+struct GeminiLiveTests {+ @Test+ func configurationParsesEnvironment() {+ // Live is on by default with no env set; audio off.+ let defaults = GeminiLiveConfiguration.fromEnvironment([:])+ #expect(defaults.enabled)+ #expect(defaults.audioEnabled == false)++ // Explicit opt-out.+ let disabled = GeminiLiveConfiguration.fromEnvironment(["GEMINI_LIVE_ENABLED": "false"])+ #expect(disabled.enabled == false)++ // Optional audio opt-in.+ let withAudio = GeminiLiveConfiguration.fromEnvironment(["GEMINI_LIVE_AUDIO": "true"])+ #expect(withAudio.enabled)+ #expect(withAudio.audioEnabled)+ }++ @Test+ func functionDeclarationsCoverCommandLayerAndInferRequired() {+ let declarations = CommandLayerFunctionDeclarations.declarations()+ #expect(declarations.count == DonkeyCommandLayer.Command.allCases.count)++ let names = Set(declarations.compactMap { $0["name"] as? String })+ for command in DonkeyCommandLayer.Command.allCases {+ #expect(names.contains(command.rawValue))+ }++ // music.play has a required `query` and an optional `app`.+ let music = declarations.first { ($0["name"] as? String) == "music.play" }+ let parameters = music?["parameters"] as? [String: Any]+ let required = parameters?["required"] as? [String] ?? []+ #expect(required.contains("query"))+ #expect(!required.contains("app"))+ }++ @Test+ func pcm16ResamplesAndPacksLittleEndian() {+ // 48kHz → 16kHz is a 3:1 decimation.+ let samples = Array(repeating: Float(0), count: 480)+ let data = GeminiLivePCM.pcm16Mono16k(from: samples, sourceRate: 48_000)+ // ~160 output samples * 2 bytes each.+ #expect(data.count == 160 * MemoryLayout<Int16>.size)++ // Full-scale sample clamps to Int16.max (0xFF7F little-endian for 32767).+ let loud = GeminiLivePCM.pcm16Mono16k(from: [1.0, 1.0], sourceRate: 16_000)+ #expect(loud.count == 2 * MemoryLayout<Int16>.size)+ #expect(loud[0] == 0xFF)+ #expect(loud[1] == 0x7F)+ }++ @Test+ func parsesToolCallAndSetupCompleteFrames() {+ let setup = Data(#"{"setupComplete":{}}"#.utf8)+ #expect(GeminiLiveProtocol.parseServerEvents(setup) == [.connected])++ let toolCall = Data(#"""+ {"toolCall":{"functionCalls":[{"id":"c1","name":"app.open","args":{"app":"Spotify"}}]}}+ """#.utf8)+ let events = GeminiLiveProtocol.parseServerEvents(toolCall)+ #expect(events == [.toolCalls([+ AIRealtimeToolCall(id: "c1", name: "app.open", arguments: ["app": "Spotify"])+ ])])+ }++ @Test+ func setupMessageDoesNotDoublePrefixVertexModelPath() {+ let vertexModel = "projects/p/locations/global/publishers/google/models/gemini-2.0-flash-live-001"+ let data = GeminiLiveProtocol.setupMessage(+ model: vertexModel,+ systemInstruction: "be fast",+ functionDeclarations: [],+ includeAudioResponse: false,+ resumptionHandle: nil+ )+ let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]+ let setup = root?["setup"] as? [String: Any]+ #expect((setup?["model"] as? String) == vertexModel)+ }++ @Test+ func decodesBackendLiveConnection() throws {+ let json = Data(#"""+ {"token":"ya29.tok","websocketUrl":"wss://aiplatform.googleapis.com/ws/x",+ "model":"projects/p/locations/global/publishers/google/models/m",+ "expiresAt":"2026-01-01T00:00:00Z","project":"p","location":"global"}+ """#.utf8)+ let connection = try JSONDecoder().decode(RemoteLiveConnection.self, from: json)+ #expect(connection.token == "ya29.tok")+ #expect(connection.websocketUrl == "wss://aiplatform.googleapis.com/ws/x")+ #expect(connection.model.hasSuffix("/models/m"))+ }++ @Test+ func buildsSetupMessageWithToolsAndSessionPolicies() {+ let data = GeminiLiveProtocol.setupMessage(+ model: "gemini-test-live",+ systemInstruction: "be fast",+ functionDeclarations: CommandLayerFunctionDeclarations.declarations(),+ includeAudioResponse: false,+ resumptionHandle: nil+ )+ let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]+ let setup = root?["setup"] as? [String: Any]+ #expect((setup?["model"] as? String) == "models/gemini-test-live")+ #expect(setup?["contextWindowCompression"] != nil)+ #expect(setup?["sessionResumption"] != nil)+ let tools = setup?["tools"] as? [[String: Any]]+ let declarations = tools?.first?["functionDeclarations"] as? [[String: Any]]+ #expect((declarations?.count ?? 0) == DonkeyCommandLayer.Command.allCases.count)+ }+}diff --git a/apps/Donkey/docs/fast-command-layer-and-gemini-live.md b/apps/Donkey/docs/fast-command-layer-and-gemini-live.mdnew file mode 100644index 00000000..e4cfeb52--- /dev/null+++ b/apps/Donkey/docs/fast-command-layer-and-gemini-live.md@@ -0,0 +1,167 @@+# Fast Donkey: tool-first Command Layer + always-on Gemini Live++> **Status: implemented end to end.** Command Layer (Phase 1) and the always-on Gemini Live+> session (Phase 2) are built, unit-tested, and wired into the overlay. The backend mints+> short-lived Vertex AI OAuth tokens (`POST /api/inference/live-token/`), the client connects+> directly to the Vertex Live websocket with a Bearer token, text/audio route through the session,+> tool calls execute against the Command Layer, and the mic can stream continuously. Gemini Live is **enabled by default** and takes over once it+> connects; if it can't authenticate it stays disconnected and the existing pipeline runs+> unchanged. Remaining work is live end-to-end verification with real credentials + mic.++## Context++Donkey is text-first, but slow to *act*. Historically it could only act two ways: generate+AppleScript (a second model round-trip) or fall into a vision loop that screenshots and+re-prompts every turn with a fixed 1.2s sleep (`UserQueryCommandHandler.swift:727`, `:805`).+There was no fast "just do it" substrate — no `open`, no native command.++The goal: **tool-first, screen-last.** Give the model a set of fast, deterministic native tools,+and let an always-on Gemini Live session drive them from text (audio optional), only looking at+the screen when a task genuinely needs visible state.++```+text (always) ─┐+audio (optional) ─┤→ Gemini Live session ──tool call──▶ Command Layer ──result──▶ back to Live+screenshot (only when needed) ─┘ (fast, native, in-process; no screenshot/AX)+```++## Phase 1 — Command Layer++Fast native, in-process tools the model calls directly. Under ~500ms, no screenshot, no AX tree.+A deliberately small set:++| Tool | Implementation |+|---|---|+| `shell_exec` | runs a safe, single-line shell command via `/bin/zsh -c` and returns its output — the primary, general-purpose tool |+| `apps.list` | reuses `MacLocalAppAvailabilityProvider.installedApplications()` (Spotlight-backed, names + bundle ids) + running apps so the model targets exact names instead of guessing |+| `music.play` | reuses the bundled, pre-validated `music-media` `play-media-by-search.applescript` (a multi-step search→play workflow a one-liner can't reproduce) |++`shell_exec` is the **primary, general-purpose tool** (the same capability the competitor's+Realtime setup exposes) — listed first and prioritized in the system instruction. It handles most+requests directly: opening/quitting/controlling apps (`open -a Spotify`, `osascript -e '…'`),+changing settings, opening URLs (`open https://…`), and reading system state. Earlier dedicated+tools (`app.open`, `app.quit`, `browser.open_url`, `system.set_volume`) were **removed** as+redundant once `shell_exec` could do them reliably; only the two that earn their keep remain —+`apps.list` (discovery is awkward via raw shell) and `music.play` (encapsulated workflow). The+model is told to send only safe single-line commands; a backstop guardrail in+`DonkeyCommandBackends` enforces single-line input, a length cap, and a hard ~12s timeout+(SIGTERM→SIGKILL). Unsafe commands are caught by a **command-word** check on each pipeline/segment+leading executable (so bare `rm`, `/bin/rm`, or a denied command inside `$(…)` is caught) plus a+short list of dangerous substrings (`do shell script`, `| sh`, redirects to `/dev`/`/system`/…) —+chosen over the earlier substring denylist, which both missed bare destructive commands and+false-positived on benign redirects.++Tool results are returned to the Live model in full — `status`, `summary`, the execution metadata+(`stdout`, `stderr`, `exitCode`, `reason`), and any clarification `question` — so it can read+output and self-correct, or ask the user when a tool needs input.++**Where it lives / how it's wired.** `DonkeyHarness` only depends on `DonkeyContracts` and can't+import AppKit, so it follows the codebase's existing injected-closure pattern (like+`appleScriptExecutor`):++- `DonkeyHarness/DonkeyCommandLayer.swift` — tool descriptors + the shared `Command` enum+ (single source of truth for the command names).+- `DonkeyRuntime/DonkeyCommandBackends.swift` — the native side effects.+- Injected via a new `HarnessBuiltInToolServices.commandExecutor` closure, wired in+ `LocalAppUserQueryHarnessServices.builtInSkillBackedServices()`.+- Dispatched from the `default` branch of `BuiltInHarnessToolExecutors.execute` (before+ `unknownTool`), and merged into `BuiltInHarnessToolCatalog.descriptors` so the tools surface to+ the model automatically (they're `.reversible`/`.guardedInput`, so the planner's tool-name+ filter keeps them).++This removes the AppleScript-generation hop and the vision loop for common commands.++## Phase 2 — Always-on Gemini Live session++A single Live session is the command brain. **Text input is always available; audio is an+optional second input** (the existing `MicrophoneWaveformMeter` gained an additive+`onAudioFrames` hook). Tool calls map to the Command Layer; screenshots are sent in-band only+when a task needs visible state.++Files (`DonkeyAI/` unless noted):++- `AIRealtimeSession.swift` — transport-agnostic protocol + event model (parallel to the+ request/response `AIHTTPClient`; this one is a persistent socket).+- `GeminiLiveSession.swift` — `URLSessionWebSocketTask` actor: setup advertising the Command+ Layer tools, context-window compression, session resumption, and transparent `goAway`/drop+ reconnect.+- `GeminiLiveProtocol.swift` — `JSONSerialization`-based message builders + tolerant event parser+ for the `BidiGenerateContent` wire format.+- `CommandLayerFunctionDeclarations.swift` — maps `HarnessToolDescriptor` → Gemini function+ declarations.+- `GeminiLivePCM.swift` — mono float32 → raw 16kHz PCM16 LE (Live's input format).+- `GeminiLiveConfiguration.swift` — env config (below).+- `Donkey/GeminiLiveVoiceController.swift` — owns the session, runs the tool-call loop against a+ Command Layer `HarnessToolRegistry`, and routes anything the model didn't tool-call back to the+ normal pipeline via `onComplexRequest`.++### Routing decision — no string matching++Per requirement, the execution path is **always the model's decision**. There is no phrase table+or deterministic prefilter: the Live model chooses a tool call (act now) vs. asking for the screen+(visual task) vs. a plain reply. The speedup comes from the model *preferring* a fast tool, not+from bypassing it.++### Authentication — Vertex OAuth only++The backend authenticates to **Vertex AI with Google Cloud OAuth (service-account) credentials**,+and the Live client uses the same. There is no client-held API-key path. `GeminiLiveSession`'s+connection provider calls `DonkeyBackendInferenceClient.mintLiveConnection()` →+`POST /api/inference/live-token/`. The backend route (`site/src/app/api/inference/live-token/route.ts`)+uses the shared service-account JWT (`site/src/lib/inference/vertex-live.ts`, `cloud-platform`+scope) to mint a short-lived access token and returns it with the Vertex Live websocket URL+(`{location}-aiplatform.googleapis.com`, or `aiplatform.googleapis.com` for `global`) and the+fully-qualified model path. The client connects with `Authorization: Bearer <token>`; the+long-lived credential never leaves the backend, and the token is re-minted on every (re)connect so+it stays fresh. The result is carried in a single `GeminiLiveConnection` (url + bearer + model).++### Configuration++| Variable | Where | Meaning |+|---|---|---|+| `GEMINI_LIVE_ENABLED` | client | Always-on Live session. **On by default**; set falsey to opt out. |+| `GEMINI_LIVE_AUDIO` | client | Also stream microphone audio (optional). Off by default. |+| `GEMINI_LIVE_MODEL` | backend | Live model id (default `gemini-3.1-flash-live-preview`). Owned solely by the backend — the single source of truth. |+| `GOOGLE_APPLICATION_CREDENTIALS_JSON` | backend | Vertex service-account JSON used to mint tokens. |+| `GEMINI_VERTEX_LOCATION` | backend | Vertex location (default `global`). |++## How the overlay is wired++`UserQueryOverlayModel` owns a `GeminiLiveVoiceController`, started on init (gated by+`isEnabled`). `submitCommand` routes through the session whenever `liveController.isConnected`:+text goes to `sendText`; the model's tool calls run against the Command Layer and report a short+status back via `onActed`; anything not satisfied by a tool call comes back through+`onComplexRequest` → the full local pipeline (`runLocalCommand`, never re-entering Live). When the+session isn't connected, `submitCommand` runs the local pipeline exactly as before.+`UserQueryOverlayController` streams the mic's `onAudioFrames` into the session via+`streamLiveAudioFrames` (no-op unless audio is enabled and connected); a batch voice transcript is+dropped while audio is streaming to avoid double-handling.++## Continuous audio++When `GEMINI_LIVE_AUDIO` is enabled and the session connects, the model fires+`onLiveAudioStreamingChanged(true)`; `UserQueryOverlayController` calls+`MicrophoneWaveformMeter.startContinuousListening()`, which keeps the engine running (and ignores+UI-driven `stop()`s) so audio streams beyond the voice-capture window. Tear down via+`stopContinuousListening()`.++## Configuration recap++Live runs against Vertex AI using backend-minted OAuth tokens (no client-held API key). Enable/audio+are client toggles (`GEMINI_LIVE_ENABLED` on by default, `GEMINI_LIVE_AUDIO` opt-in). The backend+route needs `GOOGLE_APPLICATION_CREDENTIALS_JSON` and optionally `GEMINI_VERTEX_LOCATION` /+`GEMINI_LIVE_MODEL`.++## Testing++This environment needs the full Xcode toolchain and a suite filter:++```+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer swift test --filter GeminiLiveTests+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer swift test --filter GenericHarnessTests+```++(A no-filter full run hangs on a GUI-dependent suite.) Covered today: Command Layer descriptors+surface + input validation (`GenericHarnessTests`), and Gemini Live config parsing, function+declarations, PCM packing, and frame parsing (`GeminiLiveTests`). `GenericHarnessTests` has 8+failures that pre-date this work (confirmed via a clean-tree `git stash -u` re-run).diff --git a/site/src/app/api/inference/live-token/route.ts b/site/src/app/api/inference/live-token/route.tsnew file mode 100644index 00000000..b2da3e3f--- /dev/null+++ b/site/src/app/api/inference/live-token/route.ts@@ -0,0 +1,22 @@+import { NextResponse } from "next/server";++import { withDonkeyAuth } from "@/lib/donkey-api-auth";+import { requireInferenceClientId } from "@/lib/inference/responses";+import { mintVertexLiveConnection } from "@/lib/inference/vertex-live";++export const dynamic = "force-dynamic";++// Mints a short-lived Vertex AI access token so a Donkey client can open a+// Gemini Live websocket directly. The long-lived service-account credential+// stays on the backend. Errors propagate raw.+export const POST = withDonkeyAuth(async (request) => {+ const client = requireInferenceClientId(request.donkey.clientId);+ if (!client.ok) {+ return client.response;+ }++ const connection = await mintVertexLiveConnection();+ return NextResponse.json(connection, {+ headers: { "Cache-Control": "no-store" },+ });+});diff --git a/site/src/lib/inference/vertex-live.ts b/site/src/lib/inference/vertex-live.tsnew file mode 100644index 00000000..1b298839--- /dev/null+++ b/site/src/lib/inference/vertex-live.ts@@ -0,0 +1,117 @@+import { JWT } from "google-auth-library";++import { InferenceProviderError } from "@/lib/inference/providers";++const vertexAIScope = "https://www.googleapis.com/auth/cloud-platform";+const defaultVertexLocation = "global";+// Keep in sync with GeminiLiveConfiguration.defaultModel in the macOS client+// (apps/Donkey/.../GeminiLiveConfiguration.swift); both read GEMINI_LIVE_MODEL.+const defaultLiveModel = "gemini-3.1-flash-live-preview";++type AdapterEnvironment = Record<string, string | undefined>;++/**+ * Connection details a Donkey client needs to open a Gemini Live (Vertex AI)+ * websocket directly: a short-lived OAuth access token plus the endpoint and+ * fully-qualified model path. The long-lived service-account credential never+ * leaves the backend.+ */+export type VertexLiveConnection = {+ token: string;+ expiresAt: string | null;+ websocketUrl: string;+ model: string;+ project: string;+ location: string;+};++export function vertexLiveConfigured(+ environment: AdapterEnvironment = process.env,+): boolean {+ return Boolean(environment.GOOGLE_APPLICATION_CREDENTIALS_JSON?.trim());+}++/** Mint a short-lived Vertex AI access token + Live connection details. */+export async function mintVertexLiveConnection(+ environment: AdapterEnvironment = process.env,+): Promise<VertexLiveConnection> {+ const raw = environment.GOOGLE_APPLICATION_CREDENTIALS_JSON?.trim();+ if (!raw) {+ throw new InferenceProviderError(+ "Vertex AI service account credentials are not configured.",+ { statusCode: 503, code: "vertex_live_not_configured" },+ );+ }++ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ throw new InferenceProviderError("Google service account JSON is invalid.", {+ statusCode: 500,+ code: "invalid_google_service_account_json",+ });+ }++ const credentials = parsed as {+ client_email?: string;+ private_key?: string;+ private_key_id?: string;+ project_id?: string;+ };+ const clientEmail = credentials.client_email?.trim();+ const privateKey = credentials.private_key;+ const project = credentials.project_id?.trim();+ if (!clientEmail || !privateKey || !project) {+ throw new InferenceProviderError(+ "Google service account JSON must include client_email, private_key, and project_id.",+ { statusCode: 500, code: "invalid_google_service_account_json" },+ );+ }++ const jwt = new JWT({+ email: clientEmail,+ key: privateKey,+ keyId: credentials.private_key_id,+ scopes: [vertexAIScope],+ });++ let token: string | null | undefined;+ try {+ ({ token } = await jwt.getAccessToken());+ } catch (error) {+ throw new InferenceProviderError("Failed to mint a Vertex AI access token.", {+ statusCode: 502,+ code: "vertex_live_token_failed",+ details: { message: error instanceof Error ? error.message : String(error) },+ });+ }+ if (!token) {+ throw new InferenceProviderError("Failed to mint a Vertex AI access token.", {+ statusCode: 502,+ code: "vertex_live_token_failed",+ });+ }++ const location =+ environment.GEMINI_VERTEX_LOCATION?.trim()+ || environment.GOOGLE_VERTEX_LOCATION?.trim()+ || defaultVertexLocation;+ const model = environment.GEMINI_LIVE_MODEL?.trim() || defaultLiveModel;+ const host =+ location === "global"+ ? "aiplatform.googleapis.com"+ : `${location}-aiplatform.googleapis.com`;+ const websocketUrl =+ `wss://${host}/ws/google.cloud.aiplatform.v1beta1.LlmBidiService/BidiGenerateContent`;+ const expiry = jwt.credentials.expiry_date;++ return {+ token,+ expiresAt: typeof expiry === "number" ? new Date(expiry).toISOString() : null,+ websocketUrl,+ model: `projects/${project}/locations/${location}/publishers/google/models/${model}`,+ project,+ location,+ };+}