Open source CapCut alternative.
TypeScript
Wire Gemini Live vision escalation
David Le4e4ec6adaa65
diff --git a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swiftindex ae04d542..29efed82 100644--- a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift+++ b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift@@ -36,12 +36,22 @@ final class GeminiLiveVoiceController {private(set) var isConnected = falseprivate var isAudioStreaming = false+ /// Mints the Vertex auth for the vision escalation. Defaults to the backend+ /// token-mint path; injectable for tests.+ private let visionAuthProvider: @Sendable () async throws -> GeminiVertexVisionPlanner.VertexAuth+init(configuration: GeminiLiveConfiguration = .fromEnvironment(),- systemInstruction: String = GeminiLiveVoiceController.defaultSystemInstruction+ systemInstruction: String = GeminiLiveVoiceController.defaultSystemInstruction,+ visionAuthProvider: @escaping @Sendable () async throws -> GeminiVertexVisionPlanner.VertexAuth = {+ try await GeminiVertexVisionPlanner.mintAuth(+ backend: DonkeyBackendInferenceClient(configuration: try DonkeyBackendInferenceConfiguration.fromEnvironment())+ )+ }) {self.configuration = configurationself.systemInstruction = systemInstruction+ self.visionAuthProvider = visionAuthProviderlet services = HarnessBuiltInToolServices(commandExecutor: DonkeyCommandBackends.makeExecutor())self.registry = HarnessToolRegistry(tools: BuiltInHarnessToolExecutors.tools(@@ -55,6 +65,7 @@ final class GeminiLiveVoiceController {guard configuration.enabled, session == nil else { return }let session = GeminiLiveSession(systemInstruction: systemInstruction,+ functionDescriptors: DonkeyCommandLayer.descriptors + [Self.visionControlDescriptor],connectionProvider: Self.makeConnectionProvider())self.session = session@@ -127,7 +138,17 @@ final class GeminiLiveVoiceController {guard let session else { return }var results: [AIRealtimeToolResult] = []for call in calls {- let toolCall = HarnessToolCall(id: call.id, name: call.name, input: call.arguments)+ // Gemini sometimes namespaces the tool-call name (e.g. `default_<name>`);+ // dispatch on the canonical name (a structured field, not user text).+ let toolName = Self.canonicalToolName(call.name)+ // Escalation to vision: run OUTSIDE this event-consumer task (capture+ // hangs inside `for await session.events`) and answer the model when the+ // drive finishes.+ if toolName == Self.visionControlToolName {+ launchVision(call)+ continue+ }+ let toolCall = HarnessToolCall(id: call.id, name: toolName, input: call.arguments)let result = await registry.execute(toolCall,taskID: "gemini-live",@@ -142,7 +163,7 @@ final class GeminiLiveVoiceController {response.removeValue(forKey: "executor")response["status"] = result.status.rawValueresponse["summary"] = result.summary- // Surface a clarification gate (e.g. music.play asking what to play)+ // 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"@@ -154,35 +175,121 @@ final class GeminiLiveVoiceController {response: response))}- try? await session.sendToolResults(results)+ if !results.isEmpty { try? await session.sendToolResults(results) }+ }++ /// Run the vision escalation in a separate task (NOT the event-consumer task)+ /// and answer the model's `vision_control` call when the drive completes.+ private func launchVision(_ call: AIRealtimeToolCall) {+ let app = (call.arguments["app"] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)+ let goal = (call.arguments["goal"] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)+ let model = configuration.visionModel+ let useBox = configuration.visionBoxEnabled+ let callID = call.id+ let toolName = call.name+ let provider = visionAuthProvider+ // Bind the result to the session that issued this call. A drive can run for+ // minutes; if `stop()`/`start()` replaces the session meanwhile, we must not+ // answer a fresh session that never made this call (it would leave the+ // original turn unanswered and could confuse the new one).+ let session = self.session++ // The model supplies `app`/`goal`; an empty `app` can't resolve a window, so+ // answer immediately asking for it instead of burning a no-op drive.+ guard !app.isEmpty else {+ let summary = "vision_control needs a non-empty `app` to operate; ask the user which app and retry."+ onActed?(summary)+ Task { try? await session?.sendToolResults([+ AIRealtimeToolResult(id: callID, name: toolName, response: ["status": "invalidInput", "summary": summary])+ ]) }+ return+ }++ Task { [weak self] in+ let status: String+ let summary: String+ do {+ let auth = try await provider()+ // Box and single-point drivers are independent (separate Outcome+ // types), so read the two fields we need from each branch locally.+ let completed: Bool+ let turns: Int+ if useBox {+ let outcome = await VertexVisionBoxDriver.drive(+ appName: app, bundleIdentifier: nil, goal: goal, auth: auth, model: model+ )+ completed = outcome.completed+ turns = outcome.turns+ } else {+ let outcome = await VertexVisionDriver.drive(+ appName: app, bundleIdentifier: nil, goal: goal, auth: auth, model: model+ )+ completed = outcome.completed+ turns = outcome.turns+ }+ status = completed ? "succeeded" : "incomplete"+ summary = "vision \(completed ? "completed" : "did not complete") \"\(goal)\" in \(app) over \(turns) turns"+ } catch {+ status = "failed"+ summary = "vision could not start (the screen-vision path needs the Vertex backend; check DONKEY_WEB_BASE_URL): \(error)"+ }+ self?.onActed?(summary)+ try? await session?.sendToolResults([+ AIRealtimeToolResult(id: callID, name: toolName, response: ["status": status, "summary": summary])+ ])+ }}// 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.+ /// Connection provider chosen by configuration: the Developer-API key path+ /// when `GEMINI_API_KEY` is set, else the Vertex backend-mint path. Re-invoked+ /// on every (re)connect so Vertex OAuth tokens stay 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)+ GeminiLiveConnectionFactory.makeProvider()+ }++ /// Strip a Gemini name-spacing prefix (`default_api.`, `default_`) from a+ /// tool-call name so dispatch matches the declared name.+ static func canonicalToolName(_ raw: String) -> String {+ for prefix in ["default_api.", "default_api_", "default_"] where raw.hasPrefix(prefix) {+ return String(raw.dropFirst(prefix.count))}+ return raw}+ // MARK: - Vision escalation++ static let visionControlToolName = "vision_control"++ /// The screen-last escalation tool: when no fast tool can operate an app, the+ /// model calls this and a vision agent (gemini-3.5) drives the app by sight.+ /// Not a `DonkeyCommandLayer` command — it's a Live-controller capability handled+ /// in `launchVision`, since its backend needs `DonkeyAI` (which `DonkeyRuntime`,+ /// where the Command Layer backends live, can't import).+ static let visionControlDescriptor = HarnessToolDescriptor(+ name: visionControlToolName,+ pluginID: "donkey.vision",+ summary: "Operate an app by looking at the screen (a vision agent clicks/types). Use ONLY when a task must happen inside a specific app the fast tools can't drive — e.g. searching for and playing something in Spotify (music_play controls Apple Music only).",+ inputSchema: [+ "app": "The app to operate, e.g. Spotify.",+ "goal": "What to accomplish in the app, e.g. play Coldplay's most popular song."+ ],+ requiredPermissions: [.input, .screenCapture],+ safetyClass: .guardedInput+ )+// 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.+ don't cover. music_play controls Apple Music only — it CANNOT control Spotify. \+ When a task must happen in a specific app that no fast tool can operate (e.g. \+ searching for and playing a song in Spotify), call vision_control with the app \+ and goal; a vision agent will operate the screen. Discover before guessing rather \+ than inventing names or values. Read each tool's returned output and retry or \+ adjust on failure. Keep replies short."""}diff --git a/apps/Donkey/Sources/Donkey/VertexVisionBoxDriver.swift b/apps/Donkey/Sources/Donkey/VertexVisionBoxDriver.swiftnew file mode 100644index 00000000..40b89cb8--- /dev/null+++ b/apps/Donkey/Sources/Donkey/VertexVisionBoxDriver.swift@@ -0,0 +1,164 @@+import AppKit+import DonkeyAI+import DonkeyContracts+import DonkeyRuntime+import Foundation++/// Box-based sibling of `VertexVisionDriver`. Each turn it screenshots the app+/// window, asks `GeminiVertexVisionBoxPlanner` for the next action with the target+/// as a 2D bounding box, and — for a click — tries the box center first and then a+/// few nearby points, stopping as soon as the screen changes (or `verify()`+/// passes). This makes a single turn robust to a slightly-loose box instead of+/// waiting a whole model round-trip to recover from one missed point.+///+/// Selected by `GEMINI_VISION_BOX=1` in `GeminiLiveVoiceController.launchVision`;+/// the single-point `VertexVisionDriver` remains the default. Same constraint+/// applies: must NOT run inside the Live session's `for await session.events`+/// consumer task (ScreenCaptureKit `capture` hangs there).+@MainActor+enum VertexVisionBoxDriver {+ /// Self-contained outcome (the box variant does not depend on the single-point+ /// driver, so it survives that driver's refactors).+ struct Outcome: Sendable {+ var completed: Bool+ var turns: Int+ var history: [String]+ }++ static func drive(+ appName: String,+ bundleIdentifier: String?,+ goal: String,+ auth: GeminiVertexVisionPlanner.VertexAuth,+ model: String,+ settleNanoseconds: UInt64 = 1_500_000_000,+ attemptSettleNanoseconds: UInt64 = 300_000_000,+ maxTurns: Int = 16,+ capturer: ScreenCaptureKitWindowScreenshotCapturer = ScreenCaptureKitWindowScreenshotCapturer(),+ verify: (@MainActor () -> Bool)? = nil,+ onTurn: (@MainActor (Int, CapturedWindowScreenshot, GeminiVertexVisionBoxPlanner.VisionBoxAction) -> Void)? = nil+ ) async -> Outcome {+ guard var target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {+ return Outcome(completed: false, turns: 0, history: ["no \(appName) window"])+ }+ // Per-app operating knowledge comes from a discoverable skill pack, same+ // source the single-point driver and backend vision path use.+ let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(+ forApp: appName, bundleIdentifier: bundleIdentifier+ )+ var history: [String] = []+ var turns = 0+ var completed = false+ var lastClickKey = ""+ var repeatCount = 0++ turnLoop: for _ in 0..<maxTurns {+ if verify?() == true { completed = true; break }+ ensureAppFrontAndRestored(appName: appName, processID: target.processID)+ try? await Task.sleep(nanoseconds: 250_000_000)+ if let refreshed = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) {+ target = refreshed+ }+ guard let shot = try? await capturer.capture(target: target) else {+ history.append("screenshot failed"); break+ }+ let compressed = ScreenshotCompression.compressedForModel(shot)++ let action: GeminiVertexVisionBoxPlanner.VisionBoxAction+ do {+ action = try await GeminiVertexVisionBoxPlanner.nextBoxAction(+ auth: auth, model: model, goal: goal, appName: appName,+ history: history, appGuidance: appGuidance, compressed: compressed, window: target.bounds+ )+ } catch {+ history.append("vision plan failed: \(error)"); break+ }+ turns += 1+ onTurn?(turns, shot, action)+ let reason = action.reason ?? ""++ if action.action == "done" {+ if let verify {+ if verify() { completed = true; break }+ history.append("claimed done but verify() false — your last action missed; return a tighter box")+ try? await Task.sleep(nanoseconds: settleNanoseconds)+ continue+ }+ completed = true+ history.append("done: \(reason)")+ break+ }++ switch action.action {+ case "click":+ guard let points = action.screenPoints, !points.isEmpty else {+ history.append("click without box: \(reason)")+ break+ }+ let centerKey = "\(Int(points[0].x)),\(Int(points[0].y))"+ repeatCount = (centerKey == lastClickKey) ? repeatCount + 1 : 0+ lastClickKey = centerKey+ if repeatCount >= 4 {+ history.append("aborting: stuck repeating box center \(centerKey)")+ break turnLoop+ }++ var landedIndex: Int?+ for (index, point) in points.enumerated() {+ _ = MacPointerInput.moveAndClick(at: point)+ if verify?() == true { landedIndex = index; completed = true; break }+ try? await Task.sleep(nanoseconds: attemptSettleNanoseconds)+ if let after = try? await capturer.capture(target: target),+ ScreenshotChange.changed(shot.pngData, after.pngData) {+ landedIndex = index+ break+ }+ }+ if let landedIndex {+ let landed = points[landedIndex]+ history.append("clicked box point \(landedIndex) (\(Int(landed.x)),\(Int(landed.y))) of \(points.count)\(repeatCount >= 2 ? " AGAIN" : "") — screen changed: \(reason)")+ } else {+ history.append("clicked \(points.count) box points, no visible change — pick a different/tighter target: \(reason)")+ }+ if completed { break turnLoop }+ case "type":+ MacKeyboardInput.type(action.text ?? "")+ history.append("typed \"\(action.text ?? "")\"")+ case "key":+ MacKeyboardInput.pressKey(action.text ?? "return")+ history.append("key \(action.text ?? "return")")+ default:+ history.append("ignored action \(action.action)")+ }+ try? await Task.sleep(nanoseconds: settleNanoseconds)+ }++ if let verify, !completed { completed = verify() }+ return Outcome(completed: completed, turns: turns, history: history)+ }++ /// Bring an app frontmost and un-minimize its windows (a stray vision click can+ /// hit the minimize button, breaking every later screenshot). Kept local so the+ /// box variant stays independent of the single-point driver.+ private static func ensureAppFrontAndRestored(appName: String, processID: pid_t) {+ NSRunningApplication(processIdentifier: processID)?.activate()+ let source = """+ tell application "System Events"+ if exists process "\(appName)" then+ tell process "\(appName)"+ set frontmost to true+ try+ repeat with w in windows+ if value of attribute "AXMinimized" of w is true then+ set value of attribute "AXMinimized" of w to false+ end if+ end repeat+ end try+ end tell+ end if+ end tell+ """+ var error: NSDictionary?+ NSAppleScript(source: source)?.executeAndReturnError(&error)+ }+}diff --git a/apps/Donkey/Sources/Donkey/VertexVisionDriver.swift b/apps/Donkey/Sources/Donkey/VertexVisionDriver.swiftnew file mode 100644index 00000000..98b1d201--- /dev/null+++ b/apps/Donkey/Sources/Donkey/VertexVisionDriver.swift@@ -0,0 +1,142 @@+import AppKit+import DonkeyAI+import DonkeyContracts+import DonkeyRuntime+import Foundation++/// Drives an app by vision: each turn it screenshots the app window, asks the+/// turn-based Vertex vision model (`GeminiVertexVisionPlanner`, default+/// `gemini-3.5-flash`) for the single next click/type/key, and executes it with the+/// app's real pointer/keyboard. This is the "look at the screen, decide, act"+/// fallback the Live command session escalates to (via `vision_control`) when no+/// fast tool can operate an app.+///+/// IMPORTANT: must NOT be driven from inside the Live session's `for await+/// session.events` consumer task — ScreenCaptureKit `capture` hangs there. Run it+/// from a separate task (see `GeminiLiveVoiceController`).+@MainActor+enum VertexVisionDriver {+ struct Outcome: Sendable {+ var completed: Bool+ var turns: Int+ var history: [String]+ }++ static func drive(+ appName: String,+ bundleIdentifier: String?,+ goal: String,+ auth: GeminiVertexVisionPlanner.VertexAuth,+ model: String,+ settleNanoseconds: UInt64 = 1_500_000_000,+ maxTurns: Int = 16,+ capturer: ScreenCaptureKitWindowScreenshotCapturer = ScreenCaptureKitWindowScreenshotCapturer(),+ verify: (@MainActor () -> Bool)? = nil+ ) async -> Outcome {+ guard var target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {+ return Outcome(completed: false, turns: 0, history: ["no \(appName) window"])+ }+ // Per-app operating knowledge comes from a discoverable skill pack (a+ // BuiltInSkills/<app>/SKILL.md with an `apps:` line), never a hardcoded app+ // list — same source the backend vision path uses.+ let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(+ forApp: appName, bundleIdentifier: bundleIdentifier+ )+ var history: [String] = []+ var turns = 0+ var completed = false+ var lastClickKey = ""+ var repeatCount = 0++ turnLoop: for _ in 0..<maxTurns {+ if verify?() == true { completed = true; break }+ ensureAppFrontAndRestored(appName: appName, processID: target.processID)+ try? await Task.sleep(nanoseconds: 250_000_000)+ if let refreshed = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) {+ target = refreshed+ }+ guard let shot = try? await capturer.capture(target: target) else {+ history.append("screenshot failed"); break+ }+ let compressed = ScreenshotCompression.compressedForModel(shot)++ let action: VisionActionPlanner.PlannedAction+ do {+ action = try await GeminiVertexVisionPlanner.nextAction(+ auth: auth, model: model, goal: goal, appName: appName,+ history: history, appGuidance: appGuidance, compressed: compressed, window: target.bounds+ )+ } catch {+ history.append("vision plan failed: \(error)"); break+ }+ turns += 1+ let reason = action.reason ?? ""++ if action.action == "done" {+ // Verify-don't-trust when a verifier is provided; otherwise trust the+ // model's claim (the general case, no app-specific success signal).+ if let verify {+ if verify() { completed = true; break }+ history.append("claimed done but verify() false — your last action missed; click the exact target")+ try? await Task.sleep(nanoseconds: settleNanoseconds)+ continue+ }+ completed = true+ history.append("done: \(reason)")+ break+ }++ switch action.action {+ case "click":+ if let point = action.screenPoint {+ let key = "\(Int(point.x)),\(Int(point.y))"+ repeatCount = (key == lastClickKey) ? repeatCount + 1 : 0+ lastClickKey = key+ if repeatCount >= 4 { history.append("aborting: stuck repeating click \(key)"); break turnLoop }+ _ = MacPointerInput.moveAndClick(at: point)+ history.append(repeatCount >= 2+ ? "clicked (\(key)) AGAIN — not working; pick a DIFFERENT target/exact center: \(reason)"+ : "clicked (\(key)): \(reason)")+ } else {+ history.append("click without point: \(reason)")+ }+ case "type":+ MacKeyboardInput.type(action.text ?? "")+ history.append("typed \"\(action.text ?? "")\"")+ case "key":+ MacKeyboardInput.pressKey(action.text ?? "return")+ history.append("key \(action.text ?? "return")")+ default:+ history.append("ignored action \(action.action)")+ }+ try? await Task.sleep(nanoseconds: settleNanoseconds)+ }++ if let verify, !completed { completed = verify() }+ return Outcome(completed: completed, turns: turns, history: history)+ }++ /// Bring an app frontmost and un-minimize its windows (a stray vision click can+ /// hit the minimize button, breaking every later screenshot).+ static func ensureAppFrontAndRestored(appName: String, processID: pid_t) {+ NSRunningApplication(processIdentifier: processID)?.activate()+ let source = """+ tell application "System Events"+ if exists process "\(appName)" then+ tell process "\(appName)"+ set frontmost to true+ try+ repeat with w in windows+ if value of attribute "AXMinimized" of w is true then+ set value of attribute "AXMinimized" of w to false+ end if+ end repeat+ end try+ end tell+ end if+ end tell+ """+ var error: NSDictionary?+ NSAppleScript(source: source)?.executeAndReturnError(&error)+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swift b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swiftindex bfa660f2..53dcb163 100644--- a/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swift+++ b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConfiguration.swift@@ -7,19 +7,64 @@ import Foundation/// 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.+/// Two auth paths (see `GeminiLiveConnectionFactory`): production is keyless+/// Vertex AI OAuth, where the Donkey backend mints a short-lived access token+/// (and supplies the endpoint + model) via `POST /api/inference/live-token/`. A+/// dev-only path connects directly to the Developer API when `GEMINI_API_KEY` is+/// set.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+ /// Gemini Developer API key (`GEMINI_API_KEY`). When set, the client connects+ /// directly to the Developer API (`generativelanguage.googleapis.com`) with+ /// this key instead of minting a Vertex token via the backend. Dev-only — a+ /// client-held key; prod uses the keyless Vertex path.+ public var apiKey: String?+ /// Live model id for the Developer-API path (`GEMINI_LIVE_MODEL`). The Vertex+ /// path ignores this (its model comes from the backend mint response).+ public var model: String+ /// Model used for the per-turn vision driver (`GEMINI_VISION_MODEL`). This is a+ /// turn-based `generateContent` model (not Live/bidi) — a stronger model for+ /// the screenshot-grounding task than the fast realtime command model.+ public var visionModel: String+ /// Opt into the box-based vision driver (`GEMINI_VISION_BOX`): the planner+ /// returns a 2D bounding box and the driver clicks the box center plus nearby+ /// points in one turn. Off by default, leaving the single-point driver in place.+ public var visionBoxEnabled: Bool+ /// Whether the Developer-API Live session requests AUDIO response modality+ /// (`GEMINI_LIVE_AUDIO_OUTPUT`). The default Dev-API model is audio-output only,+ /// so this defaults true; set falsey when pointing `GEMINI_LIVE_MODEL` at a+ /// TEXT-capable Live model. Ignored on the Vertex path (always TEXT).+ public var liveAudioOutput: Bool- public init(enabled: Bool, audioEnabled: Bool = false) {+ /// Default Developer-API Live (command) model — the realtime, tool-calling+ /// brain. `gemini-2.5-flash-native-audio-preview-09-2025` is the 2.5 Live model+ /// available on the Developer API; it is audio-output only (see+ /// `GeminiLiveConnection.audioOutput`).+ public static let defaultModel = "gemini-2.5-flash-native-audio-preview-09-2025"+ /// Default vision model — stronger, turn-based, used only when a task needs the+ /// screen.+ public static let defaultVisionModel = "gemini-3.5-flash"++ public init(+ enabled: Bool,+ audioEnabled: Bool = false,+ apiKey: String? = nil,+ model: String = GeminiLiveConfiguration.defaultModel,+ visionModel: String = GeminiLiveConfiguration.defaultVisionModel,+ visionBoxEnabled: Bool = false,+ liveAudioOutput: Bool = true+ ) {self.enabled = enabledself.audioEnabled = audioEnabled+ self.apiKey = apiKey+ self.model = model+ self.visionModel = visionModel+ self.visionBoxEnabled = visionBoxEnabled+ self.liveAudioOutput = liveAudioOutput}/// Build from environment.@@ -35,7 +80,12 @@ public struct GeminiLiveConfiguration: Equatable, Sendable {) -> GeminiLiveConfiguration {GeminiLiveConfiguration(enabled: boolValue(environment["GEMINI_LIVE_ENABLED"], default: true),- audioEnabled: boolValue(environment["GEMINI_LIVE_AUDIO"])+ audioEnabled: boolValue(environment["GEMINI_LIVE_AUDIO"]),+ apiKey: trimmed(environment["GEMINI_API_KEY"]),+ model: trimmed(environment["GEMINI_LIVE_MODEL"]) ?? defaultModel,+ visionModel: trimmed(environment["GEMINI_VISION_MODEL"]) ?? defaultVisionModel,+ visionBoxEnabled: boolValue(environment["GEMINI_VISION_BOX"]),+ liveAudioOutput: boolValue(environment["GEMINI_LIVE_AUDIO_OUTPUT"], default: true))}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiLiveConnectionFactory.swift b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConnectionFactory.swiftnew file mode 100644index 00000000..47e395e1--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/GeminiLiveConnectionFactory.swift@@ -0,0 +1,53 @@+import Foundation++/// Builds the `GeminiLiveConnection` provider for a Live session, choosing the+/// auth path from configuration:+///+/// - **Developer API** (`GEMINI_API_KEY` set): connect directly to+/// `generativelanguage.googleapis.com` with the key in the query string, using+/// the client-configured model (`GEMINI_LIVE_MODEL`, default+/// `GeminiLiveConfiguration.defaultModel` — an audio-output-only model). No+/// backend round-trip. Dev-only — a client-held key.+/// - **Vertex AI** (no key): mint a short-lived OAuth token via the backend+/// (`DonkeyBackendInferenceClient.mintLiveConnection`); the model + endpoint+/// come from the backend. This stays the production path (no client secrets).+public enum GeminiLiveConnectionFactory {+ /// Developer-API bidi Live endpoint (v1beta).+ private static let developerAPIEndpoint =+ "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent"++ /// A provider that rebuilds the connection on every (re)connect so Vertex+ /// OAuth tokens stay fresh; the Developer-API key path is constant.+ public static func makeProvider(+ configuration: GeminiLiveConfiguration = .fromEnvironment()+ ) -> @Sendable () async throws -> GeminiLiveConnection {+ return {+ if let apiKey = configuration.apiKey, !apiKey.isEmpty {+ return try developerAPIConnection(+ apiKey: apiKey, model: configuration.model, audioOutput: configuration.liveAudioOutput+ )+ }+ return try await vertexConnection()+ }+ }++ static func developerAPIConnection(apiKey: String, model: String, audioOutput: Bool) throws -> GeminiLiveConnection {+ var components = URLComponents(string: developerAPIEndpoint)+ components?.queryItems = [URLQueryItem(name: "key", value: apiKey)]+ guard let url = components?.url else { throw GeminiLiveError.invalidURL }+ // The key authenticates via the query string, so there's no bearer token.+ // The default Dev-API model is audio-output only, so `audioOutput` defaults+ // true (tool calls + output transcription still flow even when TEXT is+ // rejected); set `GEMINI_LIVE_AUDIO_OUTPUT=0` for a TEXT-capable model.+ return GeminiLiveConnection(url: url, bearerToken: nil, model: model, audioOutput: audioOutput)+ }++ static func vertexConnection() async throws -> GeminiLiveConnection {+ 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, audioOutput: false)+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiLiveSession.swift b/apps/Donkey/Sources/DonkeyAI/GeminiLiveSession.swiftindex 19552234..265145e2 100644--- a/apps/Donkey/Sources/DonkeyAI/GeminiLiveSession.swift+++ b/apps/Donkey/Sources/DonkeyAI/GeminiLiveSession.swift@@ -14,11 +14,17 @@ public struct GeminiLiveConnection: Equatable, Sendable {public var url: URLpublic var bearerToken: String?public var model: String+ /// Request AUDIO response modality instead of TEXT. Some Live models (e.g. the+ /// default Developer-API model, `GeminiLiveConfiguration.defaultModel`) are+ /// audio-output only and reject TEXT; tool calls + output transcription still+ /// work.+ public var audioOutput: Bool- public init(url: URL, bearerToken: String?, model: String) {+ public init(url: URL, bearerToken: String?, model: String, audioOutput: Bool = false) {self.url = urlself.bearerToken = bearerTokenself.model = model+ self.audioOutput = audioOutput}}@@ -130,7 +136,7 @@ public actor GeminiLiveSession: AIRealtimeSession {model: connection.model,systemInstruction: systemInstruction,functionDeclarations: CommandLayerFunctionDeclarations.declarations(from: functionDescriptors),- includeAudioResponse: false,+ includeAudioResponse: connection.audioOutput,resumptionHandle: resumptionHandle)try await socket.send(.data(setup))diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swift b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swiftnew file mode 100644index 00000000..7a917793--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swift@@ -0,0 +1,145 @@+import CoreGraphics+import DonkeyContracts+import DonkeyRuntime+import Foundation++/// Box-based sibling of `GeminiVertexVisionPlanner`. Instead of a single click+/// point, it asks the turn-based Vertex vision model to return the target control+/// as a 2D bounding box (`box = [ymin, xmin, ymax, xmax]` in Gemini's 0–1000+/// normalized space). `VertexVisionBoxGeometry` turns that box into an ordered list+/// of click points (center first, then nearby fallbacks), so a slightly-loose box+/// still lands on the control within a single turn.+///+/// Auth (token + project + location) is reused from `GeminiVertexVisionPlanner`+/// (`VertexAuth` / `mintAuth`); only the schema, prompt, and decoded shape differ.+public enum GeminiVertexVisionBoxPlanner {+ /// A single planned action with the target expressed as a bounding box.+ public struct VisionBoxAction: Equatable, Sendable, Codable {+ public var action: String // "click" | "type" | "key" | "done"+ public var box: [Double]? // [ymin, xmin, ymax, xmax] normalized 0–1000, click only+ public var text: String?+ public var reason: String?+ /// Resolved real-screen click points (box center first), filled in post-decode.+ public var screenPoints: [CGPoint]?++ private enum CodingKeys: String, CodingKey { case action, box, text, reason }+ }++ public static func nextBoxAction(+ auth: GeminiVertexVisionPlanner.VertexAuth,+ model: String,+ goal: String,+ appName: String,+ history: [String],+ appGuidance: String? = nil,+ compressed: CompressedScreenshot,+ window: WindowTargetBounds,+ urlSession: URLSession = .shared+ ) async throws -> VisionBoxAction {+ let host = auth.location == "global" ? "aiplatform.googleapis.com" : "\(auth.location)-aiplatform.googleapis.com"+ let endpoint = "https://\(host)/v1/projects/\(auth.project)/locations/\(auth.location)/publishers/google/models/\(model):generateContent"+ guard let url = URL(string: endpoint) else {+ throw GeminiVertexVisionPlanner.PlannerError.requestFailed(status: -1, body: "bad url")+ }++ let width = Int(compressed.pixelSize.width.rounded())+ let height = Int(compressed.pixelSize.height.rounded())+ let body: [String: Any] = [+ "contents": [[+ "role": "user",+ "parts": [+ ["text": prompt(goal: goal, app: appName, width: width, height: height, history: history, appGuidance: appGuidance)],+ ["inlineData": ["mimeType": compressed.contentType, "data": compressed.data.base64EncodedString()]]+ ]+ ]],+ "generationConfig": [+ "temperature": 0,+ "responseMimeType": "application/json",+ // gemini-3.5-flash is a thinking model; left on, thinking tokens can+ // consume the whole budget and starve the JSON output. The raw Vertex+ // API takes the nested thinkingConfig.thinkingBudget form.+ "thinkingConfig": ["thinkingBudget": 0],+ "responseSchema": [+ "type": "object",+ "properties": [+ "action": ["type": "string", "enum": ["click", "type", "key", "done"]],+ "box": ["type": "array", "items": ["type": "number"]],+ "text": ["type": "string"],+ "reason": ["type": "string"]+ ],+ "required": ["action", "reason"]+ ]+ ]+ ]++ var request = URLRequest(url: url)+ request.httpMethod = "POST"+ request.setValue("Bearer \(auth.token)", forHTTPHeaderField: "Authorization")+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ request.httpBody = try JSONSerialization.data(withJSONObject: body)++ let (data, response) = try await urlSession.data(for: request)+ let status = (response as? HTTPURLResponse)?.statusCode ?? -1+ guard status == 200 else {+ throw GeminiVertexVisionPlanner.PlannerError.requestFailed(status: status, body: String(data: data, encoding: .utf8) ?? "")+ }+ guard let text = outputText(data), !text.isEmpty else {+ throw GeminiVertexVisionPlanner.PlannerError.noOutputText(body: String(data: data, encoding: .utf8) ?? "")+ }+ let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)+ var action = try JSONDecoder().decode(VisionBoxAction.self, from: Data(json.utf8))+ if action.action == "click", let box = action.box {+ let points = VisionBoxGeometry.screenPoints(box, window: window)+ action.screenPoints = points.isEmpty ? nil : points+ }+ return action+ }++ private static func outputText(_ data: Data) -> String? {+ guard let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],+ let candidates = root["candidates"] as? [[String: Any]],+ let content = candidates.first?["content"] as? [String: Any],+ let parts = content["parts"] as? [[String: Any]]+ else { return nil }+ return parts.compactMap { $0["text"] as? String }.joined()+ }++ private static func prompt(goal: String, app: String, width: Int, height: Int, history: [String], appGuidance: String?) -> String {+ let historyBlock = history.isEmpty+ ? "This is the first action; nothing has been done yet."+ : "Actions ALREADY performed, in order (do NOT repeat one that already worked):\n"+ + history.suffix(8).enumerated().map { " \($0.offset + 1). \($0.element)" }.joined(separator: "\n")+ let guidanceBlock: String+ if let appGuidance, !appGuidance.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ guidanceBlock = """+++ APP-SPECIFIC OPERATING GUIDE for "\(app)" (follow this — it describes where controls are and how to read state; it never gives fixed coordinates, so always read the current screenshot for exact positions):+ \(appGuidance)+ """+ } else {+ guidanceBlock = ""+ }+ return """+ You are operating the macOS app "\(app)" by clicking and typing to accomplish a goal.+ GOAL: \(goal)+ The attached screenshot is the CURRENT state of the app window (\(width) x \(height) pixels), origin top-left.++ \(historyBlock)\(guidanceBlock)++ Decide the SINGLE next action that best progresses toward the goal given ONLY what is visible now.+ - "click": move the pointer and click a control. Set "box" to a TIGHT 2D bounding box around the ONE+ target control (a button, row, field, or icon). A click has no text.+ - "type": type into the ALREADY-focused field. Set "text"; omit "box". Use this after clicking a text field.+ - "key": press one key. Set "text" to the key name (e.g. "return"); omit "box".+ - "done": the goal is fully and verifiably satisfied in the current screenshot. Omit "box".+ BOX FORMAT: "box" is [ymin, xmin, ymax, xmax], each value NORMALIZED to 0–1000 relative to the image+ (x=0 left … 1000 right; y=0 top … 1000 bottom). We click the box CENTER first and then a few points just+ inside it, so the box must bound exactly one control as tightly as possible — too large and we click the+ wrong thing.+ If you clicked and the screenshot looks unchanged, the click MISSED — re-locate the target and return a+ tighter, correctly-placed box; don't repeat the same one.+ Keep "reason" to one short sentence.+ """+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swiftnew file mode 100644index 00000000..a693b98a--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift@@ -0,0 +1,129 @@+import CoreGraphics+import DonkeyContracts+import DonkeyRuntime+import Foundation++/// Per-turn vision planner backed by a strong turn-based Vertex model+/// (default `gemini-3.5-flash`), separate from the realtime Live command model+/// (`gemini-live-2.5-flash`). Given the current window screenshot + goal it returns+/// the single next UI action (click / type / key / done) with click coordinates in+/// Gemini's 0–1000 normalized space, mapped to the window via+/// `VisionActionPlanner.screenPoint`.+///+/// It calls Vertex `generateContent` directly with a Bearer token minted by the+/// backend (`DonkeyBackendInferenceClient.mintLiveConnection` returns the token ++/// project + location), so the long-lived service-account credential stays on the+/// backend. Reuse one minted token across a session's turns.+public enum GeminiVertexVisionPlanner {+ public struct VertexAuth: Sendable {+ public var token: String+ public var project: String+ public var location: String+ public init(token: String, project: String, location: String) {+ self.token = token+ self.project = project+ self.location = location+ }+ }++ public enum PlannerError: Error, CustomStringConvertible {+ case missingProjectOrLocation+ case requestFailed(status: Int, body: String)+ case noOutputText(body: String)+ public var description: String {+ switch self {+ case .missingProjectOrLocation: return "mint response lacked project/location"+ case let .requestFailed(status, body): return "vertex generateContent \(status): \(body.prefix(200))"+ case let .noOutputText(body): return "no output text: \(body.prefix(200))"+ }+ }+ }++ /// Mint a Vertex auth bundle (token + project + location) from the backend.+ public static func mintAuth(backend: DonkeyBackendInferenceClient) async throws -> VertexAuth {+ let minted = try await backend.mintLiveConnection()+ guard let project = minted.project, let location = minted.location else {+ throw PlannerError.missingProjectOrLocation+ }+ return VertexAuth(token: minted.token, project: project, location: location)+ }++ public static func nextAction(+ auth: VertexAuth,+ model: String,+ goal: String,+ appName: String,+ history: [String],+ appGuidance: String? = nil,+ compressed: CompressedScreenshot,+ window: WindowTargetBounds,+ urlSession: URLSession = .shared+ ) async throws -> VisionActionPlanner.PlannedAction {+ let host = auth.location == "global" ? "aiplatform.googleapis.com" : "\(auth.location)-aiplatform.googleapis.com"+ let endpoint = "https://\(host)/v1/projects/\(auth.project)/locations/\(auth.location)/publishers/google/models/\(model):generateContent"+ guard let url = URL(string: endpoint) else { throw PlannerError.requestFailed(status: -1, body: "bad url") }++ let width = Int(compressed.pixelSize.width.rounded())+ let height = Int(compressed.pixelSize.height.rounded())+ let prompt = VisionActionPlanner.visionPrompt(+ goal: goal, app: appName, width: width, height: height, history: history, appGuidance: appGuidance+ )+ let body: [String: Any] = [+ "contents": [[+ "role": "user",+ "parts": [+ ["text": prompt],+ ["inlineData": ["mimeType": compressed.contentType, "data": compressed.data.base64EncodedString()]]+ ]+ ]],+ "generationConfig": [+ "temperature": 0,+ "responseMimeType": "application/json",+ // gemini-3.5-flash is a thinking model; left on, thinking tokens+ // can consume the whole budget and starve the JSON output (the same+ // failure VisionActionPlanner disables thinking to avoid). The raw+ // Vertex API takes the nested thinkingConfig.thinkingBudget form.+ "thinkingConfig": ["thinkingBudget": 0],+ "responseSchema": [+ "type": "object",+ "properties": [+ "action": ["type": "string", "enum": ["click", "type", "key", "done"]],+ "x": ["type": "number"],+ "y": ["type": "number"],+ "text": ["type": "string"],+ "reason": ["type": "string"]+ ],+ "required": ["action", "x", "y", "reason"]+ ]+ ]+ ]++ var request = URLRequest(url: url)+ request.httpMethod = "POST"+ request.setValue("Bearer \(auth.token)", forHTTPHeaderField: "Authorization")+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ request.httpBody = try JSONSerialization.data(withJSONObject: body)++ let (data, response) = try await urlSession.data(for: request)+ let status = (response as? HTTPURLResponse)?.statusCode ?? -1+ guard status == 200 else {+ throw PlannerError.requestFailed(status: status, body: String(data: data, encoding: .utf8) ?? "")+ }+ guard let text = outputText(data), !text.isEmpty else {+ throw PlannerError.noOutputText(body: String(data: data, encoding: .utf8) ?? "")+ }+ let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)+ var action = try JSONDecoder().decode(VisionActionPlanner.PlannedAction.self, from: Data(json.utf8))+ action.screenPoint = VisionActionPlanner.screenPoint(action: action, window: window)+ return action+ }++ private static func outputText(_ data: Data) -> String? {+ guard let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],+ let candidates = root["candidates"] as? [[String: Any]],+ let content = candidates.first?["content"] as? [String: Any],+ let parts = content["parts"] as? [[String: Any]]+ else { return nil }+ return parts.compactMap { $0["text"] as? String }.joined()+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift b/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swiftindex 59a61f45..984e464b 100644--- a/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift+++ b/apps/Donkey/Sources/DonkeyAI/VisionActionDriver.swift@@ -17,10 +17,27 @@ import Foundationpublic enum VisionActionDriver {public typealias ScreenshotCapture = @MainActor (MacWindowTargetCandidate) async throws -> CapturedWindowScreenshot+ /// Plans the single next UI action from the current screenshot. Injected so the+ /// loop, guards, and action handling are shared across planner backends — the+ /// `backend.createResponse` path (`VisionActionPlanner`) and the direct-Vertex+ /// path (`GeminiVertexVisionPlanner`) differ only in this one step.+ public typealias ActionPlanner = @MainActor (+ _ goal: String,+ _ appName: String,+ _ screenshot: CapturedWindowScreenshot,+ _ window: WindowTargetBounds,+ _ history: [String],+ _ appGuidance: String?+ ) async throws -> VisionActionPlanner.PlannedAction++ /// Repeated identical clicks mean the model is stuck (clicking a target that+ /// never responds); abort rather than burn the whole turn budget on it.+ private static let stuckClickRepeatLimit = 4+public struct Outcome: Sendable {public var completed: Boolpublic var turns: Int- /// "ok" | "noWindowForApp" | "screenshotFailed" | "visionPlanFailed" | "targetNotFrontmost" | "maxTurnsReached"+ /// "ok" | "noWindowForApp" | "screenshotFailed" | "visionPlanFailed" | "targetNotFrontmost" | "stuckRepeatingClick" | "maxTurnsReached"public var reason: Stringpublic var lastNarration: String?public var history: [String]@@ -33,6 +50,9 @@ public enum VisionActionDriver {public var action: VisionActionPlanner.PlannedAction}+ /// Convenience: drive via the backend `createResponse` planner+ /// (`VisionActionPlanner`). Used by the production command router and the+ /// Spotify live smoke test; the loop itself is `drive(planner:)` below.public static func drive(appName: String,bundleIdentifier: String?,@@ -42,23 +62,66 @@ public enum VisionActionDriver {maxTurns: Int = 12,settleNanoseconds: UInt64 = 1_200_000_000,capture: @escaping ScreenshotCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: $0) },+ verify: (@MainActor () -> Bool)? = nil,onTurn: (@MainActor (TurnInfo) -> Void)? = nil+ ) async -> Outcome {+ await drive(+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ goal: goal,+ appGuidance: appGuidance,+ maxTurns: maxTurns,+ settleNanoseconds: settleNanoseconds,+ capture: capture,+ verify: verify,+ onTurn: onTurn,+ planner: { goal, app, shot, window, history, guidance in+ try await VisionActionPlanner.nextAction(+ goal: goal, app: app, screenshot: shot, window: window,+ history: history, appGuidance: guidance, backend: backend+ )+ }+ )+ }++ /// The single vision-driving loop: screenshot → `planner` → execute, until the+ /// model reports `done` (optionally re-checked by `verify`), the goal is+ /// independently verified, the model gets stuck, or `maxTurns` is reached.+ public static func drive(+ appName: String,+ bundleIdentifier: String?,+ goal: String,+ appGuidance: String?,+ maxTurns: Int = 12,+ settleNanoseconds: UInt64 = 1_200_000_000,+ capture: @escaping ScreenshotCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: $0) },+ verify: (@MainActor () -> Bool)? = nil,+ onTurn: (@MainActor (TurnInfo) -> Void)? = nil,+ planner: @escaping ActionPlanner) async -> Outcome {var history: [String] = []var lastNarration: String?var turnsTaken = 0+ var lastClickKey = ""+ var clickRepeatCount = 0// Resolve the target window once and reuse it; only re-resolve when a capture fails (the// window moving/closing is the only thing that invalidates the cached bounds).guard var target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {return Outcome(completed: false, turns: 0, reason: "noWindowForApp", lastNarration: nil, history: history)}- activate(target)+ activate(target, appName: appName)for _ in 0..<maxTurns {+ // An independent success signal (e.g. "Spotify is playing") wins immediately —+ // don't spend a turn asking the model whether it's done when we can check.+ if verify?() == true {+ return finish(true, turnsTaken, "ok", lastNarration, history)+ }+// Ensure the target is frontmost before we screenshot + act; re-activate only if needed.if !isFrontmost(target) {- activate(target)+ activate(target, appName: appName)try? await Task.sleep(nanoseconds: 250_000_000)guard let refreshed = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {return finish(false, turnsTaken, "noWindowForApp", lastNarration, history)@@ -75,15 +138,7 @@ public enum VisionActionDriver {let action: VisionActionPlanner.PlannedActiondo {- action = try await VisionActionPlanner.nextAction(- goal: goal,- app: appName,- screenshot: shot,- window: target.bounds,- history: history,- appGuidance: appGuidance,- backend: backend- )+ action = try await planner(goal, appName, shot, target.bounds, history, appGuidance)} catch {return finish(false, turnsTaken, "visionPlanFailed", lastNarration, history)}@@ -105,11 +160,27 @@ public enum VisionActionDriver {switch effective {case "done":- return finish(true, turnsTaken, "ok", lastNarration, history)+ // Verify-don't-trust when an independent signal is available: the model+ // claiming done while verify() is false means its last action missed.+ if let verify {+ if verify() { return finish(true, turnsTaken, "ok", lastNarration, history) }+ history.append("claimed done but the goal isn't satisfied yet — your last action missed; click the exact target")+ } else {+ return finish(true, turnsTaken, "ok", lastNarration, history)+ }case "click":if let point = action.screenPoint {+ let key = "\(Int(point.x)),\(Int(point.y))"+ clickRepeatCount = (key == lastClickKey) ? clickRepeatCount + 1 : 0+ lastClickKey = key+ if clickRepeatCount >= stuckClickRepeatLimit {+ history.append("aborting: stuck repeating click \(key)")+ return finish(false, turnsTaken, "stuckRepeatingClick", lastNarration, history)+ }_ = MacPointerInput.moveAndClick(at: point)- history.append("clicked at (\(Int(point.x)),\(Int(point.y))): \(action.reason ?? "")")+ history.append(clickRepeatCount >= 2+ ? "clicked (\(key)) AGAIN — not working; pick a DIFFERENT target/exact center: \(action.reason ?? "")"+ : "clicked at (\(key)): \(action.reason ?? "")")} else {history.append("skipped click with no resolvable point")}@@ -128,6 +199,10 @@ public enum VisionActionDriver {try? await Task.sleep(nanoseconds: settleNanoseconds)}+ // Last chance: the final action may have satisfied the goal on the turn we ran out.+ if verify?() == true {+ return finish(true, turnsTaken, "ok", lastNarration, history)+ }return finish(false, turnsTaken, "maxTurnsReached", lastNarration, history)}@@ -163,8 +238,33 @@ public enum VisionActionDriver {NSWorkspace.shared.frontmostApplication?.processIdentifier == pid_t(target.processID)}- private static func activate(_ target: MacWindowTargetCandidate) {+ private static func activate(_ target: MacWindowTargetCandidate, appName: String) {let app = NSRunningApplication(processIdentifier: pid_t(target.processID))_ = app?.activate()+ restoreMinimizedWindows(appName: appName)+ }++ /// Un-minimize the app's windows: a stray vision click can hit the minimize+ /// button, which would break every later screenshot. Best-effort — silently+ /// no-ops without Automation permission. Only runs on (re)activation, not every+ /// turn, so the System Events round-trip isn't on the hot path.+ private static func restoreMinimizedWindows(appName: String) {+ let source = """+ tell application "System Events"+ if exists process "\(appName)" then+ tell process "\(appName)"+ try+ repeat with w in windows+ if value of attribute "AXMinimized" of w is true then+ set value of attribute "AXMinimized" of w to false+ end if+ end repeat+ end try+ end tell+ end if+ end tell+ """+ var error: NSDictionary?+ NSAppleScript(source: source)?.executeAndReturnError(&error)}}diff --git a/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swift b/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swiftindex 313801e7..cfceef06 100644--- a/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swift+++ b/apps/Donkey/Sources/DonkeyAI/VisionActionPlanner.swift@@ -81,15 +81,20 @@ public enum VisionActionPlanner {)}- private static func responseRequest(+ /// Builds the vision-action prompt shared by every planner backend (the+ /// `backend.createResponse` path here and the direct-Vertex+ /// `GeminiVertexVisionPlanner`). Kept in one place so the prompt — the single+ /// most impactful lever on click accuracy — can never drift between paths, and+ /// so the discoverable per-app `appGuidance` is applied uniformly (never a+ /// hardcoded app list). `width`/`height` are the model-visible image pixels.+ nonisolated static func visionPrompt(goal: String,app: String,- compressed: CompressedScreenshot,+ width: Int,+ height: Int,history: [String],appGuidance: String?- ) -> RemoteInferenceResponseCreateRequest {- let width = Int(compressed.pixelSize.width.rounded())- let height = Int(compressed.pixelSize.height.rounded())+ ) -> String {let historyBlock = history.isEmpty? "This is the first action; nothing has been done yet.": "Actions you have ALREADY performed, in order (do NOT repeat one that already worked):\n"@@ -104,7 +109,7 @@ public enum VisionActionPlanner {} else {guidanceBlock = ""}- let prompt = """+ return """You are operating the macOS app "\(app)" by clicking and typing to accomplish a goal.GOAL: \(goal)The attached screenshot is the CURRENT state of the app window (\(width) x \(height) pixels), origin top-left.@@ -124,6 +129,20 @@ public enum VisionActionPlanner {CLICK PRECISELY: set x,y to the exact visual CENTER of the intended control, not above/below/beside it.Keep "reason" to one short sentence."""+ }++ private static func responseRequest(+ goal: String,+ app: String,+ compressed: CompressedScreenshot,+ history: [String],+ appGuidance: String?+ ) -> RemoteInferenceResponseCreateRequest {+ let width = Int(compressed.pixelSize.width.rounded())+ let height = Int(compressed.pixelSize.height.rounded())+ let prompt = visionPrompt(+ goal: goal, app: app, width: width, height: height, history: history, appGuidance: appGuidance+ )return RemoteInferenceResponseCreateRequest(input: .array([.object([diff --git a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swiftindex 180d5fa8..8b74ead0 100644--- a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift+++ b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift@@ -10,10 +10,15 @@ public enum DonkeyCommandLayer {/// Single source of truth for the command names shared between the descriptors/// here and the runtime backend that executes them.+ ///+ /// Names must be valid LLM function-call identifiers (`[A-Za-z_][A-Za-z0-9_]*`):+ /// Gemini/Vertex Live rejects dots and silently normalizes them, so a name like+ /// `apps.list` would come back from the model as `apps_list` and miss dispatch.+ /// Use underscores, never dots.public enum Command: String, CaseIterable, Sendable {case shellExec = "shell_exec"- case appsList = "apps.list"- case musicPlay = "music.play"+ case appsList = "apps_list"+ case musicPlay = "music_play"}public static var descriptors: [HarnessToolDescriptor] {@@ -36,12 +41,22 @@ public enum DonkeyCommandLayer {HarnessToolDescriptor(name: Command.appsList.rawValue,pluginID: pluginID,- summary: "List installed and currently-running applications (display names + bundle ids). Call this to discover exact app names before opening, quitting, or scripting an app instead of guessing.",- inputSchema: ["filter": "Case-insensitive substring to narrow the results."],- optionalInputKeys: ["filter"],+ summary: "List installed and currently-running applications (display names + bundle ids), so you can target exact app names before opening, quitting, or scripting an app instead of guessing. Prefer `filter` when you already know part of the name. The installed list is paginated: to browse the full catalog, read `hasMore`/`nextOffset` in the result and call again with `offset` set to `nextOffset`, keeping the same `filter`.",+ inputSchema: [+ "filter": "Case-insensitive substring to narrow both lists. Use this first when you know part of the app name.",+ "offset": "Zero-based start index into the installed list, for pagination. Defaults to 0. Pass the previous result's `nextOffset` to fetch the next page.",+ "limit": "Max installed apps to return in this page. Defaults to 50, capped at 200. Running apps are always returned in full."+ ],+ optionalInputKeys: ["filter", "offset", "limit"],outputSchema: [- "installed": "Comma-separated installed app names.",- "running": "Comma-separated running app names."+ "installed": "Comma-separated installed app names for the current page.",+ "running": "Comma-separated running app names (always the full list).",+ "installedTotal": "Total installed apps matching the filter, across all pages.",+ "offset": "Start index of the returned page.",+ "limit": "Page size applied.",+ "returned": "Number of installed apps in this page.",+ "hasMore": "\"true\" when more installed pages remain.",+ "nextOffset": "Offset to pass next to continue paging (present only when hasMore is true)."],requiredPermissions: [.appLookup],safetyClass: .readOnlydiff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swiftindex 63dc1477..d0e094bd 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift@@ -32,7 +32,32 @@ public enum DonkeyCommandBackends {}}- // MARK: - apps.list+ // MARK: - apps_list++ /// Default and ceiling for the installed-list page size. The installed+ /// catalog can run to ~100+ entries, which overflowed the response cap and+ /// silently dropped the tail; pagination lets the model page deterministically.+ private static let appsDefaultPageSize = 50+ private static let appsMaxPageSize = 200+ /// Char budget for the joined installed names. The page is built to fit this so+ /// the reported `returned`/`hasMore`/`nextOffset` describe exactly the names+ /// emitted — a later truncation can never silently drop names the model was told+ /// it received and would page past.+ private static let appsResponseCharBudget = 3_000+ /// The Spotlight-backed catalog scan (mdfind subprocess + per-app Info.plist+ /// reads) is expensive and barely changes within a session, so reuse it across+ /// paginated calls instead of re-enumerating on every page.+ private static let installedCatalogTTLSeconds: TimeInterval = 60+ @MainActor private static var installedCatalogCache: (expires: Date, apps: [LocalApplicationCatalogCandidate])?++ @MainActor+ private static func cachedInstalledApplications() -> [LocalApplicationCatalogCandidate] {+ let now = Date()+ if let cache = installedCatalogCache, cache.expires > now { return cache.apps }+ let apps = MacLocalAppAvailabilityProvider.installedApplications()+ installedCatalogCache = (now.addingTimeInterval(installedCatalogTTLSeconds), apps)+ return apps+ }@MainActorprivate static func listApps(_ context: HarnessToolExecutionContext) -> HarnessToolResult {@@ -43,9 +68,28 @@ public enum DonkeyCommandBackends {return value.lowercased().contains(filter)}+ // Pagination inputs apply to the installed list only (the large one);+ // running apps are few and always returned in full.+ var offset = 0+ if let rawOffset = trimmed(context.call.input["offset"]) {+ guard let parsed = Int(rawOffset), parsed >= 0 else {+ return invalidInput(context, "`offset` must be a non-negative integer (zero-based index into the installed list).")+ }+ offset = parsed+ }++ var limit = appsDefaultPageSize+ if let rawLimit = trimmed(context.call.input["limit"]) {+ guard let parsed = Int(rawLimit), parsed >= 1 else {+ return invalidInput(context, "`limit` must be a positive integer (max \(appsMaxPageSize)).")+ }+ limit = min(parsed, appsMaxPageSize)+ }+// Reuse the shared Spotlight-backed catalog (names + bundle ids, all the- // standard search roots) instead of a duplicated directory scan.- let installed = MacLocalAppAvailabilityProvider.installedApplications()+ // standard search roots — including /System/Applications, so Apple native+ // apps are present) instead of a duplicated directory scan.+ let installedAll = cachedInstalledApplications().filter { passesFilter($0.appName) || ($0.bundleIdentifier.map(passesFilter) ?? false) }.map { candidate -> String inguard let bundleID = candidate.bundleIdentifier, !bundleID.isEmpty else { return candidate.appName }@@ -53,23 +97,82 @@ public enum DonkeyCommandBackends {}.sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending }+ let installedTotal = installedAll.count+ let pageStart = min(offset, installedTotal)+ // Build the page so what we COUNT is exactly what we EMIT: take up to `limit`+ // names from `pageStart`, but stop early if the joined text would exceed the+ // response budget. `nextOffset`/`hasMore` then describe the real emitted page,+ // not an over-counted slice the response cap would have silently truncated.+ let (installedPage, installedText) = pagedNames(+ installedAll, start: pageStart, maxCount: limit, charBudget: appsResponseCharBudget+ )+ let pageEnd = pageStart + installedPage.count+ let hasMore = pageEnd < installedTotal+ let nextOffset = hasMore ? pageEnd : nil+let running = NSWorkspace.shared.runningApplications.filter { $0.activationPolicy == .regular }.compactMap(\.localizedName).filter(passesFilter).sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending }+ // Self-describing page header so the model can chain pages from the+ // result text alone, without re-deriving the input schema.+ let rangeText = installedTotal == 0+ ? "Installed (0)"+ : "Installed \(pageStart + 1)–\(pageEnd) of \(installedTotal)"+ let moreText = nextOffset.map { " — more available, call apps_list again with offset=\($0) (same filter) for the next page" } ?? ""++ var metadata: [String: String] = [+ "installed": installedText,+ "running": capped(running),+ "installedTotal": String(installedTotal),+ "offset": String(pageStart),+ "limit": String(limit),+ "returned": String(installedPage.count),+ "hasMore": hasMore ? "true" : "false"+ ]+ if let nextOffset { metadata["nextOffset"] = String(nextOffset) }+ if let filter = trimmed(context.call.input["filter"]) { metadata["filter"] = filter }+return success(context,- summary: "Installed (\(installed.count)): \(capped(installed))\nRunning (\(running.count)): \(capped(running))",- facts: ["installedAppCount": String(installed.count)],- metadata: [- "installed": capped(installed),- "running": capped(running)- ]+ summary: "\(rangeText)\(moreText): \(installedText)\nRunning (\(running.count)): \(capped(running))",+ facts: [+ "installedAppCount": String(installedTotal),+ "installedReturnedCount": String(installedPage.count)+ ],+ metadata: metadata)}+ /// Take up to `maxCount` names starting at `start`, stopping early if the joined+ /// text would exceed `charBudget`, and return the names actually taken alongside+ /// their joined string. The returned count is authoritative: callers derive+ /// `returned`/`hasMore`/`nextOffset` from it so the page header can't claim more+ /// than was emitted. At least one name is always taken (so paging makes progress+ /// even if a single name exceeds the budget).+ private static func pagedNames(+ _ names: [String],+ start: Int,+ maxCount: Int,+ charBudget: Int+ ) -> (page: [String], joined: String) {+ var page: [String] = []+ var joinedLength = 0+ var index = start+ while index < names.count, page.count < maxCount {+ let name = names[index]+ let separatorLength = page.isEmpty ? 0 : 2 // ", "+ let projected = joinedLength + separatorLength + name.count+ if !page.isEmpty, projected > charBudget { break }+ page.append(name)+ joinedLength = projected+ index += 1+ }+ return (page, page.joined(separator: ", "))+ }+/// Join names, capped so the model response stays bounded.private static func capped(_ names: [String], limit: Int = 3_000) -> String {var result = ""@@ -83,11 +186,11 @@ public enum DonkeyCommandBackends {return result}- // MARK: - music.play+ // MARK: - music_playprivate static func playMusic(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {guard trimmed(context.call.input["query"]) != nil else {- return invalidInput(context, "music.play requires a `query`.")+ return invalidInput(context, "music_play requires a `query`.")}guard let artifact = LocalAppUserQueryHarnessServices.builtInValidatedScriptArtifacts()diff --git a/apps/Donkey/Sources/DonkeyRuntime/ScreenshotAnnotation.swift b/apps/Donkey/Sources/DonkeyRuntime/ScreenshotAnnotation.swiftnew file mode 100644index 00000000..6ea2d7f1--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/ScreenshotAnnotation.swift@@ -0,0 +1,112 @@+import AppKit+import CoreGraphics+import Foundation+import ImageIO+import UniformTypeIdentifiers++/// Renders the box-based vision flow's decision onto a captured screenshot so a+/// human can verify it: the returned bounding box plus the ordered click points+/// (box center larger, the nearby fallback points smaller) and a short label.+/// Reuses the same `CGContext` + `CGImageDestination` drawing pattern as the debug+/// UI inspection sidecar, including the top-left↔bottom-left y-flip, and derives the+/// rect/points from `VisionBoxGeometry` so the drawing matches what gets clicked.+public enum ScreenshotAnnotation {+ public static func annotatedPNG(+ screenshot: CapturedWindowScreenshot,+ box: [Double],+ label: String+ ) -> Data? {+ annotatedPNG(pngData: screenshot.pngData, box: box, label: label)+ }++ public static func annotatedPNG(pngData: Data, box: [Double], label: String) -> Data? {+ guard let source = CGImageSourceCreateWithData(pngData as CFData, nil),+ let image = CGImageSourceCreateImageAtIndex(source, 0, nil)+ else { return nil }++ let width = image.width+ let height = image.height+ guard let context = CGContext(+ data: nil,+ width: width,+ height: height,+ bitsPerComponent: 8,+ bytesPerRow: 0,+ space: CGColorSpaceCreateDeviceRGB(),+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue+ ) else { return nil }++ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))++ // Screenshot pixels are top-left origin; CGContext is bottom-left → flip y.+ func flip(_ point: CGPoint) -> CGPoint {+ CGPoint(x: point.x, y: Double(height) - point.y)+ }++ if let rect = VisionBoxGeometry.pixelRect(box, imageWidth: width, imageHeight: height) {+ let drawRect = CGRect(+ x: rect.minX,+ y: Double(height) - rect.minY - rect.height,+ width: rect.width,+ height: rect.height+ )+ context.setLineWidth(3)+ context.setStrokeColor(NSColor.systemRed.cgColor)+ context.setFillColor(NSColor.systemRed.withAlphaComponent(0.12).cgColor)+ context.fill(drawRect)+ context.stroke(drawRect)++ if !label.isEmpty {+ let labelHeight: CGFloat = 18+ let labelRect = CGRect(+ x: drawRect.minX,+ y: min(CGFloat(height) - labelHeight - 2, drawRect.maxY),+ width: min(CGFloat(width) - drawRect.minX - 2, max(60, CGFloat(label.count) * 6.7 + 10)),+ height: labelHeight+ )+ context.setFillColor(NSColor.systemRed.withAlphaComponent(0.85).cgColor)+ context.fill(labelRect)+ let nsContext = NSGraphicsContext(cgContext: context, flipped: false)+ NSGraphicsContext.saveGraphicsState()+ NSGraphicsContext.current = nsContext+ (label as NSString).draw(+ in: labelRect.insetBy(dx: 4, dy: 2),+ withAttributes: [+ .foregroundColor: NSColor.white,+ .font: NSFont.systemFont(ofSize: 10, weight: .semibold)+ ]+ )+ NSGraphicsContext.restoreGraphicsState()+ }+ }++ let points = VisionBoxGeometry.pixelPoints(box, imageWidth: width, imageHeight: height)+ for (index, point) in points.enumerated() {+ let radius: CGFloat = index == 0 ? 9 : 5+ let center = flip(point)+ let dot = CGRect(+ x: center.x - radius,+ y: center.y - radius,+ width: radius * 2,+ height: radius * 2+ )+ context.setFillColor((index == 0 ? NSColor.systemYellow : NSColor.systemGreen).withAlphaComponent(0.9).cgColor)+ context.setStrokeColor(NSColor.black.cgColor)+ context.setLineWidth(1.5)+ context.fillEllipse(in: dot)+ context.strokeEllipse(in: dot)+ }++ guard let output = context.makeImage() else { return nil }+ let data = NSMutableData()+ guard let destination = CGImageDestinationCreateWithData(+ data,+ UTType.png.identifier as CFString,+ 1,+ nil+ ) else { return nil }+ CGImageDestinationAddImage(destination, output, nil)+ guard CGImageDestinationFinalize(destination) else { return nil }+ return data as Data+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/ScreenshotChange.swift b/apps/Donkey/Sources/DonkeyRuntime/ScreenshotChange.swiftnew file mode 100644index 00000000..51bbc28e--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/ScreenshotChange.swift@@ -0,0 +1,56 @@+import CoreGraphics+import Foundation+import ImageIO++/// Cheap "did the screen change" probe for the box-based vision flow. Between the+/// in-turn click attempts (box center, then nearby points) we need to know whether+/// a click landed — without a model round-trip. We downscale both PNGs to a small+/// grayscale thumbnail and compare mean absolute pixel difference, which ignores+/// the cursor and minor rendering noise while still catching a real UI change.+public enum ScreenshotChange {+ /// True when two PNG screenshots differ by more than `threshold` (mean absolute+ /// difference, 0–1) over a small grayscale thumbnail. If either image can't be+ /// decoded, returns true so the caller doesn't get stuck assuming "no change".+ public static func changed(+ _ before: Data,+ _ after: Data,+ threshold: Double = 0.02,+ sampleDimension: Int = 32+ ) -> Bool {+ guard let a = grayscale(before, dimension: sampleDimension),+ let b = grayscale(after, dimension: sampleDimension),+ a.count == b.count, !a.isEmpty+ else { return true }+ var total = 0.0+ for index in a.indices {+ total += abs(Double(a[index]) - Double(b[index]))+ }+ let mean = total / Double(a.count) / 255.0+ return mean > threshold+ }++ private static func grayscale(_ png: Data, dimension: Int) -> [UInt8]? {+ guard let source = CGImageSourceCreateWithData(png as CFData, nil),+ let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [+ kCGImageSourceCreateThumbnailFromImageAlways: true,+ kCGImageSourceCreateThumbnailWithTransform: true,+ kCGImageSourceThumbnailMaxPixelSize: dimension+ ] as CFDictionary)+ else { return nil }+ let width = image.width+ let height = image.height+ guard width > 0, height > 0 else { return nil }+ var buffer = [UInt8](repeating: 0, count: width * height)+ guard let context = CGContext(+ data: &buffer,+ width: width,+ height: height,+ bitsPerComponent: 8,+ bytesPerRow: width,+ space: CGColorSpaceCreateDeviceGray(),+ bitmapInfo: CGImageAlphaInfo.none.rawValue+ ) else { return nil }+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))+ return buffer+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/VisionBoxGeometry.swift b/apps/Donkey/Sources/DonkeyRuntime/VisionBoxGeometry.swiftnew file mode 100644index 00000000..2d259488--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/VisionBoxGeometry.swift@@ -0,0 +1,74 @@+import CoreGraphics+import DonkeyContracts+import Foundation++/// Geometry for the box-based vision flow. The vision model returns the target as+/// a 2D bounding box in Gemini's convention — `box = [ymin, xmin, ymax, xmax]` in+/// the native 0–1000 normalized space (independent of the screenshot's pixel size,+/// the same property `VisionActionPlanner.screenPoint` relies on). This is the one+/// source of truth shared by clicking (box → screen points) and drawing+/// (box → screenshot-pixel rect/points), so what we click always matches what we+/// annotate.+public enum VisionBoxGeometry {+ public static let normalizedScale = 1_000.0++ /// Ordered click offsets within the target box, as fractions of the box+ /// (fx, fy in [0,1]) — center first, then four inner points. All sit inside the+ /// inner 40% so they remain on the control even when the box is slightly loose.+ public static let clickFractions: [(fx: Double, fy: Double)] = [+ (0.5, 0.5), (0.5, 0.3), (0.5, 0.7), (0.3, 0.5), (0.7, 0.5)+ ]++ /// Validate + unpack a `[ymin, xmin, ymax, xmax]` box. Returns nil if it is the+ /// wrong length or has zero area.+ public static func bounds(+ _ box: [Double]+ ) -> (xmin: Double, ymin: Double, xmax: Double, ymax: Double)? {+ guard box.count == 4 else { return nil }+ let ymin = min(box[0], box[2])+ let xmin = min(box[1], box[3])+ let ymax = max(box[0], box[2])+ let xmax = max(box[1], box[3])+ guard xmax > xmin, ymax > ymin else { return nil }+ return (xmin, ymin, xmax, ymax)+ }++ /// Box → ordered normalized (0–1) image points, center first.+ public static func normalizedPoints(_ box: [Double]) -> [(nx: Double, ny: Double)] {+ guard let b = bounds(box) else { return [] }+ return clickFractions.map { fraction in+ let nx = (b.xmin + fraction.fx * (b.xmax - b.xmin)) / normalizedScale+ let ny = (b.ymin + fraction.fy * (b.ymax - b.ymin)) / normalizedScale+ return (min(max(nx, 0), 1), min(max(ny, 0), 1))+ }+ }++ /// Box → ordered real-screen points for clicking (center first), using the same+ /// `window.x + nx * window.width` mapping as `VisionActionPlanner.screenPoint`.+ public static func screenPoints(_ box: [Double], window: WindowTargetBounds) -> [CGPoint] {+ normalizedPoints(box).map { point in+ CGPoint(+ x: window.x + point.nx * window.width,+ y: window.y + point.ny * window.height+ )+ }+ }++ /// Box → screenshot-pixel rect (top-left origin) for drawing.+ public static func pixelRect(_ box: [Double], imageWidth: Int, imageHeight: Int) -> CGRect? {+ guard let b = bounds(box) else { return nil }+ return CGRect(+ x: b.xmin / normalizedScale * Double(imageWidth),+ y: b.ymin / normalizedScale * Double(imageHeight),+ width: (b.xmax - b.xmin) / normalizedScale * Double(imageWidth),+ height: (b.ymax - b.ymin) / normalizedScale * Double(imageHeight)+ )+ }++ /// Box → ordered screenshot-pixel points (top-left origin, center first) for drawing.+ public static func pixelPoints(_ box: [Double], imageWidth: Int, imageHeight: Int) -> [CGPoint] {+ normalizedPoints(box).map { point in+ CGPoint(x: point.nx * Double(imageWidth), y: point.ny * Double(imageHeight))+ }+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swiftindex 72855025..3d92ece0 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GeminiLiveTests.swift@@ -1,3 +1,4 @@+@testable import Donkeyimport DonkeyAIimport DonkeyHarnessimport Foundation@@ -32,14 +33,81 @@ struct GeminiLiveTests {#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" }+ // 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 commandNamesAreValidFunctionCallIdentifiers() {+ // Gemini/Vertex Live rejects dots in function names and normalizes them+ // (e.g. `apps.list` → `apps_list`), so a dotted name would never dispatch.+ // Every Command Layer name must be a plain `[A-Za-z_][A-Za-z0-9_]*` id.+ for command in DonkeyCommandLayer.Command.allCases {+ let name = command.rawValue+ #expect(!name.isEmpty)+ let allowed = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_")+ #expect(+ name.unicodeScalars.allSatisfy(allowed.contains),+ "command name \(name) is not a valid LLM function identifier"+ )+ let first = name.unicodeScalars.first!+ #expect(+ !CharacterSet(charactersIn: "0123456789").contains(first),+ "command name \(name) must not start with a digit"+ )+ }+ }++ @Test+ func developerAPIProviderUsesKeyModelAndAudioOutput() async throws {+ // GEMINI_API_KEY → connect directly to the Developer API with the key in+ // the query string, the configured model, and AUDIO output (gemini-3.1+ // Live is audio-only).+ let config = GeminiLiveConfiguration.fromEnvironment([+ "GEMINI_API_KEY": "test-key-123",+ "GEMINI_LIVE_MODEL": "gemini-3.1-flash-live-preview"+ ])+ #expect(config.apiKey == "test-key-123")+ #expect(config.model == "gemini-3.1-flash-live-preview")++ let connection = try await GeminiLiveConnectionFactory.makeProvider(configuration: config)()+ #expect(connection.bearerToken == nil)+ #expect(connection.audioOutput)+ #expect(connection.model == "gemini-3.1-flash-live-preview")+ #expect(connection.url.absoluteString.contains("generativelanguage.googleapis.com"))+ #expect(connection.url.query?.contains("key=test-key-123") == true)+ }++ @Test+ func configDefaultsToLive25AndVision35() {+ // Command Live model defaults to a 2.5 model; the turn-based vision model+ // defaults to the stronger gemini-3.5-flash.+ #expect(GeminiLiveConfiguration.defaultModel.contains("2.5"))+ #expect(GeminiLiveConfiguration.defaultVisionModel == "gemini-3.5-flash")+ let defaults = GeminiLiveConfiguration.fromEnvironment([:])+ #expect(defaults.apiKey == nil)+ #expect(defaults.model == GeminiLiveConfiguration.defaultModel)+ #expect(defaults.visionModel == "gemini-3.5-flash")+ // GEMINI_VISION_MODEL overrides the vision model.+ let overridden = GeminiLiveConfiguration.fromEnvironment(["GEMINI_VISION_MODEL": "gemini-2.5-pro"])+ #expect(overridden.visionModel == "gemini-2.5-pro")+ }++ @Test+ @MainActor+ func canonicalToolNameStripsGeminiPrefixes() {+ // Gemini sometimes namespaces tool-call names; dispatch must match the+ // declared name (this regressed vision_control → `default_vision_control`).+ #expect(GeminiLiveVoiceController.canonicalToolName("vision_control") == "vision_control")+ #expect(GeminiLiveVoiceController.canonicalToolName("default_vision_control") == "vision_control")+ #expect(GeminiLiveVoiceController.canonicalToolName("default_api.music_play") == "music_play")+ #expect(GeminiLiveVoiceController.canonicalToolName("apps_list") == "apps_list")+ }+@Testfunc pcm16ResamplesAndPacksLittleEndian() {// 48kHz → 16kHz is a 3:1 decimation.diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex 3cb7b549..a525087f 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -416,15 +416,20 @@ struct GenericHarnessTests {services: HarnessBuiltInToolServices(commandExecutor: DonkeyCommandBackends.makeExecutor()))- // apps.list is read-only discovery and always succeeds.+ // apps_list is read-only discovery and always succeeds.let apps = await registry.execute(- HarnessToolCall(id: "apps-1", name: "apps.list"),+ HarnessToolCall(id: "apps-1", name: "apps_list"),taskID: "task-apps",worldModel: HarnessWorldModel(),grantedPermissions: [.appLookup])#expect(apps.status == .succeeded)#expect(apps.metadata["installed"] != nil)+ // Default call reports pagination state so the model can page if needed.+ #expect(apps.metadata["installedTotal"] != nil)+ #expect(apps.metadata["offset"] == "0")+ #expect(apps.metadata["limit"] == "50")+ #expect(apps.metadata["hasMore"] != nil)// shell_exec with no command is rejected without side effects.let emptyShell = await registry.execute(@@ -446,6 +451,61 @@ struct GenericHarnessTests {#expect(unknown.status == .unknownTool)}+ @Test+ func appsListPaginatesInstalledAppsAndValidatesInputs() async {+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(commandExecutor: DonkeyCommandBackends.makeExecutor())+ )++ // A single-item page never returns more than `limit`, and surfaces a+ // `nextOffset` to continue paging whenever the catalog is larger.+ let firstPage = await registry.execute(+ HarnessToolCall(id: "apps-page-1", name: "apps_list", input: ["offset": "0", "limit": "1"]),+ taskID: "task-apps-page-1",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ #expect(firstPage.status == .succeeded)+ #expect(firstPage.metadata["limit"] == "1")+ #expect(firstPage.metadata["offset"] == "0")+ let returned = Int(firstPage.metadata["returned"] ?? "") ?? -1+ #expect(returned >= 0 && returned <= 1)+ let total = Int(firstPage.metadata["installedTotal"] ?? "") ?? -1+ if total > 1 {+ #expect(firstPage.metadata["hasMore"] == "true")+ #expect(firstPage.metadata["nextOffset"] == "1")+ }++ // Out-of-range offsets clamp to an empty page rather than crashing.+ let pastEnd = await registry.execute(+ HarnessToolCall(id: "apps-page-end", name: "apps_list", input: ["offset": "100000", "limit": "10"]),+ taskID: "task-apps-page-end",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ #expect(pastEnd.status == .succeeded)+ #expect(pastEnd.metadata["returned"] == "0")+ #expect(pastEnd.metadata["hasMore"] == "false")+ #expect(pastEnd.metadata["nextOffset"] == nil)++ // Malformed pagination inputs are rejected with actionable feedback.+ let badOffset = await registry.execute(+ HarnessToolCall(id: "apps-bad-offset", name: "apps_list", input: ["offset": "-1"]),+ taskID: "task-apps-bad-offset",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ #expect(badOffset.status == .invalidInput)++ let badLimit = await registry.execute(+ HarnessToolCall(id: "apps-bad-limit", name: "apps_list", input: ["limit": "0"]),+ taskID: "task-apps-bad-limit",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ #expect(badLimit.status == .invalidInput)+ }+@Testfunc shellExecRunsSafeCommandsAndBlocksDangerousOnes() async {let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionBoxGeometryTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionBoxGeometryTests.swiftnew file mode 100644index 00000000..2b5f19be--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionBoxGeometryTests.swift@@ -0,0 +1,76 @@+import CoreGraphics+import DonkeyContracts+import DonkeyRuntime+import Foundation+import ImageIO+import Testing+import UniformTypeIdentifiers++/// Deterministic, offline coverage for the box-based vision geometry and the+/// in-turn change probe. The live grounding quality is verified separately by+/// `GeminiLiveVisionBoxSpotifySmokeTests` (which saves annotated PNGs for review).+@Suite+struct VisionBoxGeometryTests {+ // box = [ymin, xmin, ymax, xmax] in 0–1000 space.+ private let box: [Double] = [100, 200, 300, 600]++ @Test+ func clickPointsAreCenterFirst() {+ // window maps 0–1000 normalized directly onto 0–1000 screen units here.+ let window = WindowTargetBounds(x: 0, y: 0, width: 1_000, height: 1_000)+ let points = VisionBoxGeometry.screenPoints(box, window: window)+ #expect(points.count == 5)+ // Box center: x = 200 + 0.5*400 = 400; y = 100 + 0.5*200 = 200.+ #expect(points[0] == CGPoint(x: 400, y: 200))+ // All points lie inside the box rect (200…600, 100…300).+ for point in points {+ #expect(point.x >= 200 && point.x <= 600)+ #expect(point.y >= 100 && point.y <= 300)+ }+ }++ @Test+ func screenPointsRespectWindowOffsetAndSize() {+ let window = WindowTargetBounds(x: 100, y: 50, width: 800, height: 600)+ let center = VisionBoxGeometry.screenPoints(box, window: window)[0]+ // nx = 400/1000 = 0.4 → 100 + 0.4*800 = 420; ny = 200/1000 = 0.2 → 50 + 0.2*600 = 170.+ #expect(center == CGPoint(x: 420, y: 170))+ }++ @Test+ func pixelRectScalesToImage() {+ let rect = VisionBoxGeometry.pixelRect(box, imageWidth: 1_000, imageHeight: 1_000)+ #expect(rect == CGRect(x: 200, y: 100, width: 400, height: 200))+ }++ @Test+ func malformedBoxYieldsNoPoints() {+ #expect(VisionBoxGeometry.screenPoints([1, 2, 3], window: WindowTargetBounds(x: 0, y: 0, width: 10, height: 10)).isEmpty)+ #expect(VisionBoxGeometry.bounds([100, 200, 100, 200]) == nil) // zero area+ }++ @Test+ func changeProbeDistinguishesIdenticalFromDifferent() {+ let black = solidPNG(gray: 0)+ let white = solidPNG(gray: 255)+ #expect(ScreenshotChange.changed(black, black) == false)+ #expect(ScreenshotChange.changed(black, white) == true)+ }++ /// A 16x16 solid-gray PNG for the change probe.+ private func solidPNG(gray: UInt8, side: Int = 16) -> Data {+ let value = CGFloat(gray) / 255+ let context = CGContext(+ data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: 0,+ space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue+ )!+ context.setFillColor(CGColor(red: value, green: value, blue: value, alpha: 1))+ context.fill(CGRect(x: 0, y: 0, width: side, height: side))+ let image = context.makeImage()!+ let data = NSMutableData()+ let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)!+ CGImageDestinationAddImage(destination, image, nil)+ _ = CGImageDestinationFinalize(destination)+ return data as Data+ }+}diff --git a/site/.env.example b/site/.env.exampleindex d7c580a9..e7759845 100644--- a/site/.env.example+++ b/site/.env.example@@ -17,3 +17,9 @@ ELEVENLABS_API_KEY="replace-with-elevenlabs-api-key"# Required for Gemini / Google Cloud inference through Vertex AI. The adapter# uses the global endpoint and derives the project from project_id.GOOGLE_APPLICATION_CREDENTIALS_JSON='{"type":"service_account",...}'++# Dev-only: a Gemini Developer API key. When set, the Live client connects+# directly to the Developer API (using GEMINI_LIVE_MODEL; the client default is an+# audio-output-only model) instead of minting a Vertex token. Production uses the+# keyless Vertex path above.+GEMINI_API_KEY="replace-with-gemini-api-key"diff --git a/site/src/lib/inference/vertex-live.ts b/site/src/lib/inference/vertex-live.tsindex 1b298839..dd923683 100644--- a/site/src/lib/inference/vertex-live.ts+++ b/site/src/lib/inference/vertex-live.ts@@ -4,9 +4,11 @@ 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";+// The backend owns the Live model id (the client never selects it). Override+// with GEMINI_LIVE_MODEL. `gemini-live-2.5-flash` is the model that resolves on+// Vertex AI in the `global` location and accepts the BidiGenerateContent setup+// (verified end-to-end via GeminiLiveCommandSessionLiveSmokeTests).+const defaultLiveModel = "gemini-live-2.5-flash";type AdapterEnvironment = Record<string, string | undefined>;