Open source CapCut alternative.
TypeScript
feat(app): drive apps in the background without stealing cursor or focus
David Lef13bb2b330d5
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 1173eaa6..0b43081a 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -387,14 +387,30 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {let registry = HarnessToolRegistry(tools: BuiltInHarnessToolExecutors.tools(descriptors: builtInDescriptors, services: harnessServices))- let axProvider = AXComputerUseToolProvider(appName: appName, bundleIdentifier: bundleIdentifier)+ // Background is the default operating mode: the agent acts on a safe, on-active-Space window+ // without raising the app or moving the cursor — the AX action lane for advertised controls, the+ // pid-routed event-post lane for coordinate/scroll/drag/keystroke input. The understanding+ // boundary flips this to foreground only when the turn's point is for the user to watch. When+ // understanding is unavailable we still default to background (each lane degrades to foreground on+ // its own when an action can't be delivered that way).+ let executionPreference = understanding?.executionPreference ?? .background+ let axProvider = AXComputerUseToolProvider(+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ executionPreference: executionPreference+ )let visionProvider = VisionComputerUseToolProvider(appName: appName,appKey: appKey,bundleIdentifier: bundleIdentifier,+ executionPreference: executionPreference,analyzer: analyzer)- let pointerProvider = PointerComputerUseToolProvider(appName: appName, bundleIdentifier: bundleIdentifier)+ let pointerProvider = PointerComputerUseToolProvider(+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ executionPreference: executionPreference+ )// Native music playback (MusicKit): search/play/transport/status with no Music-app GUI or// AppleScript. Declares no harness permissions — MusicKit runs its own consent flow.let musicProvider = MusicPlaybackToolProvider(service: MusicKitPlaybackService())@@ -475,6 +491,13 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {}VisionGroundingLog.emit("thread traceID=\(traceID) path=\(transcript.threadPath)")+ // On a background turn the agent acts without taking over the user's cursor, so the cosmetic+ // traveling cursor is suppressed and progress is narrated through the notch text only. (AX-lane+ // background actions already report no screen point, so they produce no cursor plan; this also+ // covers background coordinate/scroll/drag posts, which move no real pointer.) The overlay never+ // drives real input either way — realPointerMoved stays false.+ let suppressBackgroundCursorPlayback = (understanding?.executionPreference ?? .background) == .background+// Always set onStep so every turn is recorded; the overlay narration/cursor is layered on top// when a UI is attached.let onStep: (@Sendable (HarnessStepExecutionResult) async -> Void)? = { (step: HarnessStepExecutionResult) async -> Void in@@ -521,6 +544,9 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// builds; this escape hatch turns the playback off (text narration still updates) so a// run can proceed without it.guard !Self.cursorVisualizationDisabled else { return }+ // Background turns narrate through the notch only; no traveling cursor on a window the+ // user isn't driving. Text narration above still fires every step.+ guard !suppressBackgroundCursorPlayback else { return }guard let present = visualize else { return }let screenSize = (NSScreen.main ?? NSScreen.screens.first)?.frame.size ?? .zeroguard let plan = Self.cursorVisualizationPlan(diff --git a/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swiftindex aaf29e4d..bdaaa654 100644--- a/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift@@ -22,10 +22,16 @@ public final class PointerComputerUseToolProvider {private let appName: Stringprivate let bundleIdentifier: String?+ private let executionPreference: ExecutionPreference- public init(appName: String, bundleIdentifier: String?) {+ public init(+ appName: String,+ bundleIdentifier: String?,+ executionPreference: ExecutionPreference = .foreground+ ) {self.appName = appNameself.bundleIdentifier = bundleIdentifier+ self.executionPreference = executionPreference}public static var descriptors: [HarnessToolDescriptor] {@@ -83,9 +89,10 @@ public final class PointerComputerUseToolProvider {guard ["up", "down", "left", "right"].contains(direction) else {return result(context, status: .invalidInput, summary: "mouse.scroll requires direction up, down, left, or right.", reason: "invalidDirection")}- guard let target = await frontmostTarget() else {+ guard let routing = await resolveRouting() else {return notFrontmost(context)}+ let target = routing.targetlet point: CGPointif let elementID = context.call.input["elementID"], !elementID.isEmpty {guard let element = context.worldModel.elements.first(where: { $0.id == elementID }),@@ -107,7 +114,7 @@ public final class PointerComputerUseToolProvider {case "left": (deltaX, deltaY) = (amount, 0)default: (deltaX, deltaY) = (-amount, 0)}- MacPointerInput.scroll(at: point, deltaX: deltaX, deltaY: deltaY)+ MacPointerInput.scroll(at: point, deltaX: deltaX, deltaY: deltaY, target: routing.inputTarget)return HarnessToolResult(callID: context.call.id,toolName: context.call.name,@@ -123,9 +130,10 @@ public final class PointerComputerUseToolProvider {let toID = context.call.input["toElementID"], !toID.isEmpty else {return result(context, status: .invalidInput, summary: "mouse.drag requires fromElementID and toElementID.", reason: "missingElementIDs")}- guard let target = await frontmostTarget() else {+ guard let routing = await resolveRouting() else {return notFrontmost(context)}+ let target = routing.targetguard let fromElement = context.worldModel.elements.first(where: { $0.id == fromID }),let start = Self.screenPoint(for: fromElement, window: target.bounds) else {return result(context, status: .failed, summary: "Element \(fromID) has no resolvable position.", reason: "fromElementNotFound")@@ -134,7 +142,7 @@ public final class PointerComputerUseToolProvider {let end = Self.screenPoint(for: toElement, window: target.bounds) else {return result(context, status: .failed, summary: "Element \(toID) has no resolvable position.", reason: "toElementNotFound")}- MacPointerInput.drag(from: start, to: end)+ MacPointerInput.drag(from: start, to: end, target: routing.inputTarget)return HarnessToolResult(callID: context.call.id,toolName: context.call.name,@@ -173,14 +181,23 @@ public final class PointerComputerUseToolProvider {// MARK: - Helpers- /// Resolves the target window and ensures it is frontmost, attempting one recovery activation- /// of the target app (never any other app) when focus drifted between observe and act.- private func frontmostTarget() async -> MacWindowTargetCandidate? {- guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier),- await TargetFocusRecovery.ensureFrontmost(processID: pid_t(target.processID)) else {+ /// Resolves the target window and decides how to deliver input. On a background turn over a safe+ /// surface it returns a pinned target for cursor-neutral pid-routed delivery (no app raise);+ /// otherwise it brings the target frontmost (one recovery activation, never any other app) and+ /// returns a nil input target for the HID path. Returns nil only when a required activation failed.+ private func resolveRouting() async -> (target: MacWindowTargetCandidate, inputTarget: InputTarget?)? {+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {return nil}- return target+ switch TargetActionGuard.resolve(candidate: target, preference: executionPreference, lane: .pidEventPost) {+ case .background(let inputTarget):+ return (target, inputTarget)+ case .foreground:+ guard await TargetFocusRecovery.ensureFrontmost(processID: pid_t(target.processID)) else {+ return nil+ }+ return (target, nil)+ }}private func notFrontmost(_ context: HarnessToolExecutionContext) -> HarnessToolResult {diff --git a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swiftindex 74a07f51..cb3d9b16 100644--- a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift@@ -39,6 +39,7 @@ public final class VisionComputerUseToolProvider {let appName: Stringlet appKey: Stringlet bundleIdentifier: String?+ let executionPreference: ExecutionPreferencelet analyzer: any DebugUIInspectionAnalyzinglet store: ParsedVisionStore/// Fused accessibility + vision understanding kept warm by the always-on `UIUnderstandingCoordinator`.@@ -66,6 +67,7 @@ public final class VisionComputerUseToolProvider {appName: String,appKey: String,bundleIdentifier: String?,+ executionPreference: ExecutionPreference = .foreground,analyzer: any DebugUIInspectionAnalyzing,store: ParsedVisionStore = .shared,understandingStore: WindowUIUnderstandingStore = .shared,@@ -79,6 +81,7 @@ public final class VisionComputerUseToolProvider {self.appName = appNameself.appKey = appKeyself.bundleIdentifier = bundleIdentifier+ self.executionPreference = executionPreferenceself.analyzer = analyzerself.store = storeself.understandingStore = understandingStore@@ -388,9 +391,10 @@ public final class VisionComputerUseToolProvider {guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")}- guard await ensureFrontmost(target) else {+ guard let routing = await inputRouting(for: target) else {return notFrontmost(context)}+ let inputTarget = routing.inputTargetlet normalized = Self.normalizedCenter(bbox: geometry.bbox,imageWidth: geometry.imageWidth,@@ -408,7 +412,7 @@ public final class VisionComputerUseToolProvider {}let button: MacPointerInput.Button = context.call.input["button"] == "right" ? .right : .leftlet clicks = context.call.input["clicks"].flatMap(Int.init) ?? 1- MacPointerInput.moveAndClick(at: point, button: button, clickCount: clicks)+ MacPointerInput.moveAndClick(at: point, button: button, clickCount: clicks, target: inputTarget)let clickWord = button == .right ? "Right-clicked" : (clicks >= 3 ? "Triple-clicked" : (clicks == 2 ? "Double-clicked" : "Clicked"))return HarnessToolResult(callID: context.call.id,@@ -429,10 +433,10 @@ public final class VisionComputerUseToolProvider {return result(context, status: .invalidInput, summary: "text.enter requires non-empty text.", reason: "missingText")}guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier),- await ensureFrontmost(target) else {+ let routing = await inputRouting(for: target) else {return notFrontmost(context)}- MacKeyboardInput.type(text)+ MacKeyboardInput.type(text, target: routing.inputTarget)return HarnessToolResult(callID: context.call.id,toolName: context.call.name,@@ -448,11 +452,11 @@ public final class VisionComputerUseToolProvider {return result(context, status: .invalidInput, summary: "keyboard.press requires a key.", reason: "missingKey")}guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier),- await ensureFrontmost(target) else {+ let routing = await inputRouting(for: target) else {return notFrontmost(context)}let modifiers = trimmed(context.call.input["modifiers"]).map { [$0] } ?? []- MacKeyboardInput.pressKey(key, modifiers: modifiers)+ MacKeyboardInput.pressKey(key, modifiers: modifiers, target: routing.inputTarget)let chord = modifiers.first.map { "\($0)+\(key)" } ?? keyreturn HarnessToolResult(callID: context.call.id,@@ -576,6 +580,32 @@ public final class VisionComputerUseToolProvider {// MARK: - Helpers+ /// How input should reach the resolved target.+ private enum InputRouting {+ /// Deliver to the pinned target cursor-neutrally (no focus steal).+ case background(InputTarget)+ /// The target was brought frontmost; deliver via the HID tap as before.+ case foreground++ /// The pinned target for background delivery, or nil for the foreground HID path.+ var inputTarget: InputTarget? {+ if case .background(let target) = self { return target }+ return nil+ }+ }++ /// Decides how to deliver input to `target`: a pinned background target (no cursor move, no app+ /// raise) when the turn asked for background and the surface is safe, otherwise foreground after one+ /// recovery activation. Returns nil only when a required foreground activation failed.+ private func inputRouting(for target: MacWindowTargetCandidate) async -> InputRouting? {+ switch TargetActionGuard.resolve(candidate: target, preference: executionPreference, lane: .pidEventPost) {+ case .background(let inputTarget):+ return .background(inputTarget)+ case .foreground:+ return await ensureFrontmost(target) ? .foreground : nil+ }+ }+/// Frontmost check with one recovery activation of the target app (never any other app).private func ensureFrontmost(_ target: MacWindowTargetCandidate) async -> Bool {await TargetFocusRecovery.ensureFrontmost(processID: pid_t(target.processID))diff --git a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swiftindex 184a49d5..8e56264e 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift@@ -21,15 +21,18 @@ public final class AXComputerUseToolProvider {private let appName: Stringprivate let bundleIdentifier: String?+ private let executionPreference: ExecutionPreferenceprivate let actionBackend: ActionEngineInputBackendpublic init(appName: String,bundleIdentifier: String?,+ executionPreference: ExecutionPreference = .foreground,actionBackend: ActionEngineInputBackend = MacAccessibilityActionEngineInputBackend()) {self.appName = appNameself.bundleIdentifier = bundleIdentifier+ self.executionPreference = executionPreferenceself.actionBackend = actionBackend}@@ -149,6 +152,37 @@ public final class AXComputerUseToolProvider {guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")}+ let label = element.label.isEmpty ? elementID : element.label+ let button: MacPointerInput.Button = context.call.input["button"] == "right" ? .right : .left+ let clicks = context.call.input["clicks"].flatMap(Int.init) ?? 1+ let advertised = Set(element.actions)++ // Background Accessibility action first: AXUIElementPerformAction is a focus-neutral cross-process+ // RPC, so when the turn asked for background work, the surface is safe, and the control advertises+ // a semantic action, we act without raising the app or moving the cursor. Anything the background+ // lane can't drive (no advertised action, an unsafe surface, or a foreground turn) falls through to+ // the foreground path below, which is always available.+ if case .background(let inputTarget) = TargetActionGuard.resolve(+ candidate: target,+ preference: executionPreference,+ lane: .axAction+ ),+ let bundleIdentifier, !bundleIdentifier.isEmpty,+ let action = Self.semanticAction(button: button, clicks: clicks, advertised: advertised),+ await axPerform(nodeID: element.id, action: action, bundleIdentifier: bundleIdentifier, background: inputTarget) {+ return clickSucceeded(+ context,+ elementID: elementID,+ label: label,+ strategy: "ax-" + action.dropFirst(2).lowercased() + "-background",+ point: nil+ )+ }++ // Foreground path (unchanged behavior): activate the target, then prefer a native Accessibility+ // action — it works even when a coordinate click would miss (partially obscured, scrolled,+ // zero-size hit area) — and fall back to a guarded coordinate click on the frame center when no+ // semantic action applies, there's no bundle id, or the AX action doesn't land.guard await TargetFocusRecovery.ensureFrontmost(processID: pid_t(target.processID)) else {return result(context,@@ -157,19 +191,9 @@ public final class AXComputerUseToolProvider {reason: "targetNotFrontmost")}- let label = element.label.isEmpty ? elementID : element.label- let button: MacPointerInput.Button = context.call.input["button"] == "right" ? .right : .left- let clicks = context.call.input["clicks"].flatMap(Int.init) ?? 1-- // Prefer a native Accessibility action: it activates the control directly, so it works even when- // a coordinate click would miss (partially obscured, scrolled, zero-size hit area). Single- // left-click presses, right-click shows the context menu, and double-click opens — each only when- // the control advertises that action. Falls back to a guarded coordinate click on the frame- // center when no semantic action applies, there's no bundle id, or the AX action doesn't land.- let advertised = Set(element.actions)if let bundleIdentifier, !bundleIdentifier.isEmpty,let action = Self.semanticAction(button: button, clicks: clicks, advertised: advertised),- await axPerform(nodeID: element.id, action: action, bundleIdentifier: bundleIdentifier) {+ await axPerform(nodeID: element.id, action: action, bundleIdentifier: bundleIdentifier, background: nil) {return clickSucceeded(context,elementID: elementID,@@ -252,9 +276,26 @@ public final class AXComputerUseToolProvider {}/// Performs an AX `action` (e.g. `AXPress`, `AXShowMenu`, `AXOpen`) on the control identified by- /// `nodeID` via the action backend, which re-checks that `bundleIdentifier` is the frontmost app and- /// that the control still advertises the action before acting. Returns whether the action landed.- private func axPerform(nodeID: String, action: String, bundleIdentifier: String) async -> Bool {+ /// `nodeID` via the action backend. Foreground (`background: nil`) re-checks that `bundleIdentifier`+ /// is the frontmost app before acting; passing a pinned `background` target instead routes the RPC to+ /// that process id with no frontmost requirement. Either way the backend re-checks the live control+ /// still advertises the action. Returns whether the action landed.+ private func axPerform(+ nodeID: String,+ action: String,+ bundleIdentifier: String,+ background: InputTarget?+ ) async -> Bool {+ var metadata = [+ "accessibility.nodeID": nodeID,+ "accessibility.action": action,+ "bundleIdentifier": bundleIdentifier,+ "controlID": nodeID+ ]+ if let background {+ metadata["accessibility.executionMode"] = "background"+ metadata["accessibility.processID"] = String(background.processID)+ }let command = ActionEngineCommand(id: UUID().uuidString,traceID: "ax-click",@@ -264,12 +305,7 @@ public final class AXComputerUseToolProvider {wallClock: Date(),monotonicUptimeNanoseconds: DispatchTime.now().uptimeNanoseconds),- metadata: [- "accessibility.nodeID": nodeID,- "accessibility.action": action,- "bundleIdentifier": bundleIdentifier,- "controlID": nodeID- ]+ metadata: metadata)let outcome = await actionBackend.execute(command)return outcome.executed@@ -284,11 +320,21 @@ public final class AXComputerUseToolProvider {) -> HarnessToolResult {var metadata = ["elementID": elementID, "label": label, "inputStrategy": strategy]if let point { metadata["screenPoint"] = "\(Int(point.x)),\(Int(point.y))" }+ let viaAccessibility = strategy.hasPrefix("ax-")+ let inBackground = strategy.hasSuffix("-background")+ let summary: String+ if viaAccessibility {+ summary = inBackground+ ? "Pressed \(label) via Accessibility in the background."+ : "Pressed \(label) via Accessibility."+ } else {+ summary = "Clicked \(label)."+ }return HarnessToolResult(callID: context.call.id,toolName: context.call.name,status: .succeeded,- summary: strategy == "ax-press" ? "Pressed \(label) via Accessibility." : "Clicked \(label).",+ summary: summary,observations: HarnessObservationDelta(facts: ["lastAcceptedTool": context.call.name]),metadata: metadata)diff --git a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swiftindex 9d5ca944..53e2e00c 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift@@ -5,9 +5,14 @@ import Foundationimport OSLog/// Low-level keyboard input via CGEvent. Real input — gate behind explicit permission/guards.+///+/// Each entry point takes an optional `target`: with none (the default) the event posts to the HID tap+/// and lands on the frontmost app, exactly as before; with a background `InputTarget` it is delivered to+/// that process WITHOUT moving the cursor or stealing focus — via the SkyLight bridge when available,+/// else the public per-process post.public enum MacKeyboardInput {/// Types arbitrary text by posting per-character unicode key events.- public static func type(_ text: String) {+ public static func type(_ text: String, target: InputTarget? = nil) {guard let source = CGEventSource(stateID: .hidSystemState) else { return }// Post one event per Character, using its full UTF-16 representation. Characters outside the// Basic Multilingual Plane (emoji, CJK extensions, …) encode as a surrogate pair, so we send@@ -21,32 +26,44 @@ public enum MacKeyboardInput {else { continue }down.keyboardSetUnicodeString(stringLength: units.count, unicodeString: &units)up.keyboardSetUnicodeString(stringLength: units.count, unicodeString: &units)- down.post(tap: .cghidEventTap)- up.post(tap: .cghidEventTap)+ post(down, to: target)+ post(up, to: target)}}/// Posts a Return keypress (virtual key 36).- public static func pressReturn() {- pressKey("return")+ public static func pressReturn(target: InputTarget? = nil) {+ pressKey("return", target: target)}/// Posts a single named key (return, escape, tab, arrows, letters, …), optionally chorded with/// modifiers (e.g. Cmd+C). Unknown unmodified names that look like a single character are typed/// as text rather than silently firing the wrong key; truly unknown multi-char names fall back/// to Return so a "submit"-style intent still does something sane.- public static func pressKey(_ name: String, modifiers: [String] = []) {+ public static func pressKey(_ name: String, modifiers: [String] = [], target: InputTarget? = nil) {let normalized = name.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)let flags = eventFlags(for: modifiers)guard let keyCode = virtualKeyCode(for: normalized) else {if normalized.count == 1, flags.isEmpty {- type(name)+ type(name, target: target)} else {- postKey(36, flags: flags) // unknown key name → Return+ postKey(36, flags: flags, target: target) // unknown key name → Return}return}- postKey(keyCode, flags: flags)+ postKey(keyCode, flags: flags, target: target)+ }++ /// Delivers a built keyboard event: to the HID tap (frontmost) when `target` is nil, otherwise to the+ /// target process cursor-neutrally — SkyLight bridge first (adds the macOS-14 auth envelope), then the+ /// public per-process post. Never the HID tap for a background target, which would warp the cursor.+ private static func post(_ event: CGEvent, to target: InputTarget?) {+ guard let target else {+ event.post(tap: .cghidEventTap)+ return+ }+ if SkyLightEventPost.shared.postKey(event, toPid: target.processID) { return }+ event.postToPid(target.processID)}/// Maps typed modifier tokens (split on `+`, `,`, or whitespace) to CGEvent flags. Unknown@@ -69,7 +86,7 @@ public enum MacKeyboardInput {return flags}- private static func postKey(_ keyCode: CGKeyCode, flags: CGEventFlags = []) {+ private static func postKey(_ keyCode: CGKeyCode, flags: CGEventFlags = [], target: InputTarget? = nil) {guard let source = CGEventSource(stateID: .hidSystemState),let down = CGEvent(keyboardEventSource: source, virtualKey: keyCode, keyDown: true),let up = CGEvent(keyboardEventSource: source, virtualKey: keyCode, keyDown: false)@@ -78,8 +95,8 @@ public enum MacKeyboardInput {down.flags = flagsup.flags = flags}- down.post(tap: .cghidEventTap)- up.post(tap: .cghidEventTap)+ post(down, to: target)+ post(up, to: target)}static func virtualKeyCode(for name: String) -> CGKeyCode? {@@ -119,6 +136,11 @@ public enum MacKeyboardInput {/// Low-level pointer input via CGEvent (move, click variants, scroll, drag at screen points). Real/// input — callers must gate this behind explicit permission/guards.+///+/// Each entry point takes an optional `target`: with none (the default) events post to the HID tap and+/// the real cursor moves to the point, exactly as before; with a background `InputTarget` the leading+/// cursor move is skipped and events are delivered to that process cursor-neutrally — via the SkyLight+/// bridge (which stamps a window-local hit-test point) when available, else the public per-process post.public enum MacPointerInput {public enum Button: String, Sendable {case left@@ -126,10 +148,14 @@ public enum MacPointerInput {}@discardableResult- public static func moveAndClick(at point: CGPoint, button: Button = .left, clickCount: Int = 1) -> Bool {+ public static func moveAndClick(at point: CGPoint, button: Button = .left, clickCount: Int = 1, target: InputTarget? = nil) -> Bool {guard let source = CGEventSource(stateID: .hidSystemState) else { return false }- CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left)?- .post(tap: .cghidEventTap)+ // Foreground moves the real cursor to the point first; background delivery is pid-routed and+ // never warps the cursor, so the move is skipped.+ if target == nil {+ CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left)?+ .post(tap: .cghidEventTap)+ }let mouseButton: CGMouseButton = button == .right ? .right : .leftlet downType: CGEventType = button == .right ? .rightMouseDown : .leftMouseDownlet upType: CGEventType = button == .right ? .rightMouseUp : .leftMouseUp@@ -144,20 +170,22 @@ public enum MacPointerInput {}down.setIntegerValueField(.mouseEventClickState, value: Int64(clickState))up.setIntegerValueField(.mouseEventClickState, value: Int64(clickState))- down.post(tap: .cghidEventTap)- up.post(tap: .cghidEventTap)+ post(down, screenPoint: point, to: target)+ post(up, screenPoint: point, to: target)}return true}/// Scrolls by line deltas at a screen point (positive y scrolls up, positive x scrolls left,- /// matching CGEvent wheel conventions). Moves the pointer there first so the scroll lands on- /// the intended view.+ /// matching CGEvent wheel conventions). Moves the pointer there first (foreground only) so the+ /// scroll lands on the intended view.@discardableResult- public static func scroll(at point: CGPoint, deltaX: Int = 0, deltaY: Int = 0) -> Bool {+ public static func scroll(at point: CGPoint, deltaX: Int = 0, deltaY: Int = 0, target: InputTarget? = nil) -> Bool {guard let source = CGEventSource(stateID: .hidSystemState) else { return false }- CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left)?- .post(tap: .cghidEventTap)+ if target == nil {+ CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left)?+ .post(tap: .cghidEventTap)+ }guard let event = CGEvent(scrollWheelEvent2Source: source,units: .line,@@ -169,21 +197,23 @@ public enum MacPointerInput {return false}event.location = point- event.post(tap: .cghidEventTap)+ post(event, screenPoint: point, to: target)return true}/// Drags from one screen point to another: press, interpolated dragged moves so drop targets/// see continuous motion, then release at the destination.@discardableResult- public static func drag(from start: CGPoint, to end: CGPoint, steps: Int = 16) -> Bool {+ public static func drag(from start: CGPoint, to end: CGPoint, steps: Int = 16, target: InputTarget? = nil) -> Bool {guard let source = CGEventSource(stateID: .hidSystemState) else { return false }- CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: start, mouseButton: .left)?- .post(tap: .cghidEventTap)+ if target == nil {+ CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: start, mouseButton: .left)?+ .post(tap: .cghidEventTap)+ }guard let down = CGEvent(mouseEventSource: source, mouseType: .leftMouseDown, mouseCursorPosition: start, mouseButton: .left) else {return false}- down.post(tap: .cghidEventTap)+ post(down, screenPoint: start, to: target)usleep(40_000)let stepCount = max(steps, 2)for step in 1...stepCount {@@ -192,17 +222,40 @@ public enum MacPointerInput {x: start.x + (end.x - start.x) * fraction,y: start.y + (end.y - start.y) * fraction)- CGEvent(mouseEventSource: source, mouseType: .leftMouseDragged, mouseCursorPosition: point, mouseButton: .left)?- .post(tap: .cghidEventTap)+ if let dragged = CGEvent(mouseEventSource: source, mouseType: .leftMouseDragged, mouseCursorPosition: point, mouseButton: .left) {+ post(dragged, screenPoint: point, to: target)+ }usleep(8_000)}guard let up = CGEvent(mouseEventSource: source, mouseType: .leftMouseUp, mouseCursorPosition: end, mouseButton: .left) else {return false}usleep(40_000)- up.post(tap: .cghidEventTap)+ post(up, screenPoint: end, to: target)return true}++ /// Delivers a built mouse event: to the HID tap (frontmost, real cursor) when `target` is nil,+ /// otherwise to the target process cursor-neutrally — SkyLight bridge first (stamping the window-local+ /// hit-test point derived from the target's bounds), then the public per-process post. Never the HID+ /// tap for a background target, which would warp the user's cursor to the point.+ private static func post(_ event: CGEvent, screenPoint: CGPoint, to target: InputTarget?) {+ guard let target else {+ event.post(tap: .cghidEventTap)+ return+ }+ let windowLocalPoint = CGPoint(+ x: screenPoint.x - target.bounds.x,+ y: screenPoint.y - target.bounds.y+ )+ if SkyLightEventPost.shared.postMouse(+ event,+ toPid: target.processID,+ windowID: target.windowID,+ windowLocalPoint: windowLocalPoint+ ) { return }+ event.postToPid(target.processID)+ }}/// Acts on an app by grounding a control in its accessibility tree and clicking it with the realdiff --git a/apps/Donkey/Sources/DonkeyRuntime/InputTarget.swift b/apps/Donkey/Sources/DonkeyRuntime/InputTarget.swiftnew file mode 100644index 00000000..4e5775b3--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/InputTarget.swift@@ -0,0 +1,34 @@+import DonkeyContracts+import Foundation++/// A pinned handle to the one window the harness intends to drive: its process, window id, bounds, and+/// bundle. Built from a freshly resolved `MacWindowTargetCandidate` so a background action routes to a+/// specific `(pid, windowID)` instead of "whatever is frontmost". Because candidates come from the+/// on-screen window list, a pinned target is already on the active Space and not minimized.+public struct InputTarget: Equatable, Sendable {+ public var processID: pid_t+ public var windowID: UInt32+ public var bounds: WindowTargetBounds+ public var bundleIdentifier: String?++ public init(+ processID: pid_t,+ windowID: UInt32,+ bounds: WindowTargetBounds,+ bundleIdentifier: String? = nil+ ) {+ self.processID = processID+ self.windowID = windowID+ self.bounds = bounds+ self.bundleIdentifier = bundleIdentifier+ }++ public init(candidate: MacWindowTargetCandidate) {+ self.init(+ processID: pid_t(candidate.processID),+ windowID: candidate.windowID,+ bounds: candidate.bounds,+ bundleIdentifier: candidate.bundleIdentifier+ )+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swiftindex 0eb1f368..7ad26910 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift@@ -286,11 +286,24 @@ public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackendelse {return result(command, executed: false, reason: "missingAccessibilityTarget")}- guard let bundleIdentifier = command.metadata["bundleIdentifier"],- let application = frontmostApplication(),- application.bundleIdentifier == bundleIdentifier- else {- return result(command, executed: false, reason: "targetAppNotFrontmost")+ // Resolve the process to act on. In the default (foreground) mode the target must be frontmost+ // and its pid comes from the frontmost app, preserving the original guard exactly. In background+ // mode the guard upstream has already confirmed the pinned target is a safe, on-active-Space+ // surface, so we trust the supplied pid and drop the frontmost requirement — AXUIElementPerformAction+ // is a focus-neutral cross-process RPC that needs neither frontmost status nor a cursor move.+ let processID: pid_t+ if command.metadata["accessibility.executionMode"] == "background",+ let pidString = command.metadata["accessibility.processID"],+ let backgroundProcessID = pid_t(pidString) {+ processID = backgroundProcessID+ } else {+ guard let bundleIdentifier = command.metadata["bundleIdentifier"],+ let application = frontmostApplication(),+ application.bundleIdentifier == bundleIdentifier+ else {+ return result(command, executed: false, reason: "targetAppNotFrontmost")+ }+ processID = application.processIdentifier}// Prefer the live handle captured at observe time: it stays bound to the same logical control@@ -298,12 +311,12 @@ public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackend// old node index. Fall back to the positional re-walk, and surface a distinct "stale" reason when// neither resolves so the planner re-observes instead of retrying a vanished node.let element: AXUIElement- if let cached = cachedElement(processID: application.processIdentifier, nodeID: nodeID),+ if let cached = cachedElement(processID: processID, nodeID: nodeID),isAlive(cached) {element = cached} else if let walked = resolveElement(nodeID: nodeID,- application: AXUIElementCreateApplication(application.processIdentifier)+ application: AXUIElementCreateApplication(processID)) {element = walked} else {diff --git a/apps/Donkey/Sources/DonkeyRuntime/SkyLightEventPost.swift b/apps/Donkey/Sources/DonkeyRuntime/SkyLightEventPost.swiftnew file mode 100644index 00000000..fa221566--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/SkyLightEventPost.swift@@ -0,0 +1,155 @@+import CoreGraphics+import Foundation++/// Isolated bridge to private SkyLight SPIs for delivering a synthetic event to a specific process+/// WITHOUT moving the real cursor or raising the app. It is the *enhancement* layer over the public+/// per-process post (`CGEvent.postToPid`): it adds the activity-monitor tickle some apps need to treat+/// a synthetic key as live input, and the macOS-14 key authentication envelope Chromium/Electron+/// require, plus a window-local hit-test point for a backgrounded window.+///+/// The bridge is enabled by default — there is no flag to turn it on. Instead it is gated by capability+/// detection: symbols are loaded via `dlopen`/`dlsym`, and when any required one is missing the bridge+/// reports itself unavailable and every method returns `false`, so the caller falls back to the public+/// per-process post (still cursor-neutral) and ultimately to the HID tap. This is the ONLY file that+/// names a SkyLight symbol.+///+/// Focus-without-raise (the window-server event-record post) is intentionally not implemented in this+/// cut: the public per-process post and the no-auth mouse recipe do not require it, and it is the most+/// fragile of the reverse-engineered pieces. It is the natural next addition if a backgrounded mouse+/// gesture on a web surface needs the target to be app-active first.+public final class SkyLightEventPost: @unchecked Sendable {+ public static let shared = SkyLightEventPost()++ private typealias PostToPidFn = @convention(c) (pid_t, CGEvent) -> Void+ private typealias SetAuthMessageFn = @convention(c) (CGEvent, AnyObject) -> Void+ private typealias FactoryMsgSendFn = @convention(c) (AnyObject, Selector, UnsafeMutableRawPointer, Int32, UInt32) -> AnyObject?+ private typealias SetIntegerFieldFn = @convention(c) (CGEvent, UInt32, Int64) -> Void+ private typealias SetWindowLocationFn = @convention(c) (CGEvent, CGPoint) -> Void++ private struct Resolved {+ let postToPid: PostToPidFn+ let setAuthMessage: SetAuthMessageFn+ let msgSendFactory: FactoryMsgSendFn+ let messageClass: AnyClass+ let factorySelector: Selector+ }++ private let resolved: Resolved?+ /// Resolved independently so one missing symbol doesn't disable the core post path.+ private let setIntegerField: SetIntegerFieldFn?+ private let setWindowLocation: SetWindowLocationFn?++ public var isAvailable: Bool { resolved != nil }++ public init() {+ let symbols = Self.resolveSymbols()+ resolved = symbols.resolved+ setIntegerField = symbols.setIntegerField+ setWindowLocation = symbols.setWindowLocation+ }++ /// Designated initializer used to construct a known-unavailable instance for tests, without touching+ /// the real symbol table. Production always goes through `init()`.+ private init(+ resolved: Resolved?,+ setIntegerField: SetIntegerFieldFn?,+ setWindowLocation: SetWindowLocationFn?+ ) {+ self.resolved = resolved+ self.setIntegerField = setIntegerField+ self.setWindowLocation = setWindowLocation+ }++ /// A bridge that always reports unavailable — the deterministic stand-in for "the SkyLight symbols+ /// didn't resolve", so the fallback contract is testable without depending on the host's symbols.+ static func unavailableForTesting() -> SkyLightEventPost {+ SkyLightEventPost(resolved: nil, setIntegerField: nil, setWindowLocation: nil)+ }++ private static func resolveSymbols() -> (+ resolved: Resolved?,+ setIntegerField: SetIntegerFieldFn?,+ setWindowLocation: SetWindowLocationFn?+ ) {+ _ = dlopen("/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight", RTLD_LAZY)+ let rtldDefault = UnsafeMutableRawPointer(bitPattern: -2)+ func symbol(_ name: String) -> UnsafeMutableRawPointer? { dlsym(rtldDefault, name) }++ let setIntegerField = symbol("SLEventSetIntegerValueField")+ .map { unsafeBitCast($0, to: SetIntegerFieldFn.self) }+ let setWindowLocation = symbol("CGEventSetWindowLocation")+ .map { unsafeBitCast($0, to: SetWindowLocationFn.self) }++ guard let postPtr = symbol("SLEventPostToPid"),+ let authPtr = symbol("SLEventSetAuthenticationMessage"),+ let msgSendPtr = symbol("objc_msgSend"),+ let messageClass = NSClassFromString("SLSEventAuthenticationMessage")+ else {+ return (nil, setIntegerField, setWindowLocation)+ }++ let resolved = Resolved(+ postToPid: unsafeBitCast(postPtr, to: PostToPidFn.self),+ setAuthMessage: unsafeBitCast(authPtr, to: SetAuthMessageFn.self),+ msgSendFactory: unsafeBitCast(msgSendPtr, to: FactoryMsgSendFn.self),+ messageClass: messageClass,+ factorySelector: NSSelectorFromString("messageWithEventRecord:pid:version:")+ )+ return (resolved, setIntegerField, setWindowLocation)+ }++ /// Posts a keyboard event to `pid`, attaching the macOS-14 authentication envelope so Chromium/Electron+ /// accept the synthetic key. Returns true when the SPI path was taken; false (unavailable) means the+ /// caller should fall back to the public per-process post.+ @discardableResult+ public func postKey(_ event: CGEvent, toPid pid: pid_t) -> Bool {+ guard let resolved else { return false }+ if let record = extractEventRecord(from: event),+ let message = resolved.msgSendFactory(+ resolved.messageClass as AnyObject,+ resolved.factorySelector,+ record,+ Int32(pid),+ 0+ ) {+ resolved.setAuthMessage(event, message)+ }+ resolved.postToPid(pid, event)+ return true+ }++ /// Posts a mouse event to `pid`, stamping the window-local hit-test point and the target pid field so+ /// the window server routes it to the backgrounded window. The mouse recipe deliberately attaches no+ /// authentication envelope. Returns true when the SPI path was taken; false (unavailable) means the+ /// caller should fall back to the public per-process post.+ @discardableResult+ public func postMouse(+ _ event: CGEvent,+ toPid pid: pid_t,+ windowID: UInt32,+ windowLocalPoint: CGPoint+ ) -> Bool {+ guard let resolved else { return false }+ // Best-effort stamps; absence of either optional SPI simply means the window server falls back to+ // re-projecting from the event's screen-space location. windowID is carried for parity with the+ // recipe but is auto-filled by the event bridge, so it is not written explicitly here.+ _ = windowID+ setWindowLocation?(event, windowLocalPoint)+ setIntegerField?(event, 40, Int64(pid))+ resolved.postToPid(pid, event)+ return true+ }++ /// Reads the `SLSEventRecord*` embedded in the opaque `__CGEvent`, probing the candidate pointer+ /// slots the layout has used across OS revisions. Returns nil when none holds a pointer, in which+ /// case `postKey` posts without the authentication envelope (valid on older releases).+ private func extractEventRecord(from event: CGEvent) -> UnsafeMutableRawPointer? {+ let base = Unmanaged.passUnretained(event).toOpaque()+ for offset in [24, 32, 16] {+ if let record = base.load(fromByteOffset: offset, as: UnsafeMutableRawPointer?.self) {+ return record+ }+ }+ return nil+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/TargetActionGuard.swift b/apps/Donkey/Sources/DonkeyRuntime/TargetActionGuard.swiftnew file mode 100644index 00000000..41b8067e--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/TargetActionGuard.swift@@ -0,0 +1,52 @@+import DonkeyContracts+import Foundation++/// The single, typed decision for whether an action runs in the background (no cursor move, no app+/// raise) or the foreground (the existing activate-and-recover path). It replaces the ad-hoc frontmost+/// checks the act tools used to make inline, so background eligibility is decided in one place.+///+/// Background is permitted only when all of:+/// 1. the turn asked for it (`ExecutionPreference.background`), set by the understanding boundary —+/// never inferred from raw text;+/// 2. the action uses a background-capable lane — the Accessibility action lane (`AXUIElementPerformAction`+/// is a focus-neutral cross-process RPC) or the pid-routed event-post lane (`CGEvent.postToPid` and the+/// SkyLight bridge deliver to a process without moving the cursor); and+/// 3. the resolved window is a safe surface (not a login/password/payment/system surface), because a+/// background action runs on a window the user is not watching.+///+/// Anything else returns `.foreground`, which is always available, so an unsafe surface or a foreground+/// turn gracefully degrades instead of failing. The target is resolved from the on-screen window list,+/// so a returned candidate is inherently on the active Space and not minimized — no Space query needed.+public enum TargetActionGuard {+ /// The mechanism an action will use. Both lanes can run in the background; the lane records which+ /// delivery the caller will use so this stays a single, explicit decision point.+ public enum Lane: Equatable, Sendable {+ /// `AXUIElementPerformAction` on a cached element handle.+ case axAction+ /// A synthetic CGEvent delivered to the target process (public `postToPid`, optionally the+ /// SkyLight bridge) — for coordinate clicks, scroll, drag, and keystrokes AX can't express.+ case pidEventPost+ }++ public enum Decision: Equatable, Sendable {+ /// Act on the pinned target without raising it or moving the cursor.+ case background(InputTarget)+ /// Use the existing path: activate the target (one recovery) and act in front.+ case foreground+ }++ public static func resolve(+ candidate: MacWindowTargetCandidate,+ preference: ExecutionPreference,+ lane: Lane+ ) -> Decision {+ // Both lanes are background-capable; the gate is the turn's preference and the surface safety.+ _ = lane+ guard preference == .background,+ candidate.safetyAssessment.status == .allowed+ else {+ return .foreground+ }+ return .background(InputTarget(candidate: candidate))+ }+}