Open source CapCut alternative.
TypeScript
Clean up generic harness execution docs and tests
David Le048e9cc3c1eb
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex f552b298..f274421a 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -68,7 +68,9 @@ extension PointerPromptCommandHandling {struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {var catalog: LocalAppTaskCatalogvar localModelResolver: LocalModelTaskIntentResolver- var liveRunner: LocalAppTaskLiveRunner+ var appController: any LocalAppTaskAppControlling+ var actionEngineFactory: LocalAppHarnessStepExecutor.ActionEngineFactory+ var permissionPolicy: ToolCallPolicyvar redactor: AIHarnessRedactorvar memoryRetriever: SemanticRunMemoryRetrievervar coordinatorRegistry: PointerPromptRunCoordinatorRegistry@@ -78,7 +80,14 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {init(catalog: LocalAppTaskCatalog = .defaultLocal(),localModelResolver: LocalModelTaskIntentResolver? = nil,- liveRunner: LocalAppTaskLiveRunner? = nil,+ appController: any LocalAppTaskAppControlling = MacLocalAppTaskController(+ uiUnderstandingRunner: DonkeyUIUnderstandingRunnerFactory.defaultRunner()+ ),+ actionEngineFactory: @escaping LocalAppHarnessStepExecutor.ActionEngineFactory = LocalAppTaskActionEngines.keyboardOrAutomation(for:),+ permissionPolicy: ToolCallPolicy = ToolCallPolicy(+ allowedCapabilities: ToolCallPolicy.defaultAllowedCapabilities.union([.input]),+ deniedCapabilities: []+ ),redactor: AIHarnessRedactor = AIHarnessRedactor(),memoryRetriever: SemanticRunMemoryRetriever = SemanticRunMemoryRetriever(),coordinatorRegistry: PointerPromptRunCoordinatorRegistry = PointerPromptRunCoordinatorRegistry(),@@ -88,12 +97,9 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {self.catalog = catalogself.coordinatorRegistry = coordinatorRegistryself.localModelResolver = localModelResolver ?? LocalModelTaskIntentResolver(catalog: catalog)- self.liveRunner = liveRunner ?? LocalAppTaskLiveRunner(- catalog: catalog,- appController: MacLocalAppTaskController(- uiUnderstandingRunner: DonkeyUIUnderstandingRunnerFactory.defaultRunner()- )- )+ self.appController = appController+ self.actionEngineFactory = actionEngineFactory+ self.permissionPolicy = permissionPolicyself.redactor = redactorself.memoryRetriever = memoryRetrieverself.genericHarnessLifecycle = genericHarnessLifecycle@@ -164,8 +170,6 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {}let coordinator = await coordinatorRegistry.coordinator(for: taskID)- var taskLiveRunner = liveRunner- taskLiveRunner.coordinator = coordinatorlet modelInput = Self.modelInput(for: command,context: context,@@ -348,9 +352,9 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {"appHarness.decision": AppHarnessDecisionKind.runLocalTask.rawValue,"genericHarness.taskID": taskID]) { current, _ in current },- appController: taskLiveRunner.appController,- actionEngineFactory: taskLiveRunner.actionEngineFactory,- permissionPolicy: taskLiveRunner.permissionPolicy,+ appController: appController,+ actionEngineFactory: actionEngineFactory,+ permissionPolicy: permissionPolicy,coordinator: coordinator)await localStepExecutor.registerTools(in: registry)@@ -417,27 +421,17 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {}func pauseCommand(taskID: String) async -> Bool {- let genericPaused = await genericHarnessLifecycle.pauseTask(+ await genericHarnessLifecycle.pauseTask(taskID: taskID,reason: "Pointer prompt paused task") != nil- let oldRunnerPaused = await coordinatorRegistry.pause(- taskID: taskID,- reason: "Pointer prompt paused task"- )- return genericPaused || oldRunnerPaused}func resumeCommand(taskID: String) async -> Bool {- let genericResumed = await genericHarnessLifecycle.resumeTask(+ await genericHarnessLifecycle.resumeTask(taskID: taskID,reason: "Pointer prompt resumed task") != nil- let oldRunnerResumed = await coordinatorRegistry.resume(- taskID: taskID,- reason: "Pointer prompt resumed task"- )- return genericResumed || oldRunnerResumed}func approvePermissionGate(taskID: String) async -> Bool {diff --git a/apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillApprovalLiveRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillApprovalLiveRunner.swiftindex f5a2af33..67110e68 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillApprovalLiveRunner.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillApprovalLiveRunner.swift@@ -47,7 +47,7 @@ public struct DocumentFormFillApprovalLiveRunner: Sendable {deniedCapabilities: []),coordinator: RunCoordinator? = nil,- actionEngineFactory: @escaping ActionEngineFactory = LocalAppTaskLiveRunner.accessibilityActionEngine(for:)+ actionEngineFactory: @escaping ActionEngineFactory = LocalAppTaskActionEngines.accessibility(for:)) {self.planner = plannerself.appController = appControllerdiff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swiftindex fdb4b541..fd025254 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift@@ -30,7 +30,7 @@ public actor LocalAppHarnessStepExecutor {resolution: LocalAppTaskCatalogResolution,metadata: [String: String] = [:],appController: any LocalAppTaskAppControlling,- actionEngineFactory: @escaping ActionEngineFactory = LocalAppTaskLiveRunner.defaultActionEngine(for:),+ actionEngineFactory: @escaping ActionEngineFactory = LocalAppTaskActionEngines.keyboardOrAutomation(for:),permissionPolicy: ToolCallPolicy = ToolCallPolicy(allowedCapabilities: ToolCallPolicy.defaultAllowedCapabilities.union([.input]),deniedCapabilities: []diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskExecutionSupport.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskExecutionSupport.swiftnew file mode 100644index 00000000..34a09f5b--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskExecutionSupport.swift@@ -0,0 +1,532 @@+@preconcurrency import ApplicationServices+import AppKit+import DonkeyContracts+import Foundation++public enum LocalAppTaskLiveRunStatus: String, Equatable, Sendable {+ case completed+ case needsUserReview+ case unsupportedCommand+ case needsConfirmation+ case appUnavailable+ case failedSafe+}++public struct LocalAppTaskLiveRunResult: Equatable, Sendable {+ public var command: String+ public var traceID: String+ public var status: LocalAppTaskLiveRunStatus+ public var resolution: LocalAppTaskCatalogResolution+ public var initialActionPlan: LocalAppEvidenceBackedActionPlan?+ public var finalActionPlan: LocalAppEvidenceBackedActionPlan?+ public var observation: LocalAppTaskObservation?+ public var documentFormFillPlan: DocumentFormFillPlan?+ public var actionTraces: [ActionEngineCommandTrace]+ public var workflowProgress: LocalAppTaskWorkflowProgress+ public var metadata: [String: String]++ public init(+ command: String,+ traceID: String,+ status: LocalAppTaskLiveRunStatus,+ resolution: LocalAppTaskCatalogResolution,+ initialActionPlan: LocalAppEvidenceBackedActionPlan? = nil,+ finalActionPlan: LocalAppEvidenceBackedActionPlan? = nil,+ observation: LocalAppTaskObservation? = nil,+ documentFormFillPlan: DocumentFormFillPlan? = nil,+ actionTraces: [ActionEngineCommandTrace] = [],+ workflowProgress: LocalAppTaskWorkflowProgress = LocalAppTaskWorkflowProgress(),+ metadata: [String: String] = [:]+ ) {+ self.command = command+ self.traceID = traceID+ self.status = status+ self.resolution = resolution+ self.initialActionPlan = initialActionPlan+ self.finalActionPlan = finalActionPlan+ self.observation = observation+ self.documentFormFillPlan = documentFormFillPlan+ self.actionTraces = actionTraces+ self.workflowProgress = workflowProgress+ self.metadata = metadata+ }+}++public protocol LocalAppTaskAppControlling: Sendable {+ @MainActor+ func launchOrFocus(+ definition: LocalAppTaskDefinition,+ availability: LocalAppAvailability+ ) async -> LocalAppTaskObservation++ @MainActor+ func observe(definition: LocalAppTaskDefinition) async -> LocalAppTaskObservation+}++public enum LocalAppTaskActionEngines {+ public static func keyboardOrAutomation(for definition: LocalAppTaskDefinition) -> ActionEngineGuardrail {+ let inputBackend: any ActionEngineInputBackend = definition.metadata["automationBackend"] == "appleScript"+ ? MacAppleScriptActionEngineInputBackend()+ : MacKeyboardActionEngineInputBackend()++ return ActionEngineGuardrail(+ configuration: ActionEngineConfiguration(liveInputEnabled: true),+ focusGuard: MacLocalAppFocusGuard(+ targetID: LocalAppTaskAdapter(definition: definition).targetID,+ bundleIdentifier: definition.targetApp.bundleIdentifier+ ),+ inputBackend: inputBackend+ )+ }++ public static func accessibility(for definition: LocalAppTaskDefinition) -> ActionEngineGuardrail {+ ActionEngineGuardrail(+ configuration: ActionEngineConfiguration(liveInputEnabled: true),+ focusGuard: MacLocalAppFocusGuard(+ targetID: LocalAppTaskAdapter(definition: definition).targetID,+ bundleIdentifier: definition.targetApp.bundleIdentifier+ ),+ inputBackend: MacAccessibilityActionEngineInputBackend()+ )+ }+}++public struct MacLocalAppFocusGuard: ActionEngineFocusGuard {+ public var targetID: String+ public var bundleIdentifier: String?++ public init(targetID: String, bundleIdentifier: String?) {+ self.targetID = targetID+ self.bundleIdentifier = bundleIdentifier+ }++ public func targetIsSafeForInput(targetID: String) async -> Bool {+ guard targetID == self.targetID,+ let bundleIdentifier+ else {+ return false+ }++ return await MainActor.run {+ NSWorkspace.shared.frontmostApplication?.bundleIdentifier == bundleIdentifier+ }+ }+}++public struct MacLocalAppTaskController: LocalAppTaskAppControlling {+ public var uiUnderstandingRunner: any LocalUIUnderstandingRunning++ public init(+ uiUnderstandingRunner: any LocalUIUnderstandingRunning = ProcessBackedLocalUIUnderstandingAdapter()+ ) {+ self.uiUnderstandingRunner = uiUnderstandingRunner+ }++ @MainActor+ public func launchOrFocus(+ definition: LocalAppTaskDefinition,+ availability: LocalAppAvailability+ ) async -> LocalAppTaskObservation {+ if let itemURL = availability.appURL,+ let itemKind = availability.metadata["itemKind"],+ itemKind != "application" {+ let opened = await openLocalItem(at: itemURL)+ if let bundleIdentifier = definition.targetApp.bundleIdentifier {+ await waitForFrontmostApplication(+ LocalAppTarget(+ appName: definition.targetApp.appName,+ bundleIdentifier: bundleIdentifier,+ titleContains: definition.targetApp.titleContains+ )+ )+ }+ let isFocused = definition.targetApp.bundleIdentifier == nil+ || NSWorkspace.shared.frontmostApplication?.bundleIdentifier == definition.targetApp.bundleIdentifier+ return LocalAppTaskObservation(+ appIsRunning: opened,+ appIsFocused: opened && isFocused,+ availableControls: [:],+ visibleText: ["appName": definition.targetApp.appName],+ confidence: opened ? 0.72 : 0.2,+ metadata: [+ "observer": "mac-local-app-controller",+ "openedLocalItem": String(opened),+ "localItem.kind": itemKind,+ "localItem.path": itemURL.path,+ "defaultApplication": availability.metadata["defaultApplication"] ?? ""+ ]+ )+ }++ if let appURL = availability.appURL {+ await openApplication(at: appURL)+ } else if let runningApplication = runningApplication(for: definition.targetApp) {+ runningApplication.activate(options: [.activateAllWindows])+ }++ await waitForFrontmostApplication(definition.targetApp)+ return await observe(definition: definition)+ }++ @MainActor+ public func observe(definition: LocalAppTaskDefinition) async -> LocalAppTaskObservation {+ let runningApplication = runningApplication(for: definition.targetApp)+ let isFocused = NSWorkspace.shared.frontmostApplication?.bundleIdentifier == definition.targetApp.bundleIdentifier+ let verificationKey = definition.metadata["verificationTextKey"]+ ?? definition.verificationEntityName+ ?? "visibleText"+ let accessibilityIndex = accessibilityControlIndex(for: definition, runningApplication: runningApplication)+ let visibleText = accessibilityIndex?.visibleText ?? accessibilityVisibleText(for: runningApplication)+ var controls: [String: Bool] = Dictionary(+ uniqueKeysWithValues: definition.workflowSteps.compactMap { step in+ guard step.role == .focusControl,+ let controlID = step.metadata["controlID"]+ else {+ return nil+ }+ let discovered = accessibilityIndex?.firstControl(matching: controlID) != nil+ return (controlID, discovered)+ }+ )++ var textValues: [String: String] = [:]+ if let visibleText {+ textValues["visibleText"] = visibleText+ textValues[verificationKey] = visibleText+ }++ var accessibilityMetadata = [+ "observer": "mac-local-app-controller",+ "accessibilityTrusted": String(AXIsProcessTrusted()),+ "accessibilityControlDiscovery": String(accessibilityIndex != nil),+ "accessibilityControlCount": accessibilityIndex?.metadata["controlCount"] ?? "0"+ ].merging(accessibilityIndex?.metadata ?? [:]) { current, _ in current }+ for step in definition.workflowSteps {+ guard let controlID = step.metadata["controlID"],+ let control = accessibilityIndex?.firstControl(matching: controlID)+ else {+ continue+ }+ let frame = control.frame.map {+ HotLoopRect(+ x: $0.x,+ y: $0.y,+ width: $0.width,+ height: $0.height,+ space: .screen+ )+ }+ accessibilityMetadata.merge(+ LocalAppObservationGeometry.controlMetadata(+ controlID: controlID,+ frame: frame,+ source: .accessibility,+ label: control.label,+ kind: control.kind,+ confidence: 0.86,+ extra: control.metadata+ )+ ) { current, _ in current }+ }++ let accessibilityObservation = LocalAppTaskObservation(+ appIsRunning: runningApplication != nil,+ appIsFocused: isFocused,+ availableControls: controls,+ visibleText: textValues,+ confidence: accessibilityIndex == nil ? (visibleText == nil ? 0.4 : 0.75) : 0.86,+ metadata: accessibilityMetadata+ )++ guard shouldIncludeScreenshotUnderstanding(+ definition: definition,+ accessibilityObservation: accessibilityObservation,+ verificationKey: verificationKey+ ) else {+ return accessibilityObservation+ }++ guard let screenshotObservation = await screenshotUnderstandingObservation(+ definition: definition,+ runningApplication: runningApplication,+ isFocused: isFocused,+ verificationKey: verificationKey+ ) else {+ var metadata = accessibilityObservation.metadata+ metadata["screenshotUnderstanding.status"] = "unavailable"+ return LocalAppTaskObservation(+ appIsRunning: accessibilityObservation.appIsRunning,+ appIsFocused: accessibilityObservation.appIsFocused,+ availableControls: accessibilityObservation.availableControls,+ visibleText: accessibilityObservation.visibleText,+ confidence: accessibilityObservation.confidence,+ metadata: metadata+ )+ }++ controls.merge(screenshotObservation.availableControls) { current, new in current || new }+ return LocalAppTaskObservation(+ appIsRunning: accessibilityObservation.appIsRunning || screenshotObservation.appIsRunning,+ appIsFocused: accessibilityObservation.appIsFocused || screenshotObservation.appIsFocused,+ availableControls: controls,+ visibleText: accessibilityObservation.visibleText.merging(+ screenshotObservation.visibleText+ ) { current, _ in current },+ confidence: max(accessibilityObservation.confidence, screenshotObservation.confidence),+ metadata: accessibilityObservation.metadata.merging(+ screenshotObservation.metadata+ ) { current, _ in current }+ )+ }++ private func shouldIncludeScreenshotUnderstanding(+ definition: LocalAppTaskDefinition,+ accessibilityObservation: LocalAppTaskObservation,+ verificationKey: String+ ) -> Bool {+ LocalAppTaskObservationFallbackPolicy.shouldUseScreenshotUnderstanding(+ definition: definition,+ accessibilityObservation: accessibilityObservation,+ verificationKey: verificationKey+ )+ }++ @MainActor+ private func screenshotUnderstandingObservation(+ definition: LocalAppTaskDefinition,+ runningApplication: NSRunningApplication?,+ isFocused: Bool,+ verificationKey: String+ ) async -> LocalAppTaskObservation? {+ guard runningApplication != nil,+ let target = try? MacWindowResolver().selectTarget(),+ target.bundleIdentifier == definition.targetApp.bundleIdentifier,+ target.safetyAssessment.status == .allowed+ else {+ return nil+ }++ let screenshot: CapturedWindowScreenshot+ do {+ screenshot = try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: target)+ } catch {+ return nil+ }++ let imageURL = FileManager.default.temporaryDirectory+ .appendingPathComponent("donkey-ui-understanding-\(UUID().uuidString).png")+ do {+ try screenshot.pngData.write(to: imageURL, options: .atomic)+ } catch {+ return nil+ }+ defer {+ try? FileManager.default.removeItem(at: imageURL)+ }++ let request = LocalUIUnderstandingRequest(+ traceID: "local-ui-understanding-\(UUID().uuidString)",+ targetID: LocalAppTaskAdapter(definition: definition).targetID,+ appIsRunning: true,+ appIsFocused: isFocused,+ imageFileURL: imageURL,+ cropBounds: HotLoopRect(+ x: 0,+ y: 0,+ width: Double(screenshot.imageWidth),+ height: Double(screenshot.imageHeight),+ space: .window+ ),+ pixelSize: HotLoopSize(+ width: Double(screenshot.imageWidth),+ height: Double(screenshot.imageHeight),+ space: .window+ ),+ metadata: [+ "observer": "mac-local-app-controller",+ "observation.source": "screenshot",+ "verificationTextKey": verificationKey,+ "screenshot.scope": "targetWindow",+ "screenshot.desktopCaptureAllowed": "false",+ "target.windowID": String(target.windowID),+ "capture.method": screenshot.captureMethod.rawValue+ ].merging(LocalAppObservationGeometry.targetBoundsMetadata(target.bounds)) { current, _ in current }+ )++ do {+ return try await uiUnderstandingRunner.understand(request).observation(for: request)+ } catch {+ return nil+ }+ }++ @MainActor+ private func accessibilityControlIndex(+ for definition: LocalAppTaskDefinition,+ runningApplication: NSRunningApplication?+ ) -> LocalAppAccessibilityControlIndex? {+ guard AXIsProcessTrusted(),+ runningApplication != nil,+ let target = try? MacWindowResolver().selectTarget(),+ target.bundleIdentifier == definition.targetApp.bundleIdentifier+ else {+ return nil+ }++ let limits = MacAccessibilitySnapshotLimits(maxDepth: 6, maxChildrenPerNode: 80, maxTotalNodes: 500)+ guard let tree = try? ApplicationServicesMacAccessibilitySnapshotCapturer().captureTree(+ target: target,+ limits: limits+ ) else {+ return nil+ }+ let snapshot = MacAccessibilitySnapshot(+ target: target,+ limits: limits,+ root: tree.root,+ totalNodeCount: tree.totalNodeCount,+ isTreeTruncated: tree.isTreeTruncated+ )+ return LocalAppAccessibilityControlDiscovery().discover(in: snapshot)+ }++ @MainActor+ private func runningApplication(for target: LocalAppTarget) -> NSRunningApplication? {+ guard let bundleIdentifier = target.bundleIdentifier else { return nil }+ return NSRunningApplication+ .runningApplications(withBundleIdentifier: bundleIdentifier)+ .first+ }++ @MainActor+ private func openApplication(at url: URL) async {+ await withCheckedContinuation { continuation in+ let configuration = NSWorkspace.OpenConfiguration()+ configuration.activates = true+ NSWorkspace.shared.openApplication(+ at: url,+ configuration: configuration+ ) { _, _ in+ continuation.resume()+ }+ }+ }++ @MainActor+ private func openLocalItem(at url: URL) async -> Bool {+ NSWorkspace.shared.open(url)+ }++ @MainActor+ private func waitForFrontmostApplication(_ target: LocalAppTarget) async {+ let bundleIdentifier = target.bundleIdentifier+ for _ in 0..<16 {+ if NSWorkspace.shared.frontmostApplication?.bundleIdentifier == bundleIdentifier {+ return+ }+ try? await Task.sleep(nanoseconds: 125_000_000)+ }+ }++ @MainActor+ private func accessibilityVisibleText(for application: NSRunningApplication?) -> String? {+ guard AXIsProcessTrusted(),+ let processIdentifier = application?.processIdentifier+ else {+ return nil+ }++ let appElement = AXUIElementCreateApplication(processIdentifier)+ let elements = windows(from: appElement)+ let roots = elements.isEmpty ? [appElement] : elements+ let values = roots.flatMap { textValues(from: $0, depth: 0, remaining: 160) }+ let joined = values+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter { !$0.isEmpty }+ .joined(separator: " ")+ return joined.isEmpty ? nil : joined+ }++ @MainActor+ private func windows(from appElement: AXUIElement) -> [AXUIElement] {+ var value: CFTypeRef?+ guard AXUIElementCopyAttributeValue(+ appElement,+ kAXWindowsAttribute as CFString,+ &value+ ) == .success else {+ return []+ }++ return value as? [AXUIElement] ?? []+ }++ @MainActor+ private func textValues(+ from element: AXUIElement,+ depth: Int,+ remaining: Int+ ) -> [String] {+ guard depth <= 8, remaining > 0 else { return [] }++ var values: [String] = []+ for attribute in [+ kAXTitleAttribute,+ kAXDescriptionAttribute,+ kAXValueAttribute,+ kAXHelpAttribute+ ] {+ if let text = stringAttribute(attribute as CFString, from: element) {+ values.append(text)+ }+ }++ let children = children(from: element)+ let nextRemaining = max(0, remaining - values.count)+ for child in children.prefix(nextRemaining) {+ values.append(contentsOf: textValues(+ from: child,+ depth: depth + 1,+ remaining: max(0, nextRemaining - values.count)+ ))+ if values.count >= remaining {+ break+ }+ }++ return values+ }++ @MainActor+ private func children(from element: AXUIElement) -> [AXUIElement] {+ var value: CFTypeRef?+ guard AXUIElementCopyAttributeValue(+ element,+ kAXChildrenAttribute as CFString,+ &value+ ) == .success else {+ return []+ }++ return value as? [AXUIElement] ?? []+ }++ @MainActor+ private func stringAttribute(_ attribute: CFString, from element: AXUIElement) -> String? {+ var value: CFTypeRef?+ guard AXUIElementCopyAttributeValue(element, attribute, &value) == .success,+ let value+ else {+ return nil+ }++ if let string = value as? String {+ return string+ }+ if let number = value as? NSNumber {+ return number.stringValue+ }+ return nil+ }+}+diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swiftdeleted file mode 100644index f499cab5..00000000--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift+++ /dev/null@@ -1,1375 +0,0 @@-@preconcurrency import ApplicationServices-import AppKit-import DonkeyContracts-import Foundation--public enum LocalAppTaskLiveRunStatus: String, Equatable, Sendable {- case completed- case needsUserReview- case unsupportedCommand- case needsConfirmation- case appUnavailable- case failedSafe-}--public struct LocalAppTaskLiveRunResult: Equatable, Sendable {- public var command: String- public var traceID: String- public var status: LocalAppTaskLiveRunStatus- public var resolution: LocalAppTaskCatalogResolution- public var initialActionPlan: LocalAppEvidenceBackedActionPlan?- public var finalActionPlan: LocalAppEvidenceBackedActionPlan?- public var observation: LocalAppTaskObservation?- public var documentFormFillPlan: DocumentFormFillPlan?- public var actionTraces: [ActionEngineCommandTrace]- public var workflowProgress: LocalAppTaskWorkflowProgress- public var metadata: [String: String]-- public init(- command: String,- traceID: String,- status: LocalAppTaskLiveRunStatus,- resolution: LocalAppTaskCatalogResolution,- initialActionPlan: LocalAppEvidenceBackedActionPlan? = nil,- finalActionPlan: LocalAppEvidenceBackedActionPlan? = nil,- observation: LocalAppTaskObservation? = nil,- documentFormFillPlan: DocumentFormFillPlan? = nil,- actionTraces: [ActionEngineCommandTrace] = [],- workflowProgress: LocalAppTaskWorkflowProgress = LocalAppTaskWorkflowProgress(),- metadata: [String: String] = [:]- ) {- self.command = command- self.traceID = traceID- self.status = status- self.resolution = resolution- self.initialActionPlan = initialActionPlan- self.finalActionPlan = finalActionPlan- self.observation = observation- self.documentFormFillPlan = documentFormFillPlan- self.actionTraces = actionTraces- self.workflowProgress = workflowProgress- self.metadata = metadata- }-}--public protocol LocalAppTaskAppControlling: Sendable {- @MainActor- func launchOrFocus(- definition: LocalAppTaskDefinition,- availability: LocalAppAvailability- ) async -> LocalAppTaskObservation-- @MainActor- func observe(definition: LocalAppTaskDefinition) async -> LocalAppTaskObservation-}--public struct LocalAppTaskLiveRunner: Sendable {- public typealias ActionEngineFactory = @Sendable (LocalAppTaskDefinition) -> ActionEngineGuardrail-- public var catalog: LocalAppTaskCatalog- public var appController: any LocalAppTaskAppControlling- public var contextProvider: any LocalAppTaskContextProviding- public var documentFormFillPlanner: DocumentFormFillPlanner- public var actionEngineFactory: ActionEngineFactory- public var permissionPolicy: ToolCallPolicy- public var coordinator: RunCoordinator?-- public init(- catalog: LocalAppTaskCatalog = .defaultLocal(),- appController: any LocalAppTaskAppControlling = MacLocalAppTaskController(),- contextProvider: any LocalAppTaskContextProviding = MacLocalAppTaskContextProvider(),- documentFormFillPlanner: DocumentFormFillPlanner = DocumentFormFillPlanner(),- actionEngineFactory: @escaping ActionEngineFactory = Self.defaultActionEngine(for:),- permissionPolicy: ToolCallPolicy = ToolCallPolicy(- allowedCapabilities: ToolCallPolicy.defaultAllowedCapabilities.union([.input]),- deniedCapabilities: []- ),- coordinator: RunCoordinator? = nil- ) {- self.catalog = catalog- self.appController = appController- self.contextProvider = contextProvider- self.documentFormFillPlanner = documentFormFillPlanner- self.actionEngineFactory = actionEngineFactory- self.permissionPolicy = permissionPolicy- self.coordinator = coordinator- }-- public func run(- command: String,- traceID: String = "local-app-task-\(UUID().uuidString)"- ) async -> LocalAppTaskLiveRunResult {- await run(- command: command,- traceID: traceID,- resolution: catalog.resolve(command: command),- metadata: ["intentParser": "externalRequired"]- )- }-- public func run(- command: String,- traceID: String,- resolution: LocalAppTaskCatalogResolution,- metadata: [String: String] = [:]- ) async -> LocalAppTaskLiveRunResult {- let runStartedAt = Self.uptimeMilliseconds()- var runMetadata = metadata- var stepTracker = LocalAppTaskStepTracker(metadata: ["traceID": traceID])- stepTracker.complete(- .parseIntent,- summary: "Task intent parsed or supplied",- metadata: ["parser": metadata["intentParser"] ?? resolution.intent?.parserSource.rawValue ?? "external"]- )- guard resolution.status == .resolved else {- stepTracker.block(- .resolveApp,- summary: "Local app task could not be resolved",- metadata: ["resolution.status": resolution.status.rawValue]- )- await publishUnresolvedRun(- command: command,- traceID: traceID,- resolution: resolution- )- let progress = stepTracker.snapshot()- return unresolvedResult(- command: command,- traceID: traceID,- resolution: resolution,- workflowProgress: progress,- metadata: metadata.merging([- "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- ], uniquingKeysWith: { current, _ in current }).merging(- Self.workflowProgressMetadata(progress),- uniquingKeysWith: { current, _ in current }- )- )- }-- stepTracker.start(- .resolveApp,- summary: "Resolving task definition and target app",- metadata: ["resolution.status": resolution.status.rawValue]- )-- guard let definition = resolution.definition,- var intent = resolution.intent,- let availability = resolution.availability- else {- stepTracker.fail(- .resolveApp,- summary: "Local app task resolution was incomplete",- metadata: ["reason": "incompleteResolution"]- )- let progress = stepTracker.snapshot()- await publishRunStart(- command: command,- traceID: traceID,- targetID: "local-app-task-incomplete-resolution"- )- await coordinator?.recordToolEvent(- capability: .controller,- decision: .deny(reason: "local app task resolution was incomplete"),- toolName: "local-app-task-live-runner",- summary: "Local app task resolution incomplete",- traceID: traceID,- metadata: ["reason": "incompleteResolution"]- )- await coordinator?.fail(reason: "Local app task resolution incomplete")- return LocalAppTaskLiveRunResult(- command: command,- traceID: traceID,- status: .failedSafe,- resolution: resolution,- workflowProgress: progress,- metadata: runMetadata.merging([- "reason": "incompleteResolution",- "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- ], uniquingKeysWith: { current, _ in current }).merging(- Self.workflowProgressMetadata(progress),- uniquingKeysWith: { current, _ in current }- )- )- }-- stepTracker.complete(- .resolveApp,- summary: "Resolved task definition and target app",- metadata: [- "taskType": definition.taskType,- "targetApp": definition.targetApp.appName- ]- )-- intent.metadata["traceID"] = traceID- let adapter = catalog.adapter(for: definition)- await publishRunStart(- command: command,- traceID: traceID,- targetID: adapter.targetID- )- if definition.metadata["guardedLiveDefault"] == "reviewOnly" {- let contextStartedAt = Self.uptimeMilliseconds()- stepTracker.start(.observe, summary: "Capturing local app task context")- await coordinator?.recordToolEvent(- capability: .capture,- decision: permissionPolicy.decision(for: .capture),- toolName: "local-app-task-context",- summary: "Captured local app task context",- traceID: traceID- )- let context = await contextProvider.snapshot()- runMetadata["latency.observationMS"] = Self.formatLatency(- Self.uptimeMilliseconds() - contextStartedAt- )- stepTracker.complete(- .observe,- summary: "Captured local app task context",- metadata: ["observer": "local-app-task-context"]- )- stepTracker.start(.evidencePlan, summary: "Building review-first evidence-backed action plan")- let documentPlan = documentFormFillPlanner.plan(- intent: intent,- definition: definition,- context: context- )- let observation = LocalAppTaskObservation(- appIsRunning: context.focusedBundleIdentifier == definition.targetApp.bundleIdentifier,- appIsFocused: context.focusedBundleIdentifier == definition.targetApp.bundleIdentifier,- availableControls: [:],- visibleText: [- "document": context.focusedWindowTitle- ?? intent.normalizedEntities["document"]- ?? "current document"- ],- confidence: context.focusedWindowTitle == nil ? 0.4 : 0.72,- metadata: [- "observer": "local-app-task-context",- "documentFormFillPlan.status": documentPlan.status.rawValue- ]- )- let initialActionPlan = adapter.evidenceBackedActionPlan(for: intent, observation: observation)- stepTracker.complete(- .evidencePlan,- summary: "Built review-first document form-fill plan",- metadata: ["terminalState": initialActionPlan.terminalState.rawValue]- )- stepTracker.wait(- .approval,- summary: "Waiting for user review before Accessibility execution",- metadata: [- "documentFormFillPlan.status": documentPlan.status.rawValue,- "proposalCount": String(documentPlan.proposals.count)- ]- )- stepTracker.skip(.execute, summary: "Execution waits for user approval")- stepTracker.skip(.verify, summary: "Verification waits for approved execution")- let progress = stepTracker.snapshot()- await coordinator?.complete(reason: "Local app task requires document review")- return LocalAppTaskLiveRunResult(- command: command,- traceID: traceID,- status: .needsUserReview,- resolution: resolution,- initialActionPlan: initialActionPlan,- finalActionPlan: initialActionPlan,- observation: observation,- documentFormFillPlan: documentPlan,- workflowProgress: progress,- metadata: runMetadata.merging([- "reason": "reviewOnlyTask",- "documentFormFillPlan.status": documentPlan.status.rawValue,- "documentFormFillPlan.proposalCount": String(documentPlan.proposals.count),- "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- ], uniquingKeysWith: { current, _ in current }).merging(- Self.workflowProgressMetadata(progress),- uniquingKeysWith: { current, _ in current }- )- )- }-- await coordinator?.waitIfPaused()- let launchStartedAt = Self.uptimeMilliseconds()- stepTracker.start(.observe, summary: "Launching or focusing target app for observation")- await coordinator?.recordToolEvent(- capability: .input,- decision: permissionPolicy.decision(for: .input),- toolName: "mac-launch-focus",- summary: "Launching or focusing local app",- traceID: traceID,- metadata: [- "targetApp": definition.targetApp.appName,- "bundleIdentifier": definition.targetApp.bundleIdentifier ?? ""- ]- )- let launchObservation = await appController.launchOrFocus(- definition: definition,- availability: availability- )- runMetadata["latency.launchFocusMS"] = Self.formatLatency(Self.uptimeMilliseconds() - launchStartedAt)- stepTracker.complete(- .observe,- summary: "Observed target app after launch or focus",- metadata: [- "appIsRunning": String(launchObservation.appIsRunning),- "appIsFocused": String(launchObservation.appIsFocused)- ]- )- stepTracker.start(.evidencePlan, summary: "Building evidence-backed action plan")- let initialActionPlan = adapter.evidenceBackedActionPlan(for: intent, observation: launchObservation)- guard initialActionPlan.canExecuteGuardedActions else {- stepTracker.block(- .evidencePlan,- summary: "Evidence-backed action plan blocked live input",- metadata: ["terminalState": initialActionPlan.terminalState.rawValue]- )- stepTracker.skip(.approval, summary: "No approval requested for blocked evidence plan")- stepTracker.skip(.execute, summary: "Execution skipped because evidence was incomplete")- stepTracker.skip(.verify, summary: "Verification skipped because evidence was incomplete")- let progress = stepTracker.snapshot()- await coordinator?.pause(reason: "Local app task evidence-backed action plan blocked live input")- return LocalAppTaskLiveRunResult(- command: command,- traceID: traceID,- status: blockedEvidencePlanStatus(for: initialActionPlan.terminalState),- resolution: resolution,- initialActionPlan: initialActionPlan,- observation: launchObservation,- workflowProgress: progress,- metadata: runMetadata.merging([- "reason": "evidencePlanBlocked",- "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- ], uniquingKeysWith: { current, _ in current }).merging(- Self.workflowProgressMetadata(progress),- uniquingKeysWith: { current, _ in current }- )- )- }- stepTracker.complete(- .evidencePlan,- summary: "Evidence-backed action plan allows guarded live execution",- metadata: ["terminalState": initialActionPlan.terminalState.rawValue]- )- if LocalAppTaskVerificationPolicy.mode(for: definition) == .openedLocalItem,- initialActionPlan.terminalState == .completed {- stepTracker.skip(.approval, summary: "No review gate required for opened local item")- stepTracker.skip(.execute, summary: "Local item was opened through NSWorkspace")- stepTracker.complete(- .verify,- summary: "Local item open request confirmed",- metadata: ["terminalState": initialActionPlan.terminalState.rawValue]- )- await coordinator?.complete(reason: "Local item opened")- let progress = stepTracker.snapshot()- return LocalAppTaskLiveRunResult(- command: command,- traceID: traceID,- status: .completed,- resolution: resolution,- initialActionPlan: initialActionPlan,- finalActionPlan: initialActionPlan,- observation: launchObservation,- workflowProgress: progress,- metadata: runMetadata.merging([- "reason": "openedLocalItem",- "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- ], uniquingKeysWith: { current, _ in current }).merging(- Self.workflowProgressMetadata(progress),- uniquingKeysWith: { current, _ in current }- )- )- }- stepTracker.skip(.approval, summary: "No review gate required for this local-app task")-- var actionTraces: [ActionEngineCommandTrace] = []- let automationCommands = adapter.guardedAutomationCommandTemplates(- for: intent,- issuedAt: Self.now()- )- let usesAutomationBackend = !automationCommands.isEmpty- var accessibilityActionMS = 0.0- if !usesAutomationBackend {- let accessibilityCommands = await accessibilityCommandTemplates(- intent: intent,- definition: definition- )- if !accessibilityCommands.isEmpty {- let accessibilityEngine = Self.accessibilityActionEngine(for: definition)- for (index, actionCommand) in accessibilityCommands.enumerated() {- await coordinator?.waitIfPaused()- let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 60))- let actionStartedAt = Self.uptimeMilliseconds()- await coordinator?.recordToolEvent(- capability: .accessibility,- decision: permissionPolicy.decision(for: .accessibility),- toolName: "mac-accessibility-action-engine",- summary: "Executing guarded Accessibility command",- traceID: traceID,- metadata: [- "commandID": spacedCommand.id,- "workflowStepID": spacedCommand.metadata["workflowStepID"] ?? ""- ]- )- let trace = await accessibilityEngine.handle(- spacedCommand,- permissionPolicy: permissionPolicy- )- accessibilityActionMS += Self.uptimeMilliseconds() - actionStartedAt- actionTraces.append(trace)- guard trace.executed || trace.decision == .skippedNoLiveInput else {- break- }- }- }- }- runMetadata["latency.accessibilityActionMS"] = Self.formatLatency(accessibilityActionMS)-- let engine = actionEngineFactory(definition)- let accessibilityHandledStepIDs: Set<String> = Set(actionTraces.compactMap { trace -> String? in- guard trace.executed || trace.decision == ActionEngineCommandDecision.skippedNoLiveInput else { return nil }- return workflowStepID(from: trace.command)- })- runMetadata["accessibilityHandledStepIDs"] = accessibilityHandledStepIDs.sorted().joined(separator: ",")- let commands = usesAutomationBackend- ? automationCommands- : adapter.guardedKeyboardCommandTemplates(- for: intent,- issuedAt: Self.now()- ).filter { command in- guard let workflowStepID = command.metadata["workflowStepID"] else { return true }- return !accessibilityHandledStepIDs.contains(workflowStepID)- }-- var keyboardActionMS = 0.0- stepTracker.start(.execute, summary: "Executing guarded local-app actions")- for (index, actionCommand) in commands.enumerated() {- await coordinator?.waitIfPaused()- let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 40))- let actionStartedAt = Self.uptimeMilliseconds()- let automationBackend = actionCommand.metadata["automationBackend"] ?? ""- let actionToolName = automationBackend == "appleScript"- ? "mac-applescript-action-engine"- : "mac-keyboard-action-engine"- await coordinator?.recordToolEvent(- capability: .input,- decision: permissionPolicy.decision(for: .input),- toolName: actionToolName,- summary: automationBackend == "appleScript"- ? "Executing guarded AppleScript command"- : "Executing guarded keyboard command",- traceID: traceID,- metadata: [- "commandID": spacedCommand.id,- "workflowStepID": spacedCommand.metadata["workflowStepID"] ?? ""- ]- )- var trace = await engine.handle(- spacedCommand,- permissionPolicy: permissionPolicy- )- keyboardActionMS += Self.uptimeMilliseconds() - actionStartedAt- actionTraces.append(trace)- if trace.decision == .denied(reason: "focus guard failed") {- _ = await appController.launchOrFocus(- definition: definition,- availability: availability- )- let retryCommand = spacedCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 40 + 25))- trace = await engine.handle(- retryCommand,- permissionPolicy: permissionPolicy- )- actionTraces.append(trace)- }-- guard trace.executed || trace.decision == ActionEngineCommandDecision.skippedNoLiveInput else {- stepTracker.fail(- .execute,- summary: "Guarded local-app action was denied",- metadata: [- "actionDeniedReason": decisionReason(trace.decision),- "commandID": trace.command.id- ]- )- let observationStartedAt = Self.uptimeMilliseconds()- await coordinator?.recordToolEvent(- capability: .perception,- decision: permissionPolicy.decision(for: .perception),- toolName: "local-app-observation",- summary: "Observing local app after denied action",- traceID: traceID- )- let finalObservation = await appController.observe(definition: definition)- runMetadata["latency.observationMS"] = Self.formatLatency(- Self.uptimeMilliseconds() - observationStartedAt- )- let verificationStartedAt = Self.uptimeMilliseconds()- let finalActionPlan = adapter.evidenceBackedActionPlan(for: intent, observation: finalObservation)- runMetadata["latency.verificationMS"] = Self.formatLatency(- Self.uptimeMilliseconds() - verificationStartedAt- )- await coordinator?.fail(reason: "Local app task action was denied")- let progress = stepTracker.snapshot()- return LocalAppTaskLiveRunResult(- command: command,- traceID: traceID,- status: .failedSafe,- resolution: resolution,- initialActionPlan: initialActionPlan,- finalActionPlan: finalActionPlan,- observation: finalObservation,- actionTraces: actionTraces,- workflowProgress: progress,- metadata: runMetadata.merging([- "reason": "actionDenied",- "actionDeniedReason": decisionReason(trace.decision),- "actionDeniedCommandID": trace.command.id,- "actionDeniedFocusGuardPassed": String(trace.focusGuardPassed),- "latency.keyboardActionMS": Self.formatLatency(keyboardActionMS),- "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- ], uniquingKeysWith: { current, _ in current }).merging(- Self.actionTraceMetadata(actionTraces),- uniquingKeysWith: { current, _ in current }- ).merging(- Self.workflowProgressMetadata(progress),- uniquingKeysWith: { current, _ in current }- )- )- }- }- runMetadata["latency.keyboardActionMS"] = Self.formatLatency(keyboardActionMS)- runMetadata.merge(Self.actionTraceMetadata(actionTraces)) { current, _ in current }- if usesAutomationBackend {- runMetadata["automation.backend"] = automationCommands.first?.metadata["automationBackend"] ?? ""- runMetadata["automation.action"] = automationCommands.first?.metadata["appleScript.action"] ?? ""- runMetadata["latency.automationActionMS"] = Self.formatLatency(keyboardActionMS)- }- stepTracker.complete(- .execute,- summary: "Guarded local-app actions completed",- metadata: [- "executedCommandCount": String(actionTraces.filter(\.executed).count),- "skippedNoLiveInputCommandCount": String(actionTraces.filter { $0.decision == .skippedNoLiveInput }.count)- ]- )-- await coordinator?.waitIfPaused()- try? await Task.sleep(nanoseconds: 700_000_000)- await coordinator?.waitIfPaused()- let observationStartedAt = Self.uptimeMilliseconds()- stepTracker.start(.verify, summary: "Observing target app for result verification")- await coordinator?.recordToolEvent(- capability: .perception,- decision: permissionPolicy.decision(for: .perception),- toolName: "local-app-observation",- summary: "Observing local app for result verification",- traceID: traceID- )- var finalObservation = await appController.observe(definition: definition)- finalObservation = observationWithActionEvidence(- finalObservation,- actionTraces: actionTraces- )- runMetadata["latency.observationMS"] = Self.formatLatency(Self.uptimeMilliseconds() - observationStartedAt)- let verificationStartedAt = Self.uptimeMilliseconds()- let finalActionPlan = adapter.evidenceBackedActionPlan(for: intent, observation: finalObservation)- runMetadata["latency.verificationMS"] = Self.formatLatency(Self.uptimeMilliseconds() - verificationStartedAt)- runMetadata["latency.totalMS"] = Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)- if let verificationStep = finalActionPlan.steps.first(where: { $0.role == .verifyResult }) {- runMetadata["verification.summary"] = verificationStep.summary- runMetadata["verification.status"] = verificationStep.status.rawValue- for (key, value) in verificationStep.metadata {- runMetadata["verification.\(key)"] = value- }- }- let status = status(for: finalActionPlan.terminalState)- if status == .completed {- stepTracker.complete(- .verify,- summary: "Local app task result verified",- metadata: ["terminalState": finalActionPlan.terminalState.rawValue]- )- await coordinator?.complete(reason: "Local app task completed")- } else {- stepTracker.block(- .verify,- summary: "Local app task needs user review after verification",- metadata: ["terminalState": finalActionPlan.terminalState.rawValue]- )- await coordinator?.pause(reason: "Local app task needs user review")- }- let progress = stepTracker.snapshot()- return LocalAppTaskLiveRunResult(- command: command,- traceID: traceID,- status: status,- resolution: resolution,- initialActionPlan: initialActionPlan,- finalActionPlan: finalActionPlan,- observation: finalObservation,- actionTraces: actionTraces,- workflowProgress: progress,- metadata: runMetadata.merging([- "executedCommandCount": String(actionTraces.filter(\.executed).count),- "skippedNoLiveInputCommandCount": String(actionTraces.filter { $0.decision == .skippedNoLiveInput }.count)- ], uniquingKeysWith: { current, _ in current }).merging(- Self.workflowProgressMetadata(progress),- uniquingKeysWith: { current, _ in current }- )- )- }-- public static func defaultActionEngine(for definition: LocalAppTaskDefinition) -> ActionEngineGuardrail {- let inputBackend: any ActionEngineInputBackend = definition.metadata["automationBackend"] == "appleScript"- ? MacAppleScriptActionEngineInputBackend()- : MacKeyboardActionEngineInputBackend()-- return ActionEngineGuardrail(- configuration: ActionEngineConfiguration(liveInputEnabled: true),- focusGuard: MacLocalAppFocusGuard(- targetID: LocalAppTaskAdapter(definition: definition).targetID,- bundleIdentifier: definition.targetApp.bundleIdentifier- ),- inputBackend: inputBackend- )- }-- public static func accessibilityActionEngine(for definition: LocalAppTaskDefinition) -> ActionEngineGuardrail {- ActionEngineGuardrail(- configuration: ActionEngineConfiguration(liveInputEnabled: true),- focusGuard: MacLocalAppFocusGuard(- targetID: LocalAppTaskAdapter(definition: definition).targetID,- bundleIdentifier: definition.targetApp.bundleIdentifier- ),- inputBackend: MacAccessibilityActionEngineInputBackend()- )- }-- private func unresolvedResult(- command: String,- traceID: String,- resolution: LocalAppTaskCatalogResolution,- workflowProgress: LocalAppTaskWorkflowProgress,- metadata: [String: String]- ) -> LocalAppTaskLiveRunResult {- let status: LocalAppTaskLiveRunStatus- switch resolution.status {- case .resolved:- status = .failedSafe- case .needsConfirmation:- status = .needsConfirmation- case .unsupportedCommand:- status = .unsupportedCommand- case .appUnavailable:- status = .appUnavailable- }-- return LocalAppTaskLiveRunResult(- command: command,- traceID: traceID,- status: status,- resolution: resolution,- workflowProgress: workflowProgress,- metadata: metadata- )- }-- private func publishUnresolvedRun(- command: String,- traceID: String,- resolution: LocalAppTaskCatalogResolution- ) async {- await publishRunStart(- command: command,- traceID: traceID,- targetID: resolution.definition.map { LocalAppTaskAdapter(definition: $0).targetID }- ?? "local-app-task-unresolved"- )- await coordinator?.recordToolEvent(- capability: .controller,- decision: .deny(reason: resolution.metadata["reason"] ?? resolution.status.rawValue),- toolName: "local-app-task-catalog",- summary: "Local app task could not be resolved",- traceID: traceID,- metadata: resolution.metadata.merging([- "resolution.status": resolution.status.rawValue- ]) { current, _ in current }- )-- switch resolution.status {- case .needsConfirmation:- await coordinator?.pause(reason: "Local app task needs confirmation")- case .unsupportedCommand, .appUnavailable, .resolved:- await coordinator?.fail(reason: "Local app task could not be resolved")- }- }-- private func publishRunStart(- command: String,- traceID: String,- targetID: String- ) async {- guard let coordinator else { return }-- await coordinator.setTraceID(traceID)- _ = await coordinator.start(- RunSession(- userGoal: command,- targetID: targetID,- runtimeProfile: "local-app-task",- permissionPolicy: permissionPolicy- )- )- }-- @MainActor- private func accessibilityCommandTemplates(- intent: TaskIntent,- definition: LocalAppTaskDefinition- ) -> [ActionEngineCommand] {- guard AXIsProcessTrusted(),- let target = try? MacWindowResolver().selectTarget(),- target.bundleIdentifier == definition.targetApp.bundleIdentifier- else {- return []- }-- let limits = MacAccessibilitySnapshotLimits(maxDepth: 6, maxChildrenPerNode: 80, maxTotalNodes: 500)- guard let tree = try? ApplicationServicesMacAccessibilitySnapshotCapturer().captureTree(- target: target,- limits: limits- ) else {- return []- }- let snapshot = MacAccessibilitySnapshot(- target: target,- limits: limits,- root: tree.root,- totalNodeCount: tree.totalNodeCount,- isTreeTruncated: tree.isTreeTruncated- )- let index = LocalAppAccessibilityControlDiscovery().discover(in: snapshot)- return LocalAppAccessibilityActionPlanner().commands(- for: intent,- definition: definition,- index: index,- issuedAt: Self.now()- )- }-- private func observationWithActionEvidence(- _ observation: LocalAppTaskObservation,- actionTraces: [ActionEngineCommandTrace]- ) -> LocalAppTaskObservation {- var enriched = observation- let executed = actionTraces.filter(\.executed)- let submitCount = executed.filter { Self.isReturnSubmitCommand($0.command) }.count- enriched.metadata.merge([- "postActionObservation": "true",- "executedCommandCount": String(executed.count),- "submittedCommandCount": String(submitCount)- ]) { current, _ in current }- return enriched- }-- private static func isReturnSubmitCommand(_ command: ActionEngineCommand) -> Bool {- command.metadata["workflowStepRole"] == LocalAppTaskStepRole.submit.rawValue- && command.key == "Return"- }-- private func status(for terminalState: LocalAppTaskTerminalState) -> LocalAppTaskLiveRunStatus {- switch terminalState {- case .completed:- return .completed- case .needsUserReview:- return .needsUserReview- case .failedSafe, .timedOut:- return .failedSafe- }- }-- private func blockedEvidencePlanStatus(- for terminalState: LocalAppTaskTerminalState- ) -> LocalAppTaskLiveRunStatus {- switch terminalState {- case .completed, .needsUserReview:- return .needsUserReview- case .failedSafe, .timedOut:- return .failedSafe- }- }-- private func decisionReason(_ decision: ActionEngineCommandDecision) -> String {- switch decision {- case .denied(let reason):- return reason- case .skippedNoLiveInput:- return "skippedNoLiveInput"- case .executedLive:- return "executedLive"- }- }-- private func workflowStepID(from command: ActionEngineCommand) -> String? {- if let workflowStepID = command.metadata["workflowStepID"] {- return workflowStepID- }-- guard let markerRange = command.id.range(of: "-ax-") else {- return command.metadata["workflowStepRole"]- }-- return String(command.id[markerRange.upperBound...])- }-- private static func now(advancedByMilliseconds milliseconds: Double = 0) -> RunTraceTimestamp {- let now = ProcessInfo.processInfo.systemUptime- return RunTraceTimestamp(- wallClock: Date().addingTimeInterval(milliseconds / 1_000),- monotonicUptimeNanoseconds: UInt64((now * 1_000_000_000) + (milliseconds * 1_000_000))- )- }-- private static func uptimeMilliseconds() -> Double {- ProcessInfo.processInfo.systemUptime * 1_000- }-- private static func formatLatency(_ milliseconds: Double) -> String {- String(format: "%.3f", max(0, milliseconds))- }-- private static func workflowProgressMetadata(- _ progress: LocalAppTaskWorkflowProgress- ) -> [String: String] {- Dictionary(- uniqueKeysWithValues: progress.stages.map { state in- ("workflow.\(state.stage.rawValue).status", state.status.rawValue)- }- )- }-- private static func actionTraceMetadata(_ traces: [ActionEngineCommandTrace]) -> [String: String] {- guard !traces.isEmpty else { return [:] }-- let lastTrace = traces[traces.count - 1]- let backends = Set(traces.compactMap { trace in- trace.metadata["liveInputBackend"]- }).sorted()- let elementClickCount = traces.filter { trace in- isElementClick(trace.command)- }.count- let targetedElementCount = traces.filter { trace in- trace.command.targetBounds != nil || trace.command.metadata["controlID"]?.isEmpty == false- }.count-- return [- "action.traceCount": String(traces.count),- "action.executedCount": String(traces.filter(\.executed).count),- "action.backends": backends.joined(separator: ","),- "action.elementClickCount": String(elementClickCount),- "action.targetedElementCount": String(targetedElementCount),- "action.lastCommandID": lastTrace.command.id,- "action.lastCommandKind": lastTrace.command.kind.rawValue,- "action.lastDecision": decisionDescription(lastTrace.decision),- "action.lastBackend": lastTrace.metadata["liveInputBackend"] ?? "",- "action.lastTarget": actionTargetDescription(lastTrace.command),- "action.lastAppleScriptOutput": lastTrace.metadata["appleScript.output"] ?? "",- "action.lastAccessibilityResult": lastTrace.metadata["accessibility.result"] ?? "",- "action.overlayPointer": "visualOnly"- ]- }-- private static func isElementClick(_ command: ActionEngineCommand) -> Bool {- (command.kind == .tap || command.kind == .mouse) &&- (command.targetBounds != nil || command.metadata["controlID"]?.isEmpty == false)- }-- private static func actionTargetDescription(_ command: ActionEngineCommand) -> String {- if let controlID = command.metadata["controlID"],- !controlID.isEmpty {- return "control:\(controlID)"- }- guard let bounds = command.targetBounds else { return "none" }- return String(- format: "bounds:x=%.3f,y=%.3f,w=%.3f,h=%.3f,space=%@",- bounds.origin.x,- bounds.origin.y,- bounds.size.width,- bounds.size.height,- bounds.space.rawValue- )- }-- private static func decisionDescription(_ decision: ActionEngineCommandDecision) -> String {- switch decision {- case .skippedNoLiveInput:- return "skippedNoLiveInput"- case .executedLive:- return "executedLive"- case .denied(let reason):- return "denied:\(reason)"- }- }-}--public struct MacLocalAppFocusGuard: ActionEngineFocusGuard {- public var targetID: String- public var bundleIdentifier: String?-- public init(targetID: String, bundleIdentifier: String?) {- self.targetID = targetID- self.bundleIdentifier = bundleIdentifier- }-- public func targetIsSafeForInput(targetID: String) async -> Bool {- guard targetID == self.targetID,- let bundleIdentifier- else {- return false- }-- return await MainActor.run {- NSWorkspace.shared.frontmostApplication?.bundleIdentifier == bundleIdentifier- }- }-}--public struct MacLocalAppTaskController: LocalAppTaskAppControlling {- public var uiUnderstandingRunner: any LocalUIUnderstandingRunning-- public init(- uiUnderstandingRunner: any LocalUIUnderstandingRunning = ProcessBackedLocalUIUnderstandingAdapter()- ) {- self.uiUnderstandingRunner = uiUnderstandingRunner- }-- @MainActor- public func launchOrFocus(- definition: LocalAppTaskDefinition,- availability: LocalAppAvailability- ) async -> LocalAppTaskObservation {- if let itemURL = availability.appURL,- let itemKind = availability.metadata["itemKind"],- itemKind != "application" {- let opened = await openLocalItem(at: itemURL)- if let bundleIdentifier = definition.targetApp.bundleIdentifier {- await waitForFrontmostApplication(- LocalAppTarget(- appName: definition.targetApp.appName,- bundleIdentifier: bundleIdentifier,- titleContains: definition.targetApp.titleContains- )- )- }- let isFocused = definition.targetApp.bundleIdentifier == nil- || NSWorkspace.shared.frontmostApplication?.bundleIdentifier == definition.targetApp.bundleIdentifier- return LocalAppTaskObservation(- appIsRunning: opened,- appIsFocused: opened && isFocused,- availableControls: [:],- visibleText: ["appName": definition.targetApp.appName],- confidence: opened ? 0.72 : 0.2,- metadata: [- "observer": "mac-local-app-controller",- "openedLocalItem": String(opened),- "localItem.kind": itemKind,- "localItem.path": itemURL.path,- "defaultApplication": availability.metadata["defaultApplication"] ?? ""- ]- )- }-- if let appURL = availability.appURL {- await openApplication(at: appURL)- } else if let runningApplication = runningApplication(for: definition.targetApp) {- runningApplication.activate(options: [.activateAllWindows])- }-- await waitForFrontmostApplication(definition.targetApp)- return await observe(definition: definition)- }-- @MainActor- public func observe(definition: LocalAppTaskDefinition) async -> LocalAppTaskObservation {- let runningApplication = runningApplication(for: definition.targetApp)- let isFocused = NSWorkspace.shared.frontmostApplication?.bundleIdentifier == definition.targetApp.bundleIdentifier- let verificationKey = definition.metadata["verificationTextKey"]- ?? definition.verificationEntityName- ?? "visibleText"- let accessibilityIndex = accessibilityControlIndex(for: definition, runningApplication: runningApplication)- let visibleText = accessibilityIndex?.visibleText ?? accessibilityVisibleText(for: runningApplication)- var controls: [String: Bool] = Dictionary(- uniqueKeysWithValues: definition.workflowSteps.compactMap { step in- guard step.role == .focusControl,- let controlID = step.metadata["controlID"]- else {- return nil- }- let discovered = accessibilityIndex?.firstControl(matching: controlID) != nil- return (controlID, discovered)- }- )-- var textValues: [String: String] = [:]- if let visibleText {- textValues["visibleText"] = visibleText- textValues[verificationKey] = visibleText- }-- var accessibilityMetadata = [- "observer": "mac-local-app-controller",- "accessibilityTrusted": String(AXIsProcessTrusted()),- "accessibilityControlDiscovery": String(accessibilityIndex != nil),- "accessibilityControlCount": accessibilityIndex?.metadata["controlCount"] ?? "0"- ].merging(accessibilityIndex?.metadata ?? [:]) { current, _ in current }- for step in definition.workflowSteps {- guard let controlID = step.metadata["controlID"],- let control = accessibilityIndex?.firstControl(matching: controlID)- else {- continue- }- let frame = control.frame.map {- HotLoopRect(- x: $0.x,- y: $0.y,- width: $0.width,- height: $0.height,- space: .screen- )- }- accessibilityMetadata.merge(- LocalAppObservationGeometry.controlMetadata(- controlID: controlID,- frame: frame,- source: .accessibility,- label: control.label,- kind: control.kind,- confidence: 0.86,- extra: control.metadata- )- ) { current, _ in current }- }-- let accessibilityObservation = LocalAppTaskObservation(- appIsRunning: runningApplication != nil,- appIsFocused: isFocused,- availableControls: controls,- visibleText: textValues,- confidence: accessibilityIndex == nil ? (visibleText == nil ? 0.4 : 0.75) : 0.86,- metadata: accessibilityMetadata- )-- guard shouldIncludeScreenshotUnderstanding(- definition: definition,- accessibilityObservation: accessibilityObservation,- verificationKey: verificationKey- ) else {- return accessibilityObservation- }-- guard let screenshotObservation = await screenshotUnderstandingObservation(- definition: definition,- runningApplication: runningApplication,- isFocused: isFocused,- verificationKey: verificationKey- ) else {- var metadata = accessibilityObservation.metadata- metadata["screenshotUnderstanding.status"] = "unavailable"- return LocalAppTaskObservation(- appIsRunning: accessibilityObservation.appIsRunning,- appIsFocused: accessibilityObservation.appIsFocused,- availableControls: accessibilityObservation.availableControls,- visibleText: accessibilityObservation.visibleText,- confidence: accessibilityObservation.confidence,- metadata: metadata- )- }-- controls.merge(screenshotObservation.availableControls) { current, new in current || new }- return LocalAppTaskObservation(- appIsRunning: accessibilityObservation.appIsRunning || screenshotObservation.appIsRunning,- appIsFocused: accessibilityObservation.appIsFocused || screenshotObservation.appIsFocused,- availableControls: controls,- visibleText: accessibilityObservation.visibleText.merging(- screenshotObservation.visibleText- ) { current, _ in current },- confidence: max(accessibilityObservation.confidence, screenshotObservation.confidence),- metadata: accessibilityObservation.metadata.merging(- screenshotObservation.metadata- ) { current, _ in current }- )- }-- private func shouldIncludeScreenshotUnderstanding(- definition: LocalAppTaskDefinition,- accessibilityObservation: LocalAppTaskObservation,- verificationKey: String- ) -> Bool {- LocalAppTaskObservationFallbackPolicy.shouldUseScreenshotUnderstanding(- definition: definition,- accessibilityObservation: accessibilityObservation,- verificationKey: verificationKey- )- }-- @MainActor- private func screenshotUnderstandingObservation(- definition: LocalAppTaskDefinition,- runningApplication: NSRunningApplication?,- isFocused: Bool,- verificationKey: String- ) async -> LocalAppTaskObservation? {- guard runningApplication != nil,- let target = try? MacWindowResolver().selectTarget(),- target.bundleIdentifier == definition.targetApp.bundleIdentifier,- target.safetyAssessment.status == .allowed- else {- return nil- }-- let screenshot: CapturedWindowScreenshot- do {- screenshot = try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: target)- } catch {- return nil- }-- let imageURL = FileManager.default.temporaryDirectory- .appendingPathComponent("donkey-ui-understanding-\(UUID().uuidString).png")- do {- try screenshot.pngData.write(to: imageURL, options: .atomic)- } catch {- return nil- }- defer {- try? FileManager.default.removeItem(at: imageURL)- }-- let request = LocalUIUnderstandingRequest(- traceID: "local-ui-understanding-\(UUID().uuidString)",- targetID: LocalAppTaskAdapter(definition: definition).targetID,- appIsRunning: true,- appIsFocused: isFocused,- imageFileURL: imageURL,- cropBounds: HotLoopRect(- x: 0,- y: 0,- width: Double(screenshot.imageWidth),- height: Double(screenshot.imageHeight),- space: .window- ),- pixelSize: HotLoopSize(- width: Double(screenshot.imageWidth),- height: Double(screenshot.imageHeight),- space: .window- ),- metadata: [- "observer": "mac-local-app-controller",- "observation.source": "screenshot",- "verificationTextKey": verificationKey,- "screenshot.scope": "targetWindow",- "screenshot.desktopCaptureAllowed": "false",- "target.windowID": String(target.windowID),- "capture.method": screenshot.captureMethod.rawValue- ].merging(LocalAppObservationGeometry.targetBoundsMetadata(target.bounds)) { current, _ in current }- )-- do {- return try await uiUnderstandingRunner.understand(request).observation(for: request)- } catch {- return nil- }- }-- @MainActor- private func accessibilityControlIndex(- for definition: LocalAppTaskDefinition,- runningApplication: NSRunningApplication?- ) -> LocalAppAccessibilityControlIndex? {- guard AXIsProcessTrusted(),- runningApplication != nil,- let target = try? MacWindowResolver().selectTarget(),- target.bundleIdentifier == definition.targetApp.bundleIdentifier- else {- return nil- }-- let limits = MacAccessibilitySnapshotLimits(maxDepth: 6, maxChildrenPerNode: 80, maxTotalNodes: 500)- guard let tree = try? ApplicationServicesMacAccessibilitySnapshotCapturer().captureTree(- target: target,- limits: limits- ) else {- return nil- }- let snapshot = MacAccessibilitySnapshot(- target: target,- limits: limits,- root: tree.root,- totalNodeCount: tree.totalNodeCount,- isTreeTruncated: tree.isTreeTruncated- )- return LocalAppAccessibilityControlDiscovery().discover(in: snapshot)- }-- @MainActor- private func runningApplication(for target: LocalAppTarget) -> NSRunningApplication? {- guard let bundleIdentifier = target.bundleIdentifier else { return nil }- return NSRunningApplication- .runningApplications(withBundleIdentifier: bundleIdentifier)- .first- }-- @MainActor- private func openApplication(at url: URL) async {- await withCheckedContinuation { continuation in- let configuration = NSWorkspace.OpenConfiguration()- configuration.activates = true- NSWorkspace.shared.openApplication(- at: url,- configuration: configuration- ) { _, _ in- continuation.resume()- }- }- }-- @MainActor- private func openLocalItem(at url: URL) async -> Bool {- NSWorkspace.shared.open(url)- }-- @MainActor- private func waitForFrontmostApplication(_ target: LocalAppTarget) async {- let bundleIdentifier = target.bundleIdentifier- for _ in 0..<16 {- if NSWorkspace.shared.frontmostApplication?.bundleIdentifier == bundleIdentifier {- return- }- try? await Task.sleep(nanoseconds: 125_000_000)- }- }-- @MainActor- private func accessibilityVisibleText(for application: NSRunningApplication?) -> String? {- guard AXIsProcessTrusted(),- let processIdentifier = application?.processIdentifier- else {- return nil- }-- let appElement = AXUIElementCreateApplication(processIdentifier)- let elements = windows(from: appElement)- let roots = elements.isEmpty ? [appElement] : elements- let values = roots.flatMap { textValues(from: $0, depth: 0, remaining: 160) }- let joined = values- .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }- .filter { !$0.isEmpty }- .joined(separator: " ")- return joined.isEmpty ? nil : joined- }-- @MainActor- private func windows(from appElement: AXUIElement) -> [AXUIElement] {- var value: CFTypeRef?- guard AXUIElementCopyAttributeValue(- appElement,- kAXWindowsAttribute as CFString,- &value- ) == .success else {- return []- }-- return value as? [AXUIElement] ?? []- }-- @MainActor- private func textValues(- from element: AXUIElement,- depth: Int,- remaining: Int- ) -> [String] {- guard depth <= 8, remaining > 0 else { return [] }-- var values: [String] = []- for attribute in [- kAXTitleAttribute,- kAXDescriptionAttribute,- kAXValueAttribute,- kAXHelpAttribute- ] {- if let text = stringAttribute(attribute as CFString, from: element) {- values.append(text)- }- }-- let children = children(from: element)- let nextRemaining = max(0, remaining - values.count)- for child in children.prefix(nextRemaining) {- values.append(contentsOf: textValues(- from: child,- depth: depth + 1,- remaining: max(0, nextRemaining - values.count)- ))- if values.count >= remaining {- break- }- }-- return values- }-- @MainActor- private func children(from element: AXUIElement) -> [AXUIElement] {- var value: CFTypeRef?- guard AXUIElementCopyAttributeValue(- element,- kAXChildrenAttribute as CFString,- &value- ) == .success else {- return []- }-- return value as? [AXUIElement] ?? []- }-- @MainActor- private func stringAttribute(_ attribute: CFString, from element: AXUIElement) -> String? {- var value: CFTypeRef?- guard AXUIElementCopyAttributeValue(element, attribute, &value) == .success,- let value- else {- return nil- }-- if let string = value as? String {- return string- }- if let number = value as? NSNumber {- return number.stringValue- }- return nil- }-}--private extension ActionEngineCommand {- var commandName: String {- metadata["taskType"] ?? id- }-- func withIssuedAt(_ issuedAt: RunTraceTimestamp) -> ActionEngineCommand {- ActionEngineCommand(- id: id,- traceID: traceID,- targetID: targetID,- stateID: stateID,- actionID: actionID,- kind: kind,- issuedAt: issuedAt,- targetBounds: targetBounds,- key: key,- holdDurationMS: holdDurationMS,- metadata: metadata- )- }-}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex fbcc9b8f..07845daf 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -184,10 +184,10 @@ struct AIHarnessAdapterTests {router: AIModelRouter(registry: localVoiceRegistry()),runtime: FakeVoiceRuntime(transcript: LocalVoiceTranscript(- text: "play Coldplay",+ text: "show weather",language: "en",confidence: 0.91,- segments: ["play Coldplay"]+ segments: ["show weather"])),now: fixedClock([10, 42])@@ -203,7 +203,7 @@ struct AIHarnessAdapterTests {))- #expect(result.transcript?.text == "play Coldplay")+ #expect(result.transcript?.text == "show weather")#expect(result.trace.status == .completed)#expect(result.trace.role == .voiceTranscription)#expect(result.trace.modelID == "nvidia/parakeet-tdt-0.6b-v3")@@ -254,7 +254,7 @@ struct AIHarnessAdapterTests {result: LocalJSONSidecarResult(status: .completed,outputData: Data("""- {"text":"play Coldplay","language":"en","confidence":0.94,"segments":["play Coldplay"],"metadata":{"decoder":"fake-parakeet"}}+ {"text":"show weather","language":"en","confidence":0.94,"segments":["show weather"],"metadata":{"decoder":"fake-parakeet"}}""".utf8),metadata: ["sidecar.reason": "completed"])@@ -275,7 +275,7 @@ struct AIHarnessAdapterTests {))- #expect(transcript.text == "play Coldplay")+ #expect(transcript.text == "show weather")#expect(transcript.language == "en")#expect(transcript.metadata["decoder"] == "fake-parakeet")}@@ -332,55 +332,21 @@ struct AIHarnessAdapterTests {#expect(failed.metadata["sidecar.reason"] == "nonZeroExit")}- @Test- func processBackedLocalLLMTaskIntentAdapterDecodesValidatedIntent() async throws {- let adapter = ProcessBackedLocalLLMTaskIntentAdapter(- router: AIModelRouter(registry: .defaultHybridPlanner),- sidecarRunner: FakeSidecarRunner(- result: LocalJSONSidecarResult(- status: .completed,- outputData: Data("""- {"outputText":"{\\"taskType\\":\\"local_app_interaction\\",\\"targetAppName\\":\\"Music\\",\\"entities\\":{\\"appName\\":\\"Music\\",\\"goal\\":\\"play media\\",\\"query\\":\\"Viva La Vida Coldplay\\"},\\"normalizedEntities\\":{\\"appName\\":\\"Music\\",\\"goal\\":\\"play media\\",\\"query\\":\\"Viva La Vida Coldplay\\"},\\"confidence\\":0.91,\\"needsConfirmation\\":false,\\"actionPlan\\":{\\"tools\\":[\\"app.openOrFocus\\",\\"app.observe\\",\\"ui.focusSearch\\",\\"ui.setText\\",\\"ui.pressReturn\\",\\"app.verifyCommand\\"],\\"inputEntity\\":\\"query\\",\\"controlID\\":\\"search\\",\\"focusKey\\":\\"Command+F\\",\\"verification\\":\\"commandAttempted\\"},\\"metadata\\":{\\"source\\":\\"test\\",\\"mediaSelection.kind\\":\\"representative_song\\",\\"mediaSelection.seed\\":\\"Coldplay\\",\\"mediaSelection.selectedTitle\\":\\"Viva La Vida\\",\\"mediaSelection.reason\\":\\"User asked for Coldplay, so choose a concrete song.\\"}}","metadata":{"local.provider":"donkey-local-llm-sidecar"}}- """.utf8),- latencyMS: 14,- metadata: ["sidecar.role": "taskIntent"]- )- )- )-- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: "play cold play",- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- sourceTraceID: "trace-local-llm"- )- )-- #expect(result.intent?.taskType == "local_app_interaction")- #expect(result.intent?.targetApp.appName == "Music")- #expect(result.intent?.normalizedEntities["query"] == "Viva La Vida Coldplay")- #expect(result.intent?.metadata["mediaSelection.selectedTitle"] == "Viva La Vida")- #expect(result.intent?.metadata["parser"] == "local-llm-sidecar-v1")- #expect(result.trace.provider == .localRuntime)- #expect(result.trace.status == .completed)- #expect(result.trace.metadata["local.provider"] == "donkey-local-llm-sidecar")- }-@Testfunc hostedTaskIntentAdapterUsesBackendResponsesProxy() async throws {let httpClient = FakeAIHTTPClient(data: responseData(outputText: hostedPlanningOutput(- goal: "play Viva La Vida by Coldplay",+ goal: "open cnn.com in Safari",taskType: "local_app_interaction",- targetAppName: "Music",- entitiesJSON: #"{"appName":"Music","goal":"play media","query":"Viva La Vida Coldplay"}"#,- normalizedEntitiesJSON: #"{"appName":"Music","goal":"play media","query":"Viva La Vida Coldplay"}"#,+ targetAppName: "Safari",+ entitiesJSON: #"{"appName":"Safari","goal":"open requested website","query":"https://cnn.com"}"#,+ normalizedEntitiesJSON: #"{"appName":"Safari","goal":"open requested website","query":"https://cnn.com"}"#,confidence: 0.91,- planStepsJSON: #"[{"id":"launch","summary":"Open Music.","toolName":"app.openOrFocus","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Music is focused."},{"id":"focus-search","summary":"Focus search.","toolName":"ui.focusSearch","inputEntity":"","controlID":"search","focusKey":"Command+F","expectedObservation":"Search is focused."},{"id":"set-query","summary":"Enter media query.","toolName":"ui.setText","inputEntity":"query","controlID":"search","focusKey":"","expectedObservation":"Query is entered."},{"id":"submit","summary":"Submit search.","toolName":"ui.pressReturn","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Search is submitted."},{"id":"verify","summary":"Verify command.","toolName":"app.verifyCommand","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Playback command is attempted."}]"#,- verificationCriteriaJSON: #"["Playback command is attempted for the concrete selected song."]"#,- fallbacksJSON: #"["Ask before playing if the selected media is ambiguous."]"#,- metadataJSON: #"{"source":"test","mediaSelection.kind":"representative_song","mediaSelection.seed":"Coldplay","mediaSelection.selectedTitle":"Viva La Vida","mediaSelection.reason":"User asked for Coldplay, so choose a concrete song."}"#+ planStepsJSON: #"[{"id":"launch","summary":"Open Safari.","toolName":"app.openOrFocus","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Safari is focused."},{"id":"focus-address","summary":"Focus address bar.","toolName":"ui.focusAddressBar","inputEntity":"","controlID":"addressBar","focusKey":"Command+L","expectedObservation":"Address bar is focused."},{"id":"set-url","summary":"Enter URL.","toolName":"ui.setText","inputEntity":"query","controlID":"addressBar","focusKey":"","expectedObservation":"URL is entered."},{"id":"submit","summary":"Submit navigation.","toolName":"ui.pressReturn","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Navigation is submitted."},{"id":"verify","summary":"Verify command.","toolName":"app.verifyCommand","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Navigation command is attempted."}]"#,+ verificationCriteriaJSON: #"["Navigation command is attempted."]"#,+ fallbacksJSON: #"["Ask if the website is ambiguous."]"#,+ metadataJSON: #"{"source":"test"}"#)),statusCode: 200@@ -395,7 +361,7 @@ struct AIHarnessAdapterTests {let result = await adapter.parseTaskIntent(TaskIntentAdapterRequest(- command: "play cold play",+ command: "open cnn.com",taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,sourceTraceID: "trace-hosted-intent")@@ -428,17 +394,15 @@ struct AIHarnessAdapterTests {#expect(properties["fallbacks"] != nil)#expect(properties["clarificationPolicy"] != nil)#expect(result.intent?.metadata["genericHarness.schemaVersion"] == "generic_harness_planning")- #expect(result.intent?.metadata["genericHarness.intent.goal"] == "play Viva La Vida by Coldplay")+ #expect(result.intent?.metadata["genericHarness.intent.goal"] == "open cnn.com in Safari")#expect(instructions.contains("local_app_interaction"))#expect(instructions.contains("App skill guidance"))#expect(instructions.contains("metadata.assistantResponse"))- #expect(instructions.contains("play/listen media requests") == false)let input = try #require(body["input"] as? [[String: Any]])let firstInput = try #require(input.first)let content = try #require(firstInput["content"] as? [[String: Any]])let prompt = try #require(content.first?["text"] as? String)- #expect(prompt.contains("Skill ID: music-media"))- #expect(prompt.contains("mediaSelection.selectedTitle"))+ #expect(prompt.contains("Skill ID: browser-navigation"))}@Test@@ -467,7 +431,7 @@ struct AIHarnessAdapterTests {let result = await adapter.parseTaskIntent(TaskIntentAdapterRequest(command: "hi there",- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,sourceTraceID: "trace-hosted-greeting"))@@ -585,7 +549,7 @@ struct AIHarnessAdapterTests {result: LocalJSONSidecarResult(status: .completed,outputData: Data("""- {"outputText":"{\\"taskType\\":\\"local_app_interaction\\",\\"targetAppName\\":\\"Music\\",\\"entities\\":{\\"appName\\":\\"Music\\",\\"goal\\":\\"play media\\",\\"query\\":\\"justin bieber\\"},\\"normalizedEntities\\":{\\"appName\\":\\"Music\\",\\"goal\\":\\"play media\\",\\"query\\":\\"Justin Bieber\\"},\\"confidence\\":0.91,\\"needsConfirmation\\":false,\\"actionPlan\\":{\\"tools\\":[\\"app.openOrFocus\\",\\"app.observe\\",\\"ui.focusSearch\\",\\"ui.setText\\",\\"ui.pressReturn\\",\\"ui.pressReturn\\",\\"app.verifyCommand\\"],\\"inputEntity\\":\\"query\\",\\"controlID\\":\\"search\\",\\"focusKey\\":\\"Command+F\\",\\"verification\\":\\"commandAttempted\\"},\\"metadata\\":{}}","metadata":{"local.provider":"donkey-local-llm-sidecar"}}+ {"outputText":"{\\"taskType\\":\\"local_app_interaction\\",\\"targetAppName\\":\\"Music\\",\\"entities\\":{\\"appName\\":\\"Music\\",\\"goal\\":\\"play media\\",\\"query\\":\\"sample track\\"},\\"normalizedEntities\\":{\\"appName\\":\\"Music\\",\\"goal\\":\\"play media\\",\\"query\\":\\"Sample Track\\"},\\"confidence\\":0.91,\\"needsConfirmation\\":false,\\"actionPlan\\":{\\"tools\\":[\\"app.openOrFocus\\",\\"app.observe\\",\\"ui.focusSearch\\",\\"ui.setText\\",\\"ui.pressReturn\\",\\"ui.pressReturn\\",\\"app.verifyCommand\\"],\\"inputEntity\\":\\"query\\",\\"controlID\\":\\"search\\",\\"focusKey\\":\\"Command+F\\",\\"verification\\":\\"commandAttempted\\"},\\"metadata\\":{}}","metadata":{"local.provider":"donkey-local-llm-sidecar"}}""".utf8),latencyMS: 14,metadata: ["sidecar.role": "taskIntent"]@@ -595,7 +559,7 @@ struct AIHarnessAdapterTests {let result = await adapter.parseTaskIntent(TaskIntentAdapterRequest(- command: "play some justin bieber",+ command: "play sample track",taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,contextSnippets: ["Music application com.apple.Music"],sourceTraceID: "trace-local-app-plan"@@ -604,50 +568,12 @@ struct AIHarnessAdapterTests {#expect(result.intent?.taskType == "local_app_interaction")#expect(result.intent?.targetApp.appName == "Music")- #expect(result.intent?.normalizedEntities["query"] == "Justin Bieber")+ #expect(result.intent?.normalizedEntities["query"] == "Sample Track")#expect(result.intent?.actionPlan?.tools.contains(.setText) == true)#expect(result.intent?.actionPlan?.inputEntity == "query")#expect(result.trace.status == .completed)}- @Test- func taskIntentDecoderPreservesMediaSelectionForVagueArtistRequest() async throws {- let adapter = ProcessBackedLocalLLMTaskIntentAdapter(- router: AIModelRouter(registry: .defaultHybridPlanner),- sidecarRunner: FakeSidecarRunner(- result: LocalJSONSidecarResult(- status: .completed,- outputData: try localLLMSidecarOutputData(- outputText: """- {"taskType":"local_app_interaction","targetAppName":"Music","entities":{"appName":"Music","goal":"play media","query":"Viva La Vida Coldplay"},"normalizedEntities":{"appName":"Music","goal":"play media","query":"Viva La Vida Coldplay"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{"appFinder.selectedCapabilityID":"play_media","mediaSelection.kind":"representative_song","mediaSelection.seed":"Coldplay","mediaSelection.selectedTitle":"Viva La Vida","mediaSelection.reason":"User asked for some Coldplay, so choose a concrete song instead of an artist-only search."}}- """,- metadata: ["local.provider": "donkey-local-llm-sidecar"]- ),- latencyMS: 14,- metadata: ["sidecar.role": "taskIntent"]- )- )- )-- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: "play some coldplay",- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- contextSnippets: ["Music application com.apple.Music"],- sourceTraceID: "trace-media-selection"- )- )-- #expect(result.intent?.taskType == "local_app_interaction")- #expect(result.intent?.targetApp.appName == "Music")- #expect(result.intent?.normalizedEntities["query"] == "Viva La Vida Coldplay")- #expect(result.intent?.metadata["mediaSelection.kind"] == "representative_song")- #expect(result.intent?.metadata["mediaSelection.seed"] == "Coldplay")- #expect(result.intent?.metadata["mediaSelection.selectedTitle"] == "Viva La Vida")- #expect(result.intent?.metadata["appFinder.selectedCapabilityID"] == "play_media")- #expect(result.trace.status == .completed)- }-@Testfunc taskIntentDecoderGroundsGenericInteractionInAppFinderCatalog() async throws {let appFinderCatalog = StaticLocalAppAvailabilityProvider(@@ -660,7 +586,7 @@ struct AIHarnessAdapterTests {status: .completed,outputData: try localLLMSidecarOutputData(outputText: """- {"taskType":"local_app_interaction","targetAppName":"Music","entities":{"appName":"Music","goal":"play media","query":"Baby Justin Bieber"},"normalizedEntities":{"appName":"Music","goal":"play media","query":"Baby Justin Bieber"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{"appFinder.selectedAppID":"com.apple.Music","appFinder.selectedCapabilityID":"play_media","appFinder.controlProfile":"search_then_enter","mediaSelection.kind":"representative_song","mediaSelection.seed":"Justin Bieber","mediaSelection.selectedTitle":"Baby","mediaSelection.reason":"User asked for some Justin Bieber, so choose a concrete song."}}+ {"taskType":"local_app_interaction","targetAppName":"Music","entities":{"appName":"Music","goal":"play media","query":"Sample Track"},"normalizedEntities":{"appName":"Music","goal":"play media","query":"Sample Track"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{"appFinder.selectedAppID":"com.apple.Music","appFinder.selectedCapabilityID":"play_media","appFinder.controlProfile":"search_then_enter"}}""",metadata: ["local.provider": "donkey-local-llm-sidecar"]),@@ -672,7 +598,7 @@ struct AIHarnessAdapterTests {let result = await adapter.parseTaskIntent(TaskIntentAdapterRequest(- command: "play some justin bieber",+ command: "play sample track",taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,appFinderCatalog: appFinderCatalog,sourceTraceID: "trace-app-finder-grounded"@@ -682,52 +608,12 @@ struct AIHarnessAdapterTests {#expect(result.intent?.taskType == "local_app_interaction")#expect(result.intent?.targetApp.appName == "Music")#expect(result.intent?.targetApp.bundleIdentifier == "com.apple.Music")- #expect(result.intent?.normalizedEntities["query"] == "Baby Justin Bieber")+ #expect(result.intent?.normalizedEntities["query"] == "Sample Track")#expect(result.intent?.metadata["appFinder.validated"] == "true")#expect(result.intent?.metadata["appFinder.selectedCapabilityID"] == "play_media")- #expect(result.intent?.metadata["mediaSelection.selectedTitle"] == "Baby")#expect(result.trace.status == .completed)}- @Test- func taskIntentDecoderDoesNotHardCodePlayMediaSelectionSemantics() async throws {- let appFinderCatalog = StaticLocalAppAvailabilityProvider(- installedBundleIdentifiers: ["com.apple.Music"]- ).appFinderCatalogEntries()- let adapter = ProcessBackedLocalLLMTaskIntentAdapter(- router: AIModelRouter(registry: .defaultHybridPlanner),- sidecarRunner: FakeSidecarRunner(- result: LocalJSONSidecarResult(- status: .completed,- outputData: try localLLMSidecarOutputData(- outputText: """- {"taskType":"local_app_interaction","targetAppName":"Music","entities":{"appName":"Music","goal":"play media","query":"Coldplay"},"normalizedEntities":{"appName":"Music","goal":"play media","query":"Coldplay"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{"appFinder.selectedAppID":"com.apple.Music","appFinder.selectedCapabilityID":"play_media","appFinder.controlProfile":"search_then_enter"}}- """,- metadata: ["local.provider": "donkey-local-llm-sidecar"]- ),- latencyMS: 14,- metadata: ["sidecar.role": "taskIntent"]- )- )- )-- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: "play some coldplay",- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- appFinderCatalog: appFinderCatalog,- sourceTraceID: "trace-play-media-no-hardcoded-selection"- )- )-- #expect(result.intent?.taskType == "local_app_interaction")- #expect(result.intent?.targetApp.appName == "Music")- #expect(result.intent?.normalizedEntities["query"] == "Coldplay")- #expect(result.intent?.metadata["appFinder.validated"] == "true")- #expect(result.trace.status == .completed)- #expect(result.trace.validationStatus == "schemaDecoded")- }-@Testfunc taskIntentDecoderRejectsGenericInteractionOutsideAppFinderCatalog() async throws {let appFinderCatalog = StaticLocalAppAvailabilityProvider(@@ -740,7 +626,7 @@ struct AIHarnessAdapterTests {status: .completed,outputData: try localLLMSidecarOutputData(outputText: """- {"taskType":"local_app_interaction","targetAppName":"GarageBand","entities":{"appName":"GarageBand","goal":"play media","query":"justin bieber"},"normalizedEntities":{"appName":"GarageBand","goal":"play media","query":"Justin Bieber"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{"appFinder.selectedAppID":"com.apple.garageband10","appFinder.selectedCapabilityID":"play_media","appFinder.controlProfile":"search_then_enter"}}+ {"taskType":"local_app_interaction","targetAppName":"GarageBand","entities":{"appName":"GarageBand","goal":"play media","query":"Sample Track"},"normalizedEntities":{"appName":"GarageBand","goal":"play media","query":"Sample Track"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{"appFinder.selectedAppID":"com.apple.garageband10","appFinder.selectedCapabilityID":"play_media","appFinder.controlProfile":"search_then_enter"}}""",metadata: ["local.provider": "donkey-local-llm-sidecar"]),@@ -752,7 +638,7 @@ struct AIHarnessAdapterTests {let result = await adapter.parseTaskIntent(TaskIntentAdapterRequest(- command: "play some justin bieber",+ command: "play sample track",taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,appFinderCatalog: appFinderCatalog,sourceTraceID: "trace-app-finder-reject-outside-catalog"@@ -818,7 +704,7 @@ struct AIHarnessAdapterTests {let result = await adapter.parseTaskIntent(TaskIntentAdapterRequest(- command: "play some justin bieber",+ command: "play sample track",taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,sourceTraceID: "trace-local-llm-error")@@ -843,18 +729,18 @@ struct AIHarnessAdapterTests {)_ = await resolver.resolve(- command: "play some justin bieber",+ command: "play sample track",contextSnippets: [- "Existing task title: play some justin bieber",+ "Existing task title: play sample track","Recent thread: assistant could not find a supported action"],sourceTraceID: "trace-context-snippets")let request = await recorder.lastRequest()- #expect(request?.command == "play some justin bieber")+ #expect(request?.command == "play sample track")#expect(request?.contextSnippets == [- "Existing task title: play some justin bieber",+ "Existing task title: play sample track","Recent thread: assistant could not find a supported action"])#expect(request?.appFinderCatalog.first?.appID == "com.apple.Music")@@ -891,7 +777,7 @@ struct AIHarnessAdapterTests {outputText: """<think>I should choose the generic app interaction.</think>```json- {"taskType":"local_app_interaction","targetAppName":"Music","entities":{"appName":"Music","goal":"play media","query":"justin bieber"},"normalizedEntities":{"appName":"Music","goal":"play media","query":"Justin Bieber"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{}}+ {"taskType":"local_app_interaction","targetAppName":"Music","entities":{"appName":"Music","goal":"play media","query":"sample track"},"normalizedEntities":{"appName":"Music","goal":"play media","query":"Sample Track"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{}}```""",metadata: ["local.provider": "donkey-local-llm-sidecar"]@@ -904,7 +790,7 @@ struct AIHarnessAdapterTests {let result = await adapter.parseTaskIntent(TaskIntentAdapterRequest(- command: "play some justin bieber",+ command: "play sample track",taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,contextSnippets: ["Music application com.apple.Music"],sourceTraceID: "trace-wrapped-local-app-plan"@@ -913,7 +799,7 @@ struct AIHarnessAdapterTests {#expect(result.intent?.taskType == "local_app_interaction")#expect(result.intent?.targetApp.appName == "Music")- #expect(result.intent?.normalizedEntities["query"] == "Justin Bieber")+ #expect(result.intent?.normalizedEntities["query"] == "Sample Track")#expect(result.trace.status == .completed)}@@ -939,7 +825,7 @@ struct AIHarnessAdapterTests {let result = await adapter.parseTaskIntent(TaskIntentAdapterRequest(- command: "play some justin bieber",+ command: "play sample track",taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,sourceTraceID: "trace-empty-sidecar")@@ -962,7 +848,7 @@ struct AIHarnessAdapterTests {status: .completed,outputData: try localLLMSidecarOutputData(outputText: """- {"taskType":"local_app_interaction","targetAppName":"com.apple.Music","entities":{"appName":"Music","goal":"play some justin bieber"},"normalizedEntities":{"query":"Justin Bieber"},"confidence":1.0,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","ui.focusSearch"],"inputEntity":"query","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{}}+ {"taskType":"local_app_interaction","targetAppName":"com.apple.Music","entities":{"appName":"Music","goal":"play sample track"},"normalizedEntities":{"query":"Sample Track"},"confidence":1.0,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","ui.focusSearch"],"inputEntity":"query","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{}}""",metadata: ["local.provider": "donkey-local-llm-sidecar"@@ -976,7 +862,7 @@ struct AIHarnessAdapterTests {let result = await adapter.parseTaskIntent(TaskIntentAdapterRequest(- command: "play some justin bieber",+ command: "play sample track",taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,contextSnippets: ["Music application com.apple.Music"],sourceTraceID: "trace-preserved-local-app-plan"@@ -985,7 +871,7 @@ struct AIHarnessAdapterTests {#expect(result.intent?.taskType == "local_app_interaction")#expect(result.intent?.normalizedEntities["appName"] == "Music")- #expect(result.intent?.normalizedEntities["query"] == "Justin Bieber")+ #expect(result.intent?.normalizedEntities["query"] == "Sample Track")#expect(result.intent?.metadata["modelPlan.repaired"] == nil)#expect(result.intent?.actionPlan?.tools == [.openOrFocusApp, .focusSearch])#expect(result.intent?.actionPlan?.controlID == "")@@ -1070,7 +956,7 @@ struct AIHarnessAdapterTests {func localModelTaskIntentResolverValidatesAgainstCatalogAvailability() async {let resolver = LocalModelTaskIntentResolver(catalog: LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])),adapter: FixedTaskIntentAdapter(@@ -1105,7 +991,7 @@ struct AIHarnessAdapterTests {func localModelTaskIntentResolverResolvesDynamicLocalItemLookup() async {let resolver = LocalModelTaskIntentResolver(catalog: LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.figma.Desktop"],installedApplicationNames: ["Figma": "com.figma.Desktop"]@@ -1140,7 +1026,7 @@ struct AIHarnessAdapterTests {func localModelTaskIntentResolverDoesNotParseCommandTextWhenRuntimeUnavailable() async {let resolver = LocalModelTaskIntentResolver(catalog: LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])),adapter: UnavailableTaskIntentAdapter()@@ -1170,7 +1056,7 @@ struct AIHarnessAdapterTests {)let result = await resolver.resolve(- command: "play some justin bieber",+ command: "play sample track",sourceTraceID: "trace-resolve-no-command-text-fallback")@@ -1184,7 +1070,7 @@ struct AIHarnessAdapterTests {func localModelTaskIntentResolverAsksForDetailsInsteadOfUnsupportedWhenRuntimeUnavailable() async {let resolver = LocalModelTaskIntentResolver(catalog: LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])),adapter: UnavailableTaskIntentAdapter()@@ -1262,7 +1148,7 @@ struct AIHarnessAdapterTests {)let resolver = LocalModelTaskIntentResolver(catalog: LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: [])),adapter: adapter@@ -1285,7 +1171,7 @@ struct AIHarnessAdapterTests {func localModelTaskIntentResolverAcceptsClosestLowConfidenceClassification() async {let resolver = LocalModelTaskIntentResolver(catalog: LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])),adapter: FixedTaskIntentAdapter(@@ -1856,7 +1742,7 @@ struct AIHarnessAdapterTests {func semanticMemoryRetrievalUsesBudgetsAndTargetScope() async {let records = [memoryRecord(id: "weather", value: "Weather app search field accepts city names.", targetID: "weather-app"),- memoryRecord(id: "music", value: "Music app can play Coldplay from the search field.", targetID: "music-app")+ memoryRecord(id: "music", value: "Music app can play Sample Result from the search field.", targetID: "music-app")]let retriever = SemanticRunMemoryRetriever()diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AgentMemoryStoreTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AgentMemoryStoreTests.swiftindex 31610542..4346c4f2 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AgentMemoryStoreTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AgentMemoryStoreTests.swift@@ -110,7 +110,7 @@ struct AgentMemoryStoreTests {defer { try? FileManager.default.removeItem(at: root) }let store = try SQLiteAgentMemoryStore(baseDirectory: root, cleanupLegacyStores: false)- store.prewarmTaskDefinitions(BuiltInLocalAppTaskDefinitions.benchmarkFixtures)+ store.prewarmTaskDefinitions(BuiltInLocalAppTaskDefinitions.testFixtures)let result = try #require(try store.search(query: AgentMemoryQuery(text: "local app interaction",diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swiftindex 1f567e8f..93c1e828 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift@@ -231,7 +231,7 @@ struct AppHarnessTurnRouterTests {) -> AppHarnessTurnRouter {AppHarnessTurnRouter(catalog: LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather",diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swiftindex 5b11583f..1f5a6039 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift@@ -23,7 +23,7 @@ struct LocalAppTaskTests {@Testfunc catalogResolvesGenericAppOpenIntentFromModelSelectedLocalItem() throws {let catalog = LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.figma.Desktop"],installedApplicationNames: ["Figma": "com.figma.Desktop"],@@ -68,7 +68,7 @@ struct LocalAppTaskTests {@Testfunc lowConfidenceModelIntentAsksForConfirmationBeforeLookupExecution() {let catalog = LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.figma.Desktop"],installedApplicationNames: ["Figma": "com.figma.Desktop"]@@ -201,7 +201,7 @@ struct LocalAppTaskTests {@Testfunc appOpenAdapterVerifiesFocusedApp() throws {let catalog = LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Music"]))let resolution = catalog.resolve(intent: TaskIntent(@@ -241,7 +241,7 @@ struct LocalAppTaskTests {let resolution = catalog.resolve(intent: genericLocalAppInteractionIntent(appName: "Music",- query: "Justin Bieber",+ query: "Sample Track",planTools: [.openOrFocusApp,.observeApp,@@ -288,7 +288,7 @@ struct LocalAppTaskTests {for: intent,issuedAt: timestamp(100))- #expect(commands.map(\.key) == ["Command+F", "Justin Bieber", "Return", "Return"])+ #expect(commands.map(\.key) == ["Command+F", "Sample Track", "Return", "Return"])#expect(commands.first?.metadata["plan.tool"] == "ui.focusSearch")}@@ -302,7 +302,7 @@ struct LocalAppTaskTests {)let resolution = catalog.resolve(intent: genericLocalAppInteractionIntent(appName: "Music",- query: "Coldplay",+ query: "Sample Track",planTools: [.openOrFocusApp,.observeApp,@@ -330,58 +330,6 @@ struct LocalAppTaskTests {#expect(plan.steps.first(where: { $0.role == .focusControl })?.status == .verified)}- @Test- func catalogKeepsValidatedPlayMediaCapabilityOnGenericInteraction() throws {- let catalog = LocalAppTaskCatalog(- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- availabilityProvider: StaticLocalAppAvailabilityProvider(- installedBundleIdentifiers: ["com.apple.Music"]- )- )- var genericIntent = genericLocalAppInteractionIntent(- appName: "Music",- query: "Viva La Vida Coldplay",- planTools: [- .openOrFocusApp,- .observeApp,- .focusSearch,- .setText,- .pressReturn,- .verifyCommand- ]- )- genericIntent.metadata.merge([- "appFinder.selectedAppID": "com.apple.Music",- "appFinder.selectedCapabilityID": "play_media",- "appFinder.controlProfile": "search_then_enter",- "mediaSelection.kind": "representative_song",- "mediaSelection.seed": "Coldplay",- "mediaSelection.selectedTitle": "Viva La Vida"- ]) { _, new in new }-- let resolution = catalog.resolve(intent: genericIntent)- let intent = try #require(resolution.intent)- let definition = try #require(resolution.definition)- let automationCommands = catalog.adapter(for: definition).guardedAutomationCommandTemplates(- for: intent,- issuedAt: timestamp(100)- )- let keyboardCommands = catalog.adapter(for: definition).guardedKeyboardCommandTemplates(- for: intent,- issuedAt: timestamp(100)- )-- #expect(resolution.status == .resolved)- #expect(intent.taskType == "local_app_interaction")- #expect(intent.targetApp.appName == "Music")- #expect(intent.normalizedEntities["query"] == "Viva La Vida Coldplay")- #expect(intent.metadata["appFinder.selectedCapabilityID"] == "play_media")- #expect(definition.taskType == "local_app_interaction")- #expect(definition.metadata["automationBackend"] == nil)- #expect(automationCommands.isEmpty)- #expect(keyboardCommands.map(\.key) == ["Command+F", "Viva La Vida Coldplay", "Return"])- }-@Testfunc staticProviderBuildsAppFinderCatalogWithSupportAndDenyMetadata() throws {let provider = StaticLocalAppAvailabilityProvider(@@ -486,7 +434,7 @@ struct LocalAppTaskTests {let resolution = catalog.resolve(intent: genericLocalAppInteractionIntent(appName: "Music",- query: "Justin Bieber",+ query: "Sample Track",planTools: nil))@@ -497,7 +445,7 @@ struct LocalAppTaskTests {@Testfunc catalogResolvesStructuredIntentAgainstAvailableInstalledAppDefinition() throws {let catalog = LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather","com.apple.Music",@@ -526,7 +474,7 @@ struct LocalAppTaskTests {@Testfunc catalogSeparatesUnsupportedMissingEntityAndUnavailableApp() {let availableCatalog = LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"]))let unavailableAppResolution = availableCatalog.resolve(intent: TaskIntent(@@ -543,7 +491,7 @@ struct LocalAppTaskTests {#expect(availableCatalog.resolve(intent: weatherIntent(rawCity: "", city: "", needsConfirmation: true)).status == .needsConfirmation)let unavailableCatalog = LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: []))#expect(unavailableCatalog.resolve(intent: weatherIntent(rawCity: "SF", city: "San Francisco")).status == .appUnavailable)@@ -918,365 +866,6 @@ struct LocalAppTaskTests {#expect(command.targetBounds?.space == .screen)}- @Test @MainActor- func liveRunnerReturnsReviewPlanForDocumentFormFillWithoutExecutingInput() async throws {- let catalog = LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Preview"])- )- let context = LocalAppTaskContext(- focusedAppName: "Preview",- focusedBundleIdentifier: "com.apple.Preview",- focusedWindowTitle: "Application.pdf",- structuredData: ["Name": "Grace Hopper"],- observedFormFields: [- LocalDocumentFormField(id: "name", label: "Name", isRequired: true)- ]- )- let runner = LocalAppTaskLiveRunner(- catalog: catalog,- contextProvider: StaticLocalAppTaskContextProvider(context: context)- )- let intent = documentFormFillIntent()-- let result = await runner.run(- command: "fill out this PDF using this data",- traceID: "trace-document-fill",- resolution: catalog.resolve(intent: intent),- metadata: ["intentParser": "test-model"]- )-- #expect(result.status == .needsUserReview)- #expect(result.actionTraces.isEmpty)- #expect(result.documentFormFillPlan?.status == .readyForReview)- #expect(result.documentFormFillPlan?.proposals.first?.proposedValue == "Grace Hopper")- #expect(result.metadata["reason"] == "reviewOnlyTask")- #expect(result.workflowProgress.state(for: .approval)?.status == .waiting)- #expect(result.workflowProgress.state(for: .execute)?.status == .skipped)- }-- @Test @MainActor- func liveRunnerLaunchesFocusesExecutesGuardedCommandsAndVerifies() async throws {- let backend = RecordingLocalAppTaskInputBackend()- let controller = FakeLocalAppTaskAppController(- launchObservation: LocalAppTaskObservation(- appIsRunning: true,- appIsFocused: true,- availableControls: ["search": true],- confidence: 0.5,- metadata: groundedControlMetadata()- ),- finalObservation: LocalAppTaskObservation(- appIsRunning: true,- appIsFocused: true,- availableControls: ["search": true],- visibleText: ["city": "San Francisco, CA"],- confidence: 0.92,- metadata: groundedControlMetadata()- )- )- let catalog = LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])- )- let runner = LocalAppTaskLiveRunner(- catalog: catalog,- appController: controller,- actionEngineFactory: { _ in- ActionEngineGuardrail(- configuration: ActionEngineConfiguration(liveInputEnabled: true),- inputBackend: backend- )- },- permissionPolicy: ToolCallPolicy(deniedCapabilities: [])- )- let intent = weatherIntent(rawCity: "SF", city: "San Francisco")-- let result = await runner.run(- command: "show me the weather for SF",- traceID: "trace-live-task",- resolution: catalog.resolve(intent: intent),- metadata: ["intentParser": "test-model"]- )-- #expect(result.status == .completed)- #expect(result.finalActionPlan?.terminalState == .completed)- #expect(result.actionTraces.count == 4)- #expect(result.actionTraces.allSatisfy { $0.executed })- #expect(await backend.executedKeys() == ["Command+F", "San Francisco", "Return", "Return"])- #expect(controller.launchCount == 1)- #expect(controller.observeCount == 1)- #expect(result.workflowProgress.state(for: .parseIntent)?.status == .completed)- #expect(result.workflowProgress.state(for: .resolveApp)?.status == .completed)- #expect(result.workflowProgress.state(for: .evidencePlan)?.status == .completed)- #expect(result.workflowProgress.state(for: .approval)?.status == .skipped)- #expect(result.workflowProgress.state(for: .execute)?.status == .completed)- #expect(result.workflowProgress.state(for: .verify)?.status == .completed)- #expect(result.metadata["workflow.verify.status"] == "completed")- }-- @Test @MainActor- func liveRunnerExecutesOnlyModelPlannedGenericPlayMediaSteps() async throws {- let backend = RecordingLocalAppTaskInputBackend()- let controller = FakeLocalAppTaskAppController(- launchObservation: LocalAppTaskObservation(- appIsRunning: true,- appIsFocused: true,- availableControls: [:],- confidence: 0.7- ),- finalObservation: LocalAppTaskObservation(- appIsRunning: true,- appIsFocused: true,- availableControls: [:],- confidence: 0.74- )- )- let catalog = LocalAppTaskCatalog(- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Music"])- )- let runner = LocalAppTaskLiveRunner(- catalog: catalog,- appController: controller,- actionEngineFactory: { _ in- ActionEngineGuardrail(- configuration: ActionEngineConfiguration(liveInputEnabled: true),- inputBackend: backend- )- },- permissionPolicy: ToolCallPolicy(deniedCapabilities: [])- )- var intent = genericLocalAppInteractionIntent(- appName: "Music",- query: "Viva La Vida Coldplay",- planTools: [- .openOrFocusApp,- .observeApp,- .focusSearch,- .setText,- .pressReturn,- .verifyCommand- ]- )- intent.metadata.merge([- "appFinder.selectedAppID": "com.apple.Music",- "appFinder.selectedCapabilityID": "play_media",- "appFinder.controlProfile": "search_then_enter",- "mediaSelection.kind": "representative_song",- "mediaSelection.seed": "Coldplay",- "mediaSelection.selectedTitle": "Viva La Vida"- ]) { _, new in new }-- let result = await runner.run(- command: "play some cold play",- traceID: "trace-generic-play-media-automation",- resolution: catalog.resolve(intent: intent),- metadata: ["intentParser": "test-model"]- )-- #expect(result.status == .completed)- #expect(result.resolution.definition?.taskType == "local_app_interaction")- #expect(result.metadata["reason"] != "evidencePlanBlocked")- #expect(result.metadata["automation.backend"] == nil)- #expect(result.metadata["automation.action"] == nil)- #expect(result.workflowProgress.state(for: .evidencePlan)?.status == .completed)- #expect(result.workflowProgress.state(for: .execute)?.status == .completed)- #expect(result.metadata["verification.executedCommandCount"] == "3")- #expect(await backend.executedKeys() == ["Command+F", "Viva La Vida Coldplay", "Return"])- }-- @Test @MainActor- func liveRunnerExecutesGenericShortcutFocusPlanWithoutControlBounds() async throws {- let backend = RecordingLocalAppTaskInputBackend()- let controller = FakeLocalAppTaskAppController(- launchObservation: LocalAppTaskObservation(- appIsRunning: true,- appIsFocused: true,- availableControls: [:],- confidence: 0.7- ),- finalObservation: LocalAppTaskObservation(- appIsRunning: true,- appIsFocused: true,- availableControls: [:],- confidence: 0.74- )- )- let catalog = LocalAppTaskCatalog(- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Music"])- )- let runner = LocalAppTaskLiveRunner(- catalog: catalog,- appController: controller,- actionEngineFactory: { _ in- ActionEngineGuardrail(- configuration: ActionEngineConfiguration(liveInputEnabled: true),- inputBackend: backend- )- },- permissionPolicy: ToolCallPolicy(deniedCapabilities: [])- )- let intent = genericLocalAppInteractionIntent(- appName: "Music",- query: "Coldplay",- planTools: [- .openOrFocusApp,- .observeApp,- .focusSearch,- .setText,- .pressReturn,- .verifyCommand- ]- )-- let result = await runner.run(- command: "play some cold play",- traceID: "trace-generic-shortcut-focus",- resolution: catalog.resolve(intent: intent),- metadata: ["intentParser": "test-model"]- )-- #expect(result.status == .completed)- #expect(result.metadata["reason"] != "evidencePlanBlocked")- #expect(result.workflowProgress.state(for: .evidencePlan)?.status == .completed)- #expect(result.workflowProgress.state(for: .execute)?.status == .completed)- #expect(await backend.executedKeys() == ["Command+F", "Coldplay", "Return"])- }-- @Test @MainActor- func liveRunnerDoesNotReportCompletedWhenEvidencePlanBlocks() async throws {- let backend = RecordingLocalAppTaskInputBackend()- let controller = FakeLocalAppTaskAppController(- launchObservation: LocalAppTaskObservation(- appIsRunning: true,- appIsFocused: true,- availableControls: [:],- confidence: 0.7- ),- finalObservation: LocalAppTaskObservation(- appIsRunning: true,- appIsFocused: true,- availableControls: [:],- confidence: 0.74- )- )- let catalog = LocalAppTaskCatalog(- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Music"])- )- let runner = LocalAppTaskLiveRunner(- catalog: catalog,- appController: controller,- actionEngineFactory: { _ in- ActionEngineGuardrail(- configuration: ActionEngineConfiguration(liveInputEnabled: true),- inputBackend: backend- )- },- permissionPolicy: ToolCallPolicy(deniedCapabilities: [])- )- let intent = TaskIntent(- intentID: "local_app_interaction-no-focus-evidence",- taskType: "local_app_interaction",- targetApp: LocalAppTarget(appName: "Music", titleContains: "Music"),- entities: [- "appName": "Music",- "goal": "play media",- "query": "Coldplay"- ],- normalizedEntities: [- "appName": "Music",- "goal": "play media",- "query": "Coldplay"- ],- confidence: 0.93,- parserSource: .localModel,- actionPlan: LocalAppActionPlan(- tools: [- .openOrFocusApp,- .observeApp,- .focusSearch,- .setText,- .pressReturn,- .verifyCommand- ],- inputEntity: "query",- controlID: "search",- focusKey: "",- verification: .commandAttempted- ),- metadata: ["requestedItemName": "Music"]- )-- let result = await runner.run(- command: "play some cold play",- traceID: "trace-blocked-evidence-plan",- resolution: catalog.resolve(intent: intent),- metadata: ["intentParser": "test-model"]- )-- #expect(result.status == .needsUserReview)- #expect(result.metadata["reason"] == "evidencePlanBlocked")- #expect(result.workflowProgress.state(for: .evidencePlan)?.status == .blocked)- #expect(await backend.executedKeys() == [])- }-- @Test @MainActor- func liveRunnerPublishesCoordinatorEventsForGuardedRun() async throws {- let backend = RecordingLocalAppTaskInputBackend()- let controller = FakeLocalAppTaskAppController(- launchObservation: LocalAppTaskObservation(- appIsRunning: true,- appIsFocused: true,- availableControls: ["search": true],- confidence: 0.5,- metadata: groundedControlMetadata()- ),- finalObservation: LocalAppTaskObservation(- appIsRunning: true,- appIsFocused: true,- availableControls: ["search": true],- visibleText: ["city": "San Francisco, CA"],- confidence: 0.92,- metadata: groundedControlMetadata()- )- )- let coordinator = RunCoordinator()- let catalog = LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])- )- let runner = LocalAppTaskLiveRunner(- catalog: catalog,- appController: controller,- actionEngineFactory: { _ in- ActionEngineGuardrail(- configuration: ActionEngineConfiguration(liveInputEnabled: true),- inputBackend: backend- )- },- permissionPolicy: ToolCallPolicy(deniedCapabilities: []),- coordinator: coordinator- )- let intent = weatherIntent(rawCity: "SF", city: "San Francisco")-- let result = await runner.run(- command: "show me the weather for SF",- traceID: "trace-live-task-events",- resolution: catalog.resolve(intent: intent),- metadata: ["intentParser": "test-model"]- )- let events = await coordinator.events()-- #expect(result.status == .completed)- #expect(events.contains { $0.stream == .lifecycle })- #expect(events.contains { $0.stream == .tool && $0.summary == "Launching or focusing local app" })- #expect(events.contains { $0.stream == .tool && $0.summary == "Executing guarded keyboard command" })- #expect(events.last?.summary == "Run completed")- }-@Testfunc screenshotUnderstandingIsOnlyUsedWhenAccessibilityIsInsufficient() {let definition = BuiltInLocalAppTaskDefinitions.weatherLookup@@ -1458,7 +1047,7 @@ struct LocalAppTaskTests {private func catalog() -> LocalAppTaskCatalog {LocalAppTaskCatalog(- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,+ taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: []))}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MacKeyboardActionEngineInputBackendTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MacKeyboardActionEngineInputBackendTests.swiftindex 54b4d177..59b5ae1d 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/MacKeyboardActionEngineInputBackendTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MacKeyboardActionEngineInputBackendTests.swift@@ -28,7 +28,7 @@ struct MacKeyboardActionEngineInputBackendTests {)let result = await backend.execute(command(- key: "Coldplay",+ key: "Sample Result",metadata: ["inputRole": "textEntry"]))@@ -36,7 +36,7 @@ struct MacKeyboardActionEngineInputBackendTests {#expect(result.metadata["inputMode"] == "pasteboardText")#expect(result.metadata["textEntry.method"] == "pasteboard")#expect(result.metadata["textEntry.shortcut"] == "Command+V")- #expect(result.metadata["textEntry.characterCount"] == "8")+ #expect(result.metadata["textEntry.characterCount"] == "13")#expect(recorder.commands() == ["Command+V"])}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swiftindex a8faf967..8346333f 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift@@ -145,7 +145,7 @@ struct OffTheShelfVisionPerceptionTests {result: LocalJSONSidecarResult(status: .completed,outputData: Data("""- {"visibleText":{"title":"Music","result":"Coldplay"},"controls":[{"id":"search","label":"Search","kind":"searchField","frame":{"x":0.1,"y":0.1,"width":0.8,"height":0.08,"space":"normalizedTarget"},"confidence":0.86,"metadata":{"controlID":"search"}}],"formFields":[],"confidence":0.84,"metadata":{"understander":"fake-local-llm"}}+ {"visibleText":{"title":"Music","result":"Sample Result"},"controls":[{"id":"search","label":"Search","kind":"searchField","frame":{"x":0.1,"y":0.1,"width":0.8,"height":0.08,"space":"normalizedTarget"},"confidence":0.86,"metadata":{"controlID":"search"}}],"formFields":[],"confidence":0.84,"metadata":{"understander":"fake-local-llm"}}""".utf8),metadata: ["sidecar.reason": "completed"])@@ -161,7 +161,7 @@ struct OffTheShelfVisionPerceptionTests {let observation = result.observation(for: request)#expect(observation.availableControls["search"] == true)- #expect(observation.visibleText["result"] == "Coldplay")+ #expect(observation.visibleText["result"] == "Sample Result")#expect(observation.metadata["directInputActionsAllowed"] == "false")#expect(observation.metadata["understander"] == "fake-local-llm")}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/PointerPromptCopyTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/PointerPromptCopyTests.swiftindex c1c290b2..d285a87f 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/PointerPromptCopyTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/PointerPromptCopyTests.swift@@ -24,7 +24,7 @@ struct PointerPromptCopyTests {PointerPromptCopy.defaultPromptPlaceholder)#expect(- PointerPromptCopy.composerPlaceholder(for: "play some justin bieber") ==+ PointerPromptCopy.composerPlaceholder(for: "play sample track") ==PointerPromptCopy.defaultPromptPlaceholder)#expect(PointerPromptCopy.composerPlaceholder(for: "Listening...") == "Listening...")diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LegacyLocalAppTaskFixtures.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/TestLocalAppTaskDefinitions.swiftsimilarity index 97%rename from apps/Donkey/Tests/DonkeyRuntimeTests/LegacyLocalAppTaskFixtures.swiftrename to apps/Donkey/Tests/DonkeyRuntimeTests/TestLocalAppTaskDefinitions.swiftindex b39a1baf..cdc90209 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LegacyLocalAppTaskFixtures.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/TestLocalAppTaskDefinitions.swift@@ -62,7 +62,7 @@ extension BuiltInLocalAppTaskDefinitions {)}- static var benchmarkFixtures: [LocalAppTaskDefinition] {+ static var testFixtures: [LocalAppTaskDefinition] {[LocalAppTaskCatalog.genericLocalItemOpenDefinition,LocalAppTaskCatalog.genericLocalAppInteractionDefinition,diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 997ca87f..11a88b0d 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -64,6 +64,12 @@ the generic task definitions, generated or user-reviewed app catalog data, andmemory. The core runtime does not ship app-specific Weather, Music, Notes, orNumbers task branches.+The app catalog is part of the model boundary, not a hidden executor shortcut.+Pointer-prompt turns send the current supported app catalog to planning. If the+catalog is still refreshing or does not contain a supported entry, the harness+must surface conversation, clarification, waiting, or failed-safe state instead+of silently dropping the request or executing an unsupported candidate.+Pointer prompt uses the generic harness as the entrypoint for conversation,clarification, planning, and tool selection. Local desktop actions areregistered harness tools rather than a separate default path.@@ -173,13 +179,14 @@ observes, acts, verifies, and replans. The planner may propose the next toolstep, but deterministic Swift owns task state, tool validation, permissions,focus checks, execution, and result recording.-Pointer-prompt local-app work is executed through the same tool loop. Hosted-planning emits local-app tool calls such as `app.openOrFocus`, `app.observe`,-`ui.setText`, and `app.verifyCommand`; the runtime executes one guarded step,-records the resulting Accessibility or screenshot-backed observation, and then-continues only while the next planned tool remains valid. It stops on-verification failure, missing evidence, permission gates, clarification gates,-or exhausted plan steps.+Pointer-prompt local-app work is executed through the same tool loop. Planning+receives compacted context, tool descriptors, relevant skills, and the current+supported app catalog, then returns a structured route and plan. A local-app+route must validate against the catalog before it becomes executable tool+state. The runtime executes one guarded step, records the resulting+Accessibility or screenshot-backed observation, and continues only while the+next planned step remains valid. It stops on verification failure, missing+evidence, permission gates, clarification gates, or exhausted plan steps.If the user interrupts a task, the harness classifies whether the turn starts anew task, modifies the current task, cancels, pauses, resumes, answers a@@ -258,9 +265,9 @@ execution checks as other input.Verification must be backed by task evidence. A local-app command attempt is notverified merely because the target app is focused or running after execution;-post-action verification records guarded command evidence and should use-available observation evidence, including screenshots when needed, before the-task can complete or choose a recovery path.+the harness needs post-action evidence, such as guarded command traces, visible+text, selected element state, app-reported results, or screenshot-backed+observations, before the task can complete or choose a recovery path.## AppleScript And Scriptsdiff --git a/plans/00-overview.md b/plans/00-overview.mddeleted file mode 100644index d6f50d7e..00000000--- a/plans/00-overview.md+++ /dev/null@@ -1,122 +0,0 @@-# Super Low-Latency Agent Plan--> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.--## Objective--Build a desktop AI agent that can play iPhone games through Apple's iPhone Mirroring app with low latency, while keeping the architecture general enough to later control normal desktop software.--iPhone games are the first product focus. Gaming is the latency proof. The larger platform is real-time desktop and mobile-app control from the Mac.--## Archived Plan Status--The active master plan is currently `plans/master-plan.md`. Start with `docs/README.md`, the supported behavior guides, and the active master plan before changing code.--This overview remains archived background. It mixes completed boundaries with broader roadmap ideas, so it should not override the active master plan.--## Near-Term Focus--Become genuinely good at playing iPhone games through iPhone Mirroring.--That means:--- capture the iPhone Mirroring window reliably-- map the mirrored iPhone content rectangle-- perform calibrated taps, swipes, and controller-style actions-- parse game state from screenshots with low latency-- survive real game loops, not just click menus-- measure Mac-side latency separately from mirroring/game response latency-- avoid purchases, ads, account flows, and system dialogs--## Core Architecture--```text-Screen Capture- -> Off-The-Shelf Vision- -> Game State Tensor / World State- -> Fast Controller- -> Action Engine- -> Keyboard / Mouse / Controller-```--The slow planner runs beside this loop, not inside it:--```text-World State Snapshots- -> Slow Planner- -> Goals / Policies / Recovery Hints- -> Fast Controller-```--## Latency Rule--The real-time path must never depend on a large LLM or remote VLM call.--Every frame should use local, bounded-cost logic:--- capture only the pixels needed-- run small perception models or classical CV-- keep a compact world state-- choose from cheap action policies-- execute input immediately--## Plan Breakdown--- [manual-target-context-capture-master-plan.md](manual-target-context-capture-master-plan.md): completed manual screenshot, Accessibility tree, and trace artifact capture milestone-- [../master-plan.md](../master-plan.md): current master plan for closing out the off-the-shelf run loop and AI harness milestones-- [../02-capture-and-perception.md](../02-capture-and-perception.md): screen capture, visual parsing, and world-state updates-- [../03-fast-controller.md](../03-fast-controller.md): real-time controller design-- [04-slow-planner.md](04-slow-planner.md): completed slow strategy, recovery, and goal-setting layer-- [../05-action-engine.md](../05-action-engine.md): low-latency keyboard, mouse, and controller output-- [../06-benchmarking.md](../06-benchmarking.md): hard latency budgets, measurement, monitoring, traces, and regression gates-- [07-rollout.md](07-rollout.md): phased delivery path from first supported target to production readiness-- [08-dom-parsing.md](08-dom-parsing.md): DOM-driven perception for browser games and web apps-- [09-screenshot-model-inference.md](09-screenshot-model-inference.md): screenshot capture into low-latency vision models-- [10-gaps-to-expand.md](10-gaps-to-expand.md): remaining gaps needed to make the system real-- [11-game-targets.md](11-game-targets.md): recommended games and target sequence-- [12-iphone-mirroring.md](12-iphone-mirroring.md): iPhone Mirroring as a mobile-game target-- [13-subway-surfers-target.md](13-subway-surfers-target.md): concrete Subway Surfers target profile-- [14-synthetic-controller.md](14-synthetic-controller.md): generic synthetic input adapter, including gamepad/controller backends-- [16-iphone-gameplay-roadmap.md](16-iphone-gameplay-roadmap.md): iPhone Mirroring gameplay roadmap-- [17-ios-control-prompt.md](17-ios-control-prompt.md): iOS control prompt and PhoneAgent reference-- [18-macos-accessibility.md](18-macos-accessibility.md): macOS Accessibility tree/action backend-- [done/19-ai-harness.md](done/19-ai-harness.md): completed AI harness memory, proposal, and voice-hardening slice-- [../20-off-the-shelf-run-loop.md](../20-off-the-shelf-run-loop.md): off-the-shelf perception, deterministic control, and low-latency runtime stack--## System Priorities--1. Latency over generality.-2. iPhone Mirroring competence before broad desktop automation.-3. Local execution over remote calls in the reflex loop.-4. State updates over full-screen re-interpretation.-5. Specialized controllers over universal reasoning.-6. Measurement before optimization claims.-7. Small vision models over large VLMs inside the reflex loop.-8. DOM signals over vision when the target is web-based and the DOM is available.-9. Off-the-shelf components before custom model work.--## First Supported Target--Start with iPhone Mirroring targets that have:--- fast visual feedback-- simple action space-- deterministic or repeatable scenarios-- stable iPhone Mirroring window capture-- no multiplayer anti-cheat risk--Good first candidates:--- tap-only iPhone games-- iPhone puzzle/card games-- simple iPhone endless runners-- Subway Surfers after swipe calibration works-- local iPhone Safari test pages as measurement harnesses--Avoid for the first supported target:--- competitive multiplayer games-- games with anti-cheat-- visually noisy 3D iPhone games-- games requiring multi-touch, gyro, camera, or microphone-- games requiring long strategic memory before basic control worksdiff --git a/plans/05-action-engine.md b/plans/05-action-engine.mddeleted file mode 100644index f190d137..00000000--- a/plans/05-action-engine.md+++ /dev/null@@ -1,126 +0,0 @@-# Action Engine--> Active status: not complete. Current action-engine support provides guardrails, traces, and injected-backend smoke execution, but not the narrow default macOS app-control backend needed for the first fast-navigation benchmark.--## Goal--Execute app activation, keyboard, mouse, Accessibility, and controller actions with low latency and predictable timing.--## Responsibilities--- app launch and activation-- keyboard press/release-- text entry-- mouse movement-- mouse click/drag-- Accessibility focus/action when trusted-- controller input, if needed-- action scheduling-- input cancellation-- focus checks--## Design--The controller emits action commands:--```text-press_key(W, duration=40ms)-type_text("San Francisco")-move_mouse(dx=10, dy=-4)-click(button=left)-tap(x, y)-swipe(start_x, start_y, end_x, end_y, duration=80ms)-press_button(A, duration=40ms)-set_axis(left_stick_x, 0.5)-release_all()-launch_app(bundle_id=com.apple.weather)-activate_app(bundle_id=com.apple.weather)-perform_accessibility_action(element_id=search-field, action=focus)-```--The action engine translates commands into OS input calls.--For local app tasks, prefer the safest high-level primitive that works:--1. Launch or activate the target app through the app-control backend.-2. Use Accessibility focus/actions when trusted and the target element is confidently identified.-3. Use guarded keyboard text entry for ordinary search text.-4. Use mouse clicks only when coordinates are derived from typed state and focus guard passes.--For touch-style targets such as iPhone Mirroring, the action engine should expose a synthetic controller adapter. It turns semantic commands like `swipe_left` or `tap_lane_center` into calibrated mouse/touch-like gestures. See [14-synthetic-controller.md](14-synthetic-controller.md).--For games that support controllers, the action engine should expose a generic gamepad backend with buttons, sticks, triggers, and directional pads through the synthetic controller abstraction. See [14-synthetic-controller.md](14-synthetic-controller.md).--## Rules--- Input execution should be fire-and-forget where safe.-- Long key holds must have explicit release times.-- The engine should release all inputs on shutdown or loss of focus.-- The controller should not call OS input APIs directly.-- Every command should be timestamped and traceable.-- App launch/focus commands must be traceable and covered by tool policy.-- Text entry must be scoped to the verified focused app/control.-- Accessibility actions must not run on sensitive or review-required surfaces.--## Mouse Strategy--For games, mouse movement should support:--- relative movement-- absolute movement-- smooth movement over a short duration-- instant click after movement-- calibrated sensitivity per game--## Keyboard Strategy--Support:--- tap-- hold-- chord-- release-- type text-- rate limit--Movement keys should be represented as desired direction first, then converted to key states. This prevents conflicting commands like left and right being held accidentally.--For the Weather demo, text entry should be a first-class command so traces can show the normalized entity being typed without exposing unrelated keyboard events.--## App-Control Strategy--Support a narrow macOS backend for the first target:--- launch app by bundle identifier-- activate/focus app-- verify frontmost app before input-- focus a known Accessibility element when available-- fall back to keyboard shortcut/search only when focus is safe--This backend is intentionally narrower than a general desktop-control agent. Add capabilities only when a task adapter needs them and the guardrails can explain them.--## Latency Risks--- OS accessibility/input permission prompts.-- APIs that add smoothing or delay.-- Cross-process command queues.-- Too many tiny scheduled timers.-- Failure to release inputs after an exception.--## First Milestones--1. Add semantic app-control commands for launch, activate, type text, focus element, click/select, and verify.-2. Implement a narrow macOS backend for Weather behind existing guardrails.-3. Add input and app-control tracing.-4. Add focus guard for target app and target control.-5. Add emergency release.-6. Measure command-to-input latency for Weather lookup.-7. Calibrate mouse movement only if Accessibility/keyboard control is insufficient.--## Acceptance Criteria--- Input execution p95 is under 5ms after command creation.-- App launch/focus and text-entry latency are measured separately.-- All held inputs release on stop.-- Commands can be replayed from a trace.-- Weather lookup live input cannot run unless the Weather app/control is verified safe.diff --git a/plans/06-benchmarking.md b/plans/06-benchmarking.mddeleted file mode 100644index 1cc479d3..00000000--- a/plans/06-benchmarking.md+++ /dev/null@@ -1,460 +0,0 @@-# Latency Budget, Benchmarking, And Monitoring--> Active status: not complete. Current reports support synthetic and dry-run traces, but this plan is not complete until p50/p95/p99 budgets are measured for the first fast-navigation benchmark, compared with a same-machine manual baseline, and persisted across runs.--## Goal--Make latency visible, measurable, and hard to accidentally regress.--No latency claim counts unless it is measured with local traces.--The first benchmark target is the user-facing Weather navigation task:--```text-"show me the weather for SF"- -> Weather app visible with San Francisco verified-```--This must be compared against a manual baseline on the same machine so the product claim is honest: local navigation should be faster than doing the navigation by hand, or the report should show which stage prevents that.--The project needs two observability loops:--- local measurement while building and tuning the agent-- continuous monitoring so latency regressions show up over time--## Product Targets--For the first Weather demo:--- command-to-first-action p95 under 300ms after text submission-- local observation/controller/input step p95 under 100ms-- command-to-verified-result faster than a documented manual baseline on the same machine--For later game and visual targets:--- visual reflex p95 under 100ms end to end-- stretch target of 30-60ms for simple games--## Stage Budgets--### Weather Task Budget--| Stage | Baseline Target | Stretch Target |-| --- | ---: | ---: |-| Intent parse | 5-100ms | <20ms deterministic |-| App launch/focus | 100-800ms | 50-300ms when already warm |-| App observation | 5-50ms | 2-15ms |-| Controller decision | 1-20ms | <5ms |-| Input execution | 1-20ms | <5ms |-| Result verification | 10-100ms | 5-30ms |--### Visual Reflex Budget--| Stage | Baseline Target | Stretch Target |-| --- | ---: | ---: |-| Screen capture | 5-15ms | 2-8ms |-| Perception / model inference | 10-50ms | 5-20ms |-| World-state update | 1-5ms | <2ms |-| Action decision | 1-20ms | <5ms |-| Input execution | 1-5ms | <2ms |-| Total | <100ms | 30-60ms |--## Hard Rules--- No large LLM calls in the per-frame loop.-- No remote calls in the per-frame loop.-- No remote call is required for common Weather command parsing or execution.-- No full-screen expensive inference unless the target requires it.-- No full-resolution model input in the hot path unless measured under budget.-- No unbounded queues between capture, perception, and action.-- Drop stale frames instead of processing late frames.-- Do not wait for planner output before acting in the reflex loop.-- Do not type into an unverified focused control.--## Loop Shape--Use a latest-frame-wins design:--```text-Observation thread- -> overwrites latest app/window/task state--Perception thread- -> reads latest structured observation or latest frame fallback- -> emits latest world state--Controller thread- -> reads latest world state- -> emits immediate action-```--Do not preserve every frame if the system falls behind. A real-time agent should be current, not complete.--## Required Metrics--Per loop:--- intent parse start and end timestamps-- app launch/focus start and end timestamps-- app observation start and end timestamps-- capture start and end timestamps-- perception start and end timestamps-- model preprocess start and end timestamps-- model inference start and end timestamps-- world-state timestamp-- controller start and end timestamps-- input command and execution timestamps-- verification start and end timestamps-- command-to-result timestamp-- frame age when perception begins-- state age when controller begins-- action age when input executes--Aggregate:--- p50, p95, and p99 latency-- dropped frames and stale actions-- planner calls and planner latency-- app launch/focus latency-- app observation latency-- result verification latency-- command-to-result latency-- manual baseline latency-- controller fallback count-- capture FPS, perception FPS, and controller tick rate-- queue depth-- CPU usage-- GPU usage and GPU memory usage, if used-- memory usage-- thermal throttling indicator, when available--## Clock Rules--Use a monotonic high-resolution clock for all internal timing.--Do not use wall-clock time for latency deltas. Wall-clock time can jump due to NTP updates, sleep/wake, or user changes. It is useful for log labels, but not for measuring elapsed time.--Every trace event should include:--- monotonic timestamp for latency math-- wall-clock timestamp for humans-- process id-- thread or worker id-- build/version id-- machine profile--## Measurement Levels--### Command-To-Result Latency--This is the product-feel number for local app tasks.--```text-user command accepted -> intent parsed -> app focused -> input executed -> result verified-```--For Weather lookup, report both cold-start and warm-app numbers. Compare against a manual run where the operator opens Weather, searches for San Francisco, and confirms the result.--### Internal Software Latency--This is the time from captured frame to input command execution inside the agent.--```text-capture_end -> perception_end -> controller_end -> input_execute-```--This is the easiest latency to measure and should be present from the first supported build.--### Reflex Latency--This is the time from a visual change becoming available to the agent taking an action.--```text-visual_change_on_screen -> captured_frame -> world_state -> action-```--For controlled tests, create a synthetic target that changes color or position on screen, then measure how long the agent takes to respond.--### Physical Loop Latency--This is the true player-feel number:--```text-screen changes -> agent sees it -> input fires -> game responds on screen-```--This may require external measurement, such as a high-FPS camera, OS-level input event tracing, or a game/test app that logs both rendered frame ids and received input events.--## Instrumentation Plan--Add tiny timestamp spans around every hot-path boundary:--```text-command.accepted-intent_parse.start-intent_parse.end-app_focus.start-app_focus.end-app_observation.start-app_observation.end-capture.start-capture.end-preprocess.start-preprocess.end-model.start-model.end-perception.start-perception.end-state.publish-controller.start-controller.end-action.enqueue-input.execute-verification.start-verification.end-```--Each span should be cheap enough to leave on all the time. Avoid synchronous disk writes in the frame loop. Buffer trace events in memory and flush from a background worker.--## Latency Breakdown--Reports should show both total latency and stage latency:--| Metric | Definition |-| --- | --- |-| intent_parse_ms | `intent_parse.end - intent_parse.start` |-| app_focus_ms | `app_focus.end - app_focus.start` |-| app_observation_ms | `app_observation.end - app_observation.start` |-| capture_ms | `capture.end - capture.start` |-| preprocess_ms | `preprocess.end - preprocess.start` |-| model_inference_ms | `model.end - model.start` |-| perception_ms | `perception.end - perception.start` |-| decision_ms | `controller.end - controller.start` |-| input_ms | `input.execute - action.enqueue` |-| verification_ms | `verification.end - verification.start` |-| command_to_first_action_ms | `input.execute - command.accepted` |-| command_to_result_ms | `verification.end - command.accepted` |-| software_loop_ms | `input.execute - capture.end` |-| frame_age_ms | `controller.start - capture.end` |-| state_age_ms | `input.execute - state.publish` |--Frame and state age matter because an action can be computed quickly but still be based on stale data.--## Trace Format--Every action should be traceable:--```text-trace_id-intent_id-frame_id-state_id-action_id-timestamps-latency_breakdown-controller_policy-confidence-planner_hint_id-machine_profile-build_id-```--## Optimization Order--1. Measure each stage with monotonic timestamps.-2. Remove unnecessary work from the hot path.-3. Shrink the capture region.-4. Use frame differencing to skip perception when nothing relevant changed.-5. Move repeated calculations into cached state.-6. Quantize or replace slow models.-7. Split perception into fast local signals and slower background interpretation.-8. Batch only when it reduces total latency without increasing frame age.--## Latency Risks--- Full-screen capture at high resolution.-- Python-only hot loops for pixel-heavy work.-- Large image copies between processes.-- Image encoding or decoding before inference.-- GPU upload/download overhead.-- Model warmup during the first live loop.-- Remote model calls.-- Synchronous logging in the frame loop.-- Input APIs with hidden OS scheduling delays.-- App launch cold-start time.-- Accessibility permission or trust checks.-- Typing into an unverified focused control.--## Benchmark Modes--1. Capture-only benchmark.-2. Perception-only benchmark from recorded frames.-3. Controller-only benchmark from recorded world states.-4. End-to-end dry run with input disabled.-5. End-to-end live run with input enabled.-6. Synthetic reflex test with a controlled visual stimulus.-7. Long soak test for drift, throttling, and memory growth.-8. Weather command-to-result benchmark, with cold-start, warm-app, and manual-baseline modes.--## Monitoring Over Time--Keep a rolling latency history for every serious run.--Track at least:--- latest run-- last good run-- daily best-- daily median-- seven-day trend-- worst regression by stage--Store summaries in a simple machine-readable format:--```text-runs/- 2026-05-12T10-30-00Z/- summary.json- trace.jsonl- config.json-```--The `summary.json` should contain p50, p95, p99, max, FPS, dropped frames, stale actions, and environment details. The `trace.jsonl` can be larger and sampled or compressed as needed.--## Dashboards--Start with a CLI report before building a UI:--```text-Latency report- total p50/p95/p99- per-stage p50/p95/p99- stale actions- dropped frames- worst 10 traces- regression versus baseline-```--Later, add a lightweight local dashboard with:--- live loop latency graph-- per-stage stacked latency-- FPS and queue depth-- stale frame rate-- planner call timeline-- action timeline-- alerts when thresholds are crossed--## Alerts And Regression Gates--Alert on symptoms that matter to feel:--- p95 visual reflex latency over 100ms-- Weather command-to-result latency slower than manual baseline by more than the configured tolerance-- p99 visual reflex latency over 150ms-- stale action rate over 2%-- dropped frame rate over 5%-- perception p95 over 50ms-- model inference p95 over target budget-- preprocessing cost over 20% of perception budget-- controller p95 over 20ms-- queue depth above 1 in the reflex loop-- sustained FPS below target--For the first supported target:--- intent parse p95 under the Weather budget-- app observation p95 under the Weather budget-- verification p95 under the Weather budget-- command-to-first-action p95 under 300ms-- local observation/controller/input step p50 under 60ms-- local observation/controller/input step p95 under 100ms-- command-to-result p95 faster than the manual Weather baseline or explicitly flagged--For later visual targets:--- capture p95 under 15ms-- perception p95 under 50ms-- screenshot preprocessing plus model inference p95 under 50ms-- end-to-end visual reflex p95 under 100ms--Use both absolute and comparative gates:--- absolute gate: fail when latency exceeds the product target-- comparative gate: warn when a stage gets 10% slower than baseline-- comparative hard fail: fail when a stage gets 25% slower than baseline--Small changes can pass absolute targets while still making the system worse over time. The comparative gate catches that drift. Alerts should include the stage that regressed, the previous baseline, and the worst trace ids.--## Replay Harness--Record frames and world states so performance work can happen without launching the target every time.--Replay should support:--- fixed-speed playback-- maximum-speed playback-- deterministic controller comparison-- output action diffing-- latency comparison against a saved baseline-- frame-age and state-age reporting--## Baselines--Keep explicit baselines for each supported target and machine class.--Example:--```text-baselines/- macbook-pro-m3/- weather.json- simple-2d-game.json- windows-desktop-gpu/- simple-2d-game.json-```--Each baseline should record:--- hardware-- OS version-- screen resolution-- app/window settings-- agent config-- capture backend-- model versions-- model runtime-- model precision-- input resolution-- preprocessing pipeline-- measured p50/p95/p99--Do not compare runs across different machines without labeling them. Hardware differences can hide real software regressions.--## First Milestones--1. Add monotonic timestamp helper.-2. Add trace event schema.-3. Record Weather command, observation, action, and verification events.-4. Record capture and action events for visual/reflex runs.-5. Build a local trace viewer or summary command.-6. Add p50/p95/p99 report.-7. Add a same-machine manual Weather baseline.-8. Add a failing threshold check for regressions.-9. Add baseline comparison.-10. Add a 10-minute soak test.-11. Add live console monitoring for active runs.--## Acceptance Criteria--- A single command can print the latest latency report.-- Every Weather task trace includes intent parse, app launch/focus, observation, decision, input, and verification timestamps.-- Every visual action trace includes capture, perception, decision, and input timestamps.-- p50 local observation/controller/input step latency is under 60ms for the first supported target.-- p95 local observation/controller/input step latency is under 100ms for the first supported target.-- command-to-result time is compared with a manual Weather lookup baseline.-- Stale-frame actions are counted and visible in metrics.-- Trace files can explain why an action happened.-- Performance regressions are visible before release time.-- Latency trends can be compared across runs from different days.-- The system can identify whether capture, perception, controller, input, app observation, or verification caused a regression.diff --git a/plans/08-dom-parsing.md b/plans/08-dom-parsing.mddeleted file mode 100644index 24c8b241..00000000--- a/plans/08-dom-parsing.md+++ /dev/null@@ -1,157 +0,0 @@-# DOM Parsing--## Goal--Use DOM state as a low-latency perception channel for browser games, web apps, and desktop software built on web views.--When available, DOM state can be faster and more reliable than computer vision:--- exact text instead of OCR-- element roles instead of visual guessing-- stable ids/classes/data attributes-- input values and checked states-- clickable targets and links-- layout bounds from the browser--DOM parsing should complement screen perception, not replace it entirely. Canvas-heavy games, WebGL games, videos, and custom-rendered UIs may still require pixels.--## Position In The Architecture--```text-Browser / WebView- -> DOM Snapshot Or HTML String- -> DOM Parser / Extractor- -> DOM State- -> World State- -> Fast Controller-```--DOM extraction runs beside screen capture. Both should publish into the same world-state model.--## Recommended Default--Use `node-html-parser` for fast parsing of HTML snapshots:--Source: https://github.com/taoqf/node-html-parser--Why it fits this project:--- designed for performance-- produces a simplified DOM tree-- supports `querySelector` and `querySelectorAll`-- lightweight compared with full browser emulation-- good enough for extracting state from known pages or controlled game UIs--Example use:--```ts-import { parse } from "node-html-parser";--const root = parse(html);-const score = root.querySelector("[data-score]")?.textContent;-const buttons = root.querySelectorAll("button, [role=button]");-```--## Important Limitation--Parsing HTML is not the same as reading a live browser DOM.--If the page is dynamic, the HTML string may miss:--- runtime state stored in JavaScript-- canvas/WebGL content-- shadow DOM details-- computed layout-- event listeners-- transient animation state-- framework state not reflected in attributes or text--For browser-controlled targets, prefer live DOM queries or Chrome DevTools Protocol snapshots when possible.--## Decision Tree--1. If the target is a normal browser page and the agent can execute JavaScript in it, use live DOM queries first.-2. If the agent needs layout bounds, shadow DOM, or computed styles, use Chrome DevTools Protocol `DOMSnapshot.captureSnapshot`.-3. If the agent only has HTML strings or saved snapshots, use `node-html-parser`.-4. If strict browser-compatible parsing matters more than speed, use `parse5`.-5. If jQuery-style extraction is more productive than raw DOM traversal, use `cheerio`.-6. If a nearly complete DOM environment is needed, use `happy-dom` or `jsdom` outside the reflex loop.--## Alternatives--| Option | Best Use | Tradeoff |-| --- | --- | --- |-| Browser-native DOM APIs | fastest live state when inside the page | requires page execution or browser automation access |-| Chrome DevTools Protocol `DOMSnapshot.captureSnapshot` | DOM plus layout/style snapshots | Chrome-specific and snapshot payloads can be large |-| `node-html-parser` | fast HTML snapshot parsing | simplified DOM, not full browser behavior |-| `htmlparser2` | very fast streaming/callback parsing | lower-level API unless paired with DOM utilities |-| `parse5` | standards-compliant HTML parsing | usually heavier than performance-first parsers |-| `cheerio` | ergonomic jQuery-like extraction | useful API, but adds abstraction and may be slower than direct parsing |-| `linkedom` | lightweight DOMParser-style API | less battle-tested than `parse5`/`jsdom` for edge cases |-| `happy-dom` | faster browser-like DOM environment for tests/simulation | much heavier than a simple parser |-| `jsdom` | broad web standards emulation | too heavy for the hot path |--## Hot-Path Rules--- Extract only the selectors needed by the controller.-- Avoid reparsing the full DOM every frame.-- Keep selector lists explicit and small.-- Cache stable nodes or selector results when possible.-- Prefer incremental mutation signals when available.-- Keep full DOM snapshots out of the reflex loop unless measured and proven cheap.-- Drop stale DOM snapshots the same way stale video frames are dropped.--## DOM State Shape--Keep the parsed output compact:--```text-timestamp-page_url-scene_id-visible_text-interactive_elements-game_state_elements-form_values-selected_menu-layout_bounds-confidence-raw_source_id-```--Do not pass parser-specific nodes into the controller. Convert DOM data into the common world-state schema.--## Measurement--Track DOM parsing separately from visual perception:--- html_fetch_ms-- dom_snapshot_ms-- parse_ms-- selector_ms-- extraction_ms-- dom_state_age_ms-- dom_payload_bytes-- selected_node_count--Add these to the latency report so the team can compare:--- vision-only reflex loop-- DOM-only reflex loop-- hybrid DOM plus vision loop--## First Milestones--1. Add `node-html-parser` as the first HTML snapshot parser candidate.-2. Build a small extractor that maps selectors to world-state fields.-3. Benchmark parse time and selector time on representative pages.-4. Add a live DOM query path for browser-controlled targets.-5. Add CDP snapshot evaluation for pages where layout bounds matter.-6. Decide per target whether DOM, vision, or hybrid perception is fastest.--## Acceptance Criteria--- DOM extraction p95 is measured separately from visual perception.-- DOM-derived state can feed the same controller interface as vision-derived state.-- Full DOM parsing is not required on every frame unless it stays inside the latency budget.-- The chosen parser is justified by benchmark results on target pages, not generic package claims.diff --git a/plans/14-synthetic-controller.md b/plans/14-synthetic-controller.mddeleted file mode 100644index 051f59f3..00000000--- a/plans/14-synthetic-controller.md+++ /dev/null@@ -1,335 +0,0 @@-# Synthetic Controller--> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.--## Goal--Build a generic synthetic input controller that emits calibrated input into a target game or app.--This layer should work across games by separating:--- semantic game actions-- normalized controller actions-- target-specific mappings-- OS or device-specific input backends--Touch gestures for iPhone Mirroring are one backend. A virtual gamepad is another backend. Keyboard/mouse is another.--This plan consolidates the previous standalone gamepad-controller sketch. Gamepad support is a backend and command family inside the broader synthetic controller, not a separate top-level architecture.--## Core Idea--The fast controller should not know about screen coordinates, key codes, HID details, or OS input APIs.--It should emit semantic actions:--```text-move_left-move_right-jump-roll-attack-interact-pause-release_all-```--The synthetic controller maps those actions through a target profile:--```text-move_left -> gamepad.dpad_left-move_right -> gamepad.left_stick_x = 1.0-jump -> gamepad.button_south-roll -> touch.swipe_down-interact -> keyboard.E-```--## Architecture--```text-Fast Controller- -> Semantic Action- -> Action Mapper- -> Normalized Input Command- -> Backend Adapter- -> Game / App-```--Backends can include:--- macOS Accessibility tree/action backend-- gamepad / controller-- touch gestures-- keyboard-- mouse-- browser automation-- emulator API--## Normalized Command Interface--Generic commands:--```text-press(action, duration_ms)-hold(action)-release(action)-set_axis(axis, value)-tap(point, duration_ms)-swipe(direction, distance_px, duration_ms)-drag(start, end, duration_ms)-release_all()-stop()-```--Gamepad-shaped commands:--```text-press_button(button, duration_ms)-hold_button(button)-release_button(button)-tap_dpad(direction, duration_ms)-hold_dpad(direction)-release_dpad(direction)-set_left_stick(x, y)-set_right_stick(x, y)-set_left_trigger(value)-set_right_trigger(value)-neutralize_sticks()-release_all()-```--For low latency, axis updates should be cheap and avoid allocation.--Touch-shaped commands:--```text-tap(point, duration_ms=30)-double_tap(point, gap_ms=80)-swipe(direction, distance_px, duration_ms)-drag(start, end, duration_ms)-```--## Target Mappings--Each game should define a mapping file:--```text-target_id-backend-semantic_actions-bindings-timing-dead_zones-cooldowns-safety_rules-```--Example:--```text-target_id: subway-surfers-iphone-mirroring-backend: touch-move_left: swipe_left-move_right: swipe_right-jump: swipe_up-roll: swipe_down-hoverboard: double_tap_center-```--Example:--```text-target_id: generic-controller-game-backend: gamepad-move_left: left_stick_x=-1.0-move_right: left_stick_x=1.0-jump: button_south-attack: button_west-pause: button_menu-```--## Backend Selection--Pick the backend per target:--| Target Type | Preferred Backend |-| --- | --- |-| native Mac app with accessible controls | macOS Accessibility backend |-| native PC/Mac game with controller support | gamepad backend |-| emulator with API | emulator backend |-| iPhone Mirroring touch game | touch gesture backend |-| browser canvas game | mouse/keyboard or browser backend |-| DOM game/app | browser automation or DOM action backend |--If a game supports controllers, prefer the gamepad backend because it is usually more stable than screen-coordinate mouse gestures.--Important iPhone Mirroring caveat:--- Apple documents that wireless game controllers for iPhone apps should be connected to the iPhone, not the Mac.-- A Mac-side virtual controller may not control iPhone games through iPhone Mirroring.-- For iPhone games, gamepad automation may require a controller bridge paired directly to the iPhone, or the touch backend if controller bridging is not available.--## Gamepad Backend Shape--Use a common modern controller shape and keep vendor labels in mapping metadata:--```text-buttons:- south- east- west- north- left_bumper- right_bumper- left_stick_button- right_stick_button- menu- view- home--dpad:- up- down- left- right--axes:- left_stick_x [-1.0, 1.0]- left_stick_y [-1.0, 1.0]- right_stick_x [-1.0, 1.0]- right_stick_y [-1.0, 1.0]- left_trigger [0.0, 1.0]- right_trigger [0.0, 1.0]-```--Gamepad-specific mappings should support:--```text-jump -> press_button(south, 50ms)-dodge -> press_button(east, 50ms)-move_left -> set_left_stick(-1.0, 0.0)-move_right -> set_left_stick(1.0, 0.0)-aim_at -> set_right_stick(x, y)-shoot -> set_right_trigger(1.0)-stop_shoot -> set_right_trigger(0.0)-```--Possible gamepad backends:--- virtual gamepad device-- hardware controller bridge-- emulator controller API-- browser Gamepad API test harness-- platform-specific HID driver--## Backend Contract--Every backend should implement:--```text-connect()-is_available()-get_capabilities()-send(command)-release_all()-measure_latency()-disconnect()-```--Capabilities should declare:--```text-supports_buttons-supports_dpad-supports_analog_sticks-supports_triggers-supports_rumble-supports_low_latency-requires_focus-requires_pairing-```--## Calibration State--Store calibration separately from controller logic:--```text-target_id-target_window_id-target_window_title-backend-content_rect-display_scale-device_orientation-gamepad_layout-axis_dead_zones-button_hold_ms-gesture_distance_px-gesture_duration_ms-cooldowns-last_verified_at-```--## Timing Rules--- Use monotonic timestamps for every command.-- Do not queue stale commands.-- Enforce per-command deadlines.-- Prevent contradictory held inputs.-- Release held axes/buttons on stop.-- Rate-limit repeated taps, swipes, and button presses.-- Keep backend calls out of the perception loop.--Trace every command:--```text-action_id-semantic_action-normalized_command-backend-target_id-created_at-input_start_at-input_end_at-visual_confirmation_at-success-command_create_ms-backend_send_ms-device_update_ms-visual_response_ms-dropped_command_count-stale_command_count-held_input_duration-release_all_latency_ms-```--For controller games, visual response is the real proof that the backend works.--## Safety Rules--- Verify the target before input.-- Stop if the target window or device disappears.-- Stop if confidence is low.-- Stop on payment, login, system dialog, or unknown screen.-- Always support `stop()` and `release_all()`.-- Release all held buttons, keys, sticks, triggers, and mouse buttons on shutdown.--## Testing Plan--1. Build a local input visualizer target for each backend family.-2. Send every button, axis, key, pointer, and gesture command that the backend declares.-3. Verify neutral and release behavior.-4. Measure p50/p95 command-send latency.-5. Test one emulator, simple controller-friendly game, or touch target.-6. Add a target mapping.-7. Replay a recorded action trace.--## Acceptance Criteria--- The fast controller emits semantic actions, not backend-specific input.-- A target mapping can swap touch, keyboard/mouse, and gamepad backends without changing controller logic.-- Buttons, D-pad, sticks, and triggers are all supported in the normalized gamepad interface.-- Held inputs are always released on stop.-- Commands are timestamped and replayable.-- Backend latency is measured separately from decision latency.-- iPhone controller support is treated as a separate backend problem, not assumed through Mac iPhone Mirroring.diff --git a/plans/16-iphone-gameplay-roadmap.md b/plans/16-iphone-gameplay-roadmap.mddeleted file mode 100644index b7c807dd..00000000--- a/plans/16-iphone-gameplay-roadmap.md+++ /dev/null@@ -1,147 +0,0 @@-# iPhone Gameplay Roadmap--> Archived status: historical context only. This file is not an active implementation queue. Supported behavior lives in `docs/`; future work from this idea needs a fresh active plan created deliberately.--## Goal--Make the agent good at playing iPhone games through Apple's iPhone Mirroring app.--This is the near-term product focus. Other targets are useful only when they help this path.--## Product Thesis--iPhone Mirroring turns mobile apps into a Mac window. If the agent can capture that window, understand game state, and send calibrated taps/swipes/controllers with low latency, it can play a broad class of iPhone games without custom game integrations.--## Core Capabilities--Build these in order:--1. iPhone Mirroring window detection-2. iPhone content-rectangle calibration-3. synthetic tap/swipe controller-4. screenshot capture of the mirrored content-5. low-latency perception from screenshots-6. game phase detection: menu, running, crashed, ad/offer, unknown-7. safety guard for purchases, login, ads, system dialogs-8. trace recording and replay-9. per-game adapters-10. model-assisted perception when heuristics are not enough-11. optional PhoneAgent-style RPC/accessibility backend for app navigation, setup, and non-frame-critical iOS control--## Game Progression--### Stage 1: Harness--Target:--- local iPhone Safari test page-- simple tap/swipe detector--Purpose:--- measure mirroring latency-- calibrate coordinates-- verify tap/swipe synthesis-- test focus and stop behavior--Exit criteria:--- 99% tap recognition on a static target-- 95% swipe recognition in four directions-- p95 Mac-side action latency under 100ms-- no stuck input after 10-minute soak--### Stage 2: Simple iPhone Games--Target:--- tap-only games-- puzzle/card/turn-based games-- simple one-finger swipe games--Purpose:--- prove real App Store gameplay-- build menu/retry handling-- harden screenshot perception-- collect traces--Exit criteria:--- agent can play for 3-5 minutes-- failures are classified by perception, control, latency, or safety guard-- no purchase/ad/account flows are touched--### Stage 3: Subway Surfers--Target:--- Subway Surfers through iPhone Mirroring--Purpose:--- flagship latency and perception target-- lane tracking-- obstacle detection-- left/right/up/down swipe control--Exit criteria:--- agent survives longer than no-op and random baselines-- wrong-swipe and missed-obstacle rates are measured-- crashes are explainable from traces-- gameplay improves across recorded runs--### Stage 4: Controller-Supported iPhone Games--Target:--- iPhone games with controller support--Purpose:--- validate generic controller abstraction-- reduce coordinate-dependence-- broaden game coverage--Exit criteria:--- controller backend can drive at least one iPhone controller game-- backend limitations through iPhone Mirroring are documented-- touch and controller mappings share the same semantic action layer--## Success Metrics--Measure both latency and game competence:--- p50/p95/p99 Mac-side loop latency-- iPhone mirroring visual-response latency-- tap/swipe recognition rate-- stale-frame rate-- wrong-action rate-- missed-action rate-- survival time-- score/distance when readable-- retries completed-- safety stops--## Safety Rules--- Use offline or single-player games first.-- Avoid anti-cheat and multiplayer.-- Use a test iPhone/account where possible.-- Stop on purchases, App Store prompts, login, messages, contacts, system settings, ads, or unknown screens.-- Keep all remote model calls outside the reflex loop.-- Record only the cropped mirrored game content when possible.--## Immediate Build Order--1. Finish the macOS synthetic controller foundation.-2. Add iPhone Mirroring window/content detection.-3. Add a calibration command for tap and four swipe directions.-4. Add screenshot capture of the calibrated content rectangle.-5. Add trace logging for every capture, perception result, and input command.-6. Build the local iPhone Safari harness.-7. Capture a PhoneAgent-inspired iOS control prompt and backend contract.-8. Move to one simple iPhone game.-9. Move to Subway Surfers.diff --git a/plans/17-ios-control-prompt.md b/plans/17-ios-control-prompt.mddeleted file mode 100644index aa42351e..00000000--- a/plans/17-ios-control-prompt.md+++ /dev/null@@ -1,156 +0,0 @@-# iOS Control Prompt--## Goal--Capture the operating prompt for controlling iOS, using PhoneAgent as a reference while keeping iPhone Mirroring gameplay as the main product path.--Reference:--- https://github.com/rounak/PhoneAgent--PhoneAgent is an experimental mobile automation project with two relevant ideas:--- an in-app iPhone agent using SwiftUI, XCTest, and the OpenAI Responses API-- an external JSON-RPC bridge that lets agents control iOS/Android devices--For this project, the most useful pattern is the structured control loop: inspect context, choose one action, execute, verify, repeat.--The same pattern applies on macOS through Apple's Accessibility APIs. macOS can expose an accessibility tree and actions for native controls, windows, menus, dialogs, and many app UIs. See [18-macos-accessibility.md](18-macos-accessibility.md).--## Backend Positioning--Use two iOS-control backends:--| Backend | Best Use | Tradeoff |-| --- | --- | --- |-| iPhone Mirroring window backend | real-time visual gameplay, Subway Surfers, App Store games | needs screenshot perception and calibrated Mac input |-| PhoneAgent-style RPC backend | app navigation, accessibility tree, screenshots, setup flows, non-frame-critical iOS actions | XCTest/RPC setup, not necessarily suitable for fast frame-by-frame gameplay |--The gameplay reflex loop should remain iPhone Mirroring first. The RPC backend can help with setup, menus, app launching, screenshots, and accessibility-grounded verification.--## PhoneAgent-Inspired Action Surface--Model the generic iOS action surface around:--```text-get_tree-get_screen_image-get_context-open_app-tap-tap_element-enter_text-scroll-swipe-stop-```--PhoneAgent's README describes these as shared RPC methods for iOS and Android, with an iOS-only `submit_prompt` for its in-app agent loop.--## Core iOS Control Loop--Use this prompt pattern for non-frame-critical iOS control:--```text-You are controlling an iOS device.--Loop:-1. Get context: accessibility tree plus screenshot when available.-2. Decide the next single safe action.-3. Prefer accessibility-tree targets when the UI is structured.-4. Use coordinate/touch actions only when necessary.-5. Execute one action.-6. Verify the result with a fresh tree, screenshot, or context.-7. Stop or ask for help on payment, login, system, privacy, unknown, or unsafe screens.--Rules:-- Use one action at a time.-- Do not queue actions against stale UI.-- Re-read the tree after animations, navigation, or failed taps.-- Prefer tap_element over raw tap when a reliable element frame exists.-- Prefer get_context when both tree and screenshot are useful.-- For games, use screenshot perception and the fast controller instead of slow tree reasoning.-- Keep remote model calls outside the reflex loop.-```--## Game-Specific Prompt Boundary--For iPhone games:--- use the prompt loop for menus, setup, app launch, and recovery-- use the fast screenshot/controller loop for live gameplay-- do not ask the slow planner to decide every dodge, tap, or swipe-- use `game_phase` to decide whether the slow iOS prompt loop is allowed--Recommended boundary:--```text-menu / setup / crashed / unknown -> iOS control prompt may act-running / live gameplay -> fast controller acts-payment / login / system / ad_or_offer -> stop or require explicit approval-```--## World-State Additions--Add optional iOS-control fields:--```text-ios_backend-bundle_identifier-accessibility_tree_id-screenshot_id-focused_app-game_phase-unsafe_screen_reason-last_verified_action_id-```--## Backend Contract--Whether the implementation is PhoneAgent, iPhone Mirroring, or a future bridge, expose a common interface:--```text-get_context() -> tree?, screenshot?, metadata-open_app(bundle_identifier)-tap(x, y)-tap_element(frame_or_element_id)-enter_text(target, text)-scroll(x, y, dx, dy)-swipe(x, y, direction)-stop()-```--Every response should include enough fresh context to verify progress when practical.--## Safety Rules--- Keep iOS control localhost/local-device oriented.-- Do not enter passwords, 2FA codes, payment details, or private messages automatically.-- Stop on App Store purchases, login screens, permission prompts, messages, contacts, system settings, or unknown sensitive screens.-- Use test devices/accounts where possible.-- Screenshot artifacts can contain sensitive phone data; crop to game content and redact when possible.--## When To Use PhoneAgent Ideas--Use them for:--- opening apps by bundle identifier-- reading accessibility trees-- tapping known UI elements-- entering text into structured fields-- taking screenshots for verification-- recovering from menus or settings screens--Avoid them for:--- per-frame Subway Surfers decisions-- low-latency dodge/jump/roll loops-- any gameplay path where RPC round trips make state stale--## First Milestones--1. Keep iPhone Mirroring as the primary gameplay backend.-2. Define the shared iOS control interface above.-3. Add an optional PhoneAgent-style backend adapter plan.-4. Build prompts that separate slow iOS UI control from fast gameplay control.-5. Use accessibility/context only when it improves reliability without hurting reflex latency.diff --git a/plans/18-macos-accessibility.md b/plans/18-macos-accessibility.mddeleted file mode 100644index a1a3d904..00000000--- a/plans/18-macos-accessibility.md+++ /dev/null@@ -1,20 +0,0 @@-# macOS Accessibility--> Archived status: this slice is implemented. Supported behavior lives in `docs/`; future work needs a fresh active plan created deliberately.--## Completed Slice--Donkey now treats iPhone Mirroring as an ordinary Mac window candidate. Window discovery builds runtime app identity from the current `NSWorkspace` running-app map, enriches each visible window by pid, and keeps iPhone Mirroring as an additive hint instead of a separate discovery path.--The implemented accessibility/window slice covers:--- content-rectangle calibration for mirrored iPhone content inside the selected generic target window-- generic target-window focus, process, bundle, bounds, visibility, and safety guarding before synthetic input-- timeout-bounded Accessibility snapshot reads and Accessibility action execution-- native macOS dialog detection from Accessibility trees as a safety stop--## Current Boundary--Accessibility still describes the Mac-side container and native dialogs. It does not inspect iPhone game internals inside the mirrored video stream. Live gameplay perception remains screenshot/model driven, with the calibrated content rectangle feeding the capture/control loop.--No remaining implementation queue is tracked in this plan.diff --git a/plans/20-off-the-shelf-run-loop.md b/plans/20-off-the-shelf-run-loop.mddeleted file mode 100644index 261f5f7b..00000000--- a/plans/20-off-the-shelf-run-loop.md+++ /dev/null@@ -1,547 +0,0 @@-# Off-The-Shelf Run Loop--## Goal--Build the first fast local navigation agent from existing system components instead of custom model work.--The first product proof is a local Weather lookup navigation benchmark expressed through a generic local-app task system. Donkey should interpret a natural command, resolve the installed app and task definition, use local macOS navigation to open or focus the target app, perform the defined expert-user workflow, verify the app is showing the requested result, and leave the result visible. It should feel faster than manual app navigation or a chat assistant because most work is local and deterministic.--Fast navigation is the focus across apps and games. Use Accessibility, app/window metadata, LaunchServices, keyboard input, bounded screenshot/crop context for local model UI understanding, open-vocabulary detectors, segmentation, templates, OCR when specifically measured as useful, and classical CV as swappable navigation signals. Start with the cheapest local signal that can reliably move the target toward the requested state.--## Target Shape--```text-User Command- -> Intent Parser- -> Task Adapter- -> App Launch / Focus- -> Accessibility / Window Metadata / Screenshot Fallback- -> Task State- -> Deterministic UI Controller- -> Action Engine- -> Keyboard / Mouse / Accessibility Action- -> Result Verification--Reasoning LLM- <-> Ambiguous Intent / UI Understanding / Memory / Recovery-```--The hot path is local and bounded. A small model can help interpret unusual phrasing, but app navigation and action timing come from deterministic logic over structured state. Voice commands should enter this same path as transcript text. The selected local ASR model belongs in the model registry; the run loop should only consume validated transcript text and should never let an audio model emit actions directly.--## Core Rule--Do not build a custom model pipeline for the first version.--The first version should prove:--- local-model command-to-intent parsing is reliable for common tasks and validated against known app-task definitions-- local voice transcription, when wired, produces transcript text before the same command-to-intent validation path-- macOS app launch/focus is reliable-- Accessibility/window metadata can extract useful app state-- local visual fallback is available only when Accessibility and metadata are insufficient-- state is compact and timestamped-- controller rules can act on that state-- guarded live input can type/search safely-- result verification can confirm the requested target-- latency is measured end to end-- the LLM can help with ambiguous phrasing and recovery without blocking local navigation--## Hot-Path Components--Use existing, swappable components:--- local-model command parser for common local commands using app-task definitions-- local voice transcription adapter for microphone commands before command parsing-- deterministic parser only as fallback, validator, and test scaffold-- installed-app and task-knowledge lookup for target app identity, workflows, controls, and verification rules-- small local model or planner hint only for ambiguous command parsing-- target/task adapters for app-specific workflows-- LaunchServices or Workspace app launch/focus-- Accessibility snapshots/actions for app UI state and controls-- keyboard/mouse input behind guardrails-- local model UI understanding for bounded screenshot/crop fallback-- template matching or OCR only when measured as better for a narrow UI fallback-- YOLO-family detector for boxes, UI elements, enemies, objects, and markers-- SAM / SAM2 / MobileSAM / FastSAM for masks when boxes are not enough-- OCR for text, labels, and menus only when a task-specific benchmark shows it is better than local model UI understanding-- color/edge/motion heuristics for simple fast signals-- deterministic state machines for action decisions-- LLM planner only for slow hints and recovery--Avoid:--- custom policy models-- custom action models-- custom neural networks-- full LLM decision-making every frame-- Ollama or any chat LLM in the per-frame action path-- remote model calls for common app-command execution-- Python pixel loops in the hot path-- generic agent frameworks around every frame--## Runtime Stack--Keep the runtime optimized even when the models are off the shelf.--Preferred inference paths:--- ONNX Runtime as the portable boundary-- TensorRT on NVIDIA when it wins measured p95 latency-- CUDA graphs for fixed-shape repeated inference when launch overhead matters-- DirectML or WinML as a broad Windows fallback-- Core ML / Metal on Apple hardware-- CPU only for tiny templates, OCR snippets, or very small local models--Runtime rules:--- keep model inputs fixed-size when possible-- warm every model before live control starts-- preallocate buffers-- avoid PNG/JPEG encode/decode in the hot loop-- drop stale frames-- cap queue sizes at 1 in the reflex path-- benchmark each component separately and together--## Product-Grade Run Loop--Wrap the low-latency loop in an OpenClaw-inspired runtime shell, but do not make Donkey depend on OpenClaw, Pi, or a generic agent framework in the hot path.--The product loop should look like:--```text-intake / local intent parse- -> session queue- -> context assembly- -> task adapter selection- -> local app observation- -> deterministic controller- -> tool / action execution- -> result verification- -> streaming events- -> transcript / trace persistence- -> compaction / recovery-```--The runtime shell owns coordination. It loads target adapters and skills, resolves model/auth/runtime profiles, subscribes to model/tool/reflex events, enforces queue sizes and deadlines, applies tool permission policy, and bridges events back to UI or client streams.--The runtime shell does not own app-specific workflow internals, perception logic, controller policy internals, or direct OS input. Those stay behind explicit intent, task-adapter, capture/perception, controller, and action-engine interfaces.--### First Benchmark: Weather Lookup--The first supported benchmark definition is:--```text-"show me the weather for SF"- -> weather_lookup(city: "San Francisco")- -> resolve target app/task metadata- -> open/focus the target app- -> perform the definition's search/select workflow- -> verify displayed result-```--The first local-app task adapter should stay generic and support:--- deterministic alias expansion for common city shorthand such as `SF`-- dry-run trace output before live input-- app launch/focus through a narrow macOS app-control boundary based on resolved target app metadata-- observation through Accessibility first, window metadata second, local model UI understanding over bounded screenshots/crops third, OCR only as an optional measured adapter-- guarded text entry into the resolved task control-- verification that visible app output matches the normalized requested entity-- terminal result states: completed, needs-user-review, failed-safe, timed-out--### Event Bridge--Publish a small set of typed event streams:--- `assistant`: user-visible reasoning, recovery notes, explanations, summaries-- `tool`: capture, perception, controller, action, Accessibility, model, and persistence calls-- `lifecycle`: run started, paused, resumed, aborted, timed out, completed-- `reflex`: frame, state, and action trace events, sampled or summarized to avoid hot-path overhead--All event envelopes should include trace ids where possible. Reflex events must be cheap to emit and safe to drop or sample when the loop is under pressure.--### Run Coordination Responsibilities--The coordinator should provide the product-grade parts around the loop:--- session queue with latest-request-wins behavior for live control-- run lifecycle state: idle, starting, running, paused, stopping, completed, failed-- tool permission policy for capture, Accessibility, model calls, and input actions-- transcript and trace persistence with a single writer or explicit append lock-- context compaction before slow planner calls-- streaming event publication for UI/client observers-- abort and timeout handling that releases held input and closes streams-- sandbox/focus guard for risky tools and OS input-- bounded queues, deadlines, and stale-frame drops--### Conceptual Runtime Shape--This pseudocode is conceptual. It describes coordination boundaries, not the exact Swift API.--```swift-while run.isActive {- let ticket = await sessionQueue.nextLatest()-- let context = await contextAssembler.build(- session: ticket.session,- latestWorldState: stateStore.latest(),- transcriptSummary: transcript.compactedSummary(),- activeHints: hintStore.validHints()- )-- let plannerResult = await planner.maybeGenerate(- context: context,- timeout: policy.plannerTimeout- )-- await hintStore.publishValidated(plannerResult.hints)- await stream.publish(plannerResult.events)-- while let frame = await frameBuffer.latestIfFresh() {- let state = await perception.update(frame)- let action = controller.decide(state, hintStore.validHints())-- guard await permissionPolicy.allows(action),- await focusGuard.targetIsSafe()- else {- await lifecycle.pause(reason: .unsafeActionSurface)- break- }-- let result = await actionEngine.execute(action)- await traceStore.append(frame, state, action, result)- await stream.publishReflexSample(frame, state, action, result)- }-}-```--Separate the loops in implementation:--- reflex loop: latest-frame-wins capture, local perception, deterministic controller, bounded action execution-- planner loop: context assembly, model call, validated planner hints, memory updates-- tool/action loop: permission checks, sandbox/focus guard, execution, trace persistence--Remote LLM and chat-style local LLM work belongs in the planner loop. It must never be required for reflex ticks or direct input.--### Interfaces To Define--Define these contracts before the first production coordinator implementation:--- `RunSession`: user goal, target id, runtime profile, permission scope, lifecycle state-- `RunEvent`: assistant/tool/lifecycle/reflex event envelope with trace ids-- `TaskIntent`: parsed local app task, normalized entities, confidence, parser source-- `TaskAdapter`: app-specific observation, action selection, verification, and recovery hooks-- `ToolCallPolicy`: allow, deny, or ask rules for capture, Accessibility, model, and input actions-- `TranscriptStore` / `TraceStore`: append-only persistence with a single writer or explicit lock-- `ContextAssembler`: compact planner context from world state, traces, memory, screenshots, and user goal-- `RunCoordinator`: queueing, cancellation, timeouts, event bridging, and lifecycle ownership--## Platform Defaults--### Windows--Best default for raw desktop game performance:--```text-DXGI Desktop Duplication- -> crop on GPU or with minimal copy- -> ONNX Runtime / TensorRT / DirectML- -> native input backend-```--Use TensorRT first on NVIDIA if the model exports cleanly and p95 latency improves. Use DirectML/WinML when broader GPU support matters more than peak NVIDIA performance.--### macOS--Best default for local app task control:--```text-Natural command- -> deterministic/local intent parser- -> NSWorkspace/LaunchServices app activation- -> Accessibility tree/action when trusted- -> guarded keyboard/mouse fallback- -> ScreenCaptureKit/local model UI understanding only for missing UI facts-```--Use Accessibility for window bounds, focus checks, controls, dialogs, and setup flows. Use screenshot perception only when the app does not expose the needed state through Accessibility.--## Vision Options--### Detector First--For later visual targets, start with a detector when the target state can be represented as objects.--Good jobs:--- enemies-- obstacles-- buttons-- collectibles-- health bars-- hit markers-- lane markers-- minimap markers--Use current Ultralytics YOLO-family nano/small models as candidates. The exact model should be selected by export support, license, latency, and whether the built-in labels are useful. As of the official Ultralytics docs checked on May 17, 2026, YOLO26 is the latest line, YOLO11 is a stable modern line, and YOLOv8 remains widely supported. The current screenshot segmentation catalog candidate is `yolo26n-seg.pt`, and it should run on bounded crops before any full-screenshot or live-control use.--### Segment Anything When Needed--Use SAM-style segmentation when object boundaries matter or the scene is too irregular for boxes.--Candidate options:--- SAM / SAM2 for high-quality masks and video/image segmentation-- MobileSAM for lighter local segmentation-- FastSAM for faster approximate masks-- Ultralytics SAM integrations when they simplify wiring--Use segmentation sparingly in the hot loop. It is often better as:--- slow-path scene understanding-- mask proposal for a region of interest-- setup/calibration helper-- fallback when detection is ambiguous--### Local Model UI Understanding And OCR--Use local model UI understanding over bounded screenshot or crop context for:--- menus-- labels-- scores-- inventory text-- quest text-- countdowns--OCR remains a useful narrow adapter, but it should not be the default visual fallback. Prefer local model UI understanding when the question is semantic, layout-dependent, or app-specific. Use OCR when the needed signal is plain text, the crop is small, and measured p95/cost/reliability beats the local model path.--Local model or OCR work should usually run on cropped regions, not the full frame.--### Templates And Classical CV--Use simple methods when they work:--- template matching for known buttons/icons-- color thresholding for health/resource bars-- optical flow or frame differencing for motion-- edge/shape heuristics for simple lanes and obstacles-- DOM parsing when the target is web-based--These are often faster and easier to debug than a model.--## Task State--Convert all observation outputs into a compact state object:--```text-state_id-frame_id-timestamp-target_id-task_intent_id-app_id-scene_type-objects-masks-text-ui_flags-action_affordances-confidence-source_ages-planner_hint_id-```--Rules:--- include confidence and age for every signal-- keep coordinate spaces explicit-- mark stale fields instead of silently using them-- do not expose detector tensors or raw masks directly to the controller-- prefer task-specific state over generic scene captions--For a local app task, state should include task-specific facts such as:--```text-app_running-app_frontmost-required_control_available-entered_text-selected_result-visible_result_text-requested_result_visible-confidence-verification_reason-```--## Controller--Use deterministic logic over task state:--```text-Task State- -> Policy Selector- -> Rule / State Machine- -> Semantic Action- -> Calibrated Input-```--Examples:--- target app not running -> launch app-- target app running but not focused -> focus app-- required control visible and empty -> type normalized entity-- matching suggestion/result visible -> select suggestion-- visible result matches normalized entity -> complete-- obstacle on left lane -> move center/right-- button visible and safe -> tap button center-- health low -> request planner recovery hint-- menu state unknown -> pause and ask LLM to classify snapshot-- target box center offset -> move/click toward center-- countdown text appears -> wait or prepare action--The controller should be boring, inspectable, and traceable.--## LLM Role--Use LLMs for:--- interpreting ambiguous commands when deterministic intent parsing is insufficient-- interpreting unfamiliar screens-- choosing objectives-- explaining failures-- deciding which detector/local-model/OCR/template signals matter-- suggesting recovery steps-- summarizing memory-- reading slow-path screenshots or UI snapshots-- producing structured planner hints--Do not use LLMs for:--- launching apps-- typing ordinary search text-- clicking known controls-- aiming every frame-- dodge timing-- tap/swipe timing-- continuous movement-- direct OS input--LLM output must become validated hints, not direct actions.--## First Supported Benchmark Recommendation--Pick one navigation scenario with a visible, verifiable end state.--The first benchmark is still Weather lookup, represented as a local-app task definition rather than a dedicated adapter:--- command: "show me the weather for SF"-- normalized intent: `weather_lookup(city: "San Francisco")`-- target app: resolved from task definition-- success: target app is frontmost and visibly showing the requested result--Weather is only the first benchmark definition. The same catalog, local-model intent parser, context intake, and guarded runtime should support other user tasks such as playing music in a media app or filling a document from structured data without introducing source-specific runtime classes.--Good follow-on tasks:--- fast game/menu navigation to a known screen-- open Calendar to a named date-- search Mail for a sender-- create a short Notes note-- open a browser tab to a known site-- navigate a repeated game menu--Suggested first stack:--```text-Intent: local-model parser with deterministic fallback/validation-App control: NSWorkspace/LaunchServices activation-Observation: Accessibility snapshot first, local model UI understanding over bounded screenshot/crop fallback-Rules: deterministic local-app task state machine-Input: guarded keyboard/mouse or Accessibility action backend-Reasoning: local/online planner only for recovery or ambiguity-Runtime: native Swift coordinator and trace pipeline-```--## Rollout--1. Define generic `TaskIntent`, target-app, entity, workflow-step, observation, and verification contracts.-2. Add local-model command parsing from local app-task definitions, including aliases such as `SF -> San Francisco` in benchmark data, with deterministic parsing kept as fallback/validation.-3. Load additional local app-task definitions from Application Support so new workflows can be added as data.-4. Add installed-app and app-task knowledge lookup for target app identity, workflows, controls, and verification rules.-5. Define generic task-state fields and terminal states.-6. Extend the generic local-app task adapter from dry-run semantic actions to guarded-live orchestration.-7. Add app launch/focus action commands and guardrails.-8. Add guarded text-entry and submit/select commands.-9. Add Accessibility observation for resolved controls and visible result text.-10. Add local task-context intake for focused app/window metadata, clipboard structured data, attached files, and observed form fields.-11. Add review-first document/data mapping before any guarded form-fill execution.-12. Add local model UI-understanding fallback only where Accessibility and metadata are insufficient; keep OCR optional and measured.-13. Add result verification for normalized requested entities.-14. Add command-to-result latency report and manual baseline comparison.-15. Add optional slow planner recovery only after deterministic execution works.-16. Keep game/vision adapters as follow-on targets using the same contracts.--## Acceptance Criteria--- No custom model work is required.-- The hot loop can run with the LLM disabled.-- The first local-app task benchmark can run without a remote model call.-- Every perception component is swappable.-- Every action is explainable from state, rule, and trace id.-- p95 local navigation/action latency stays under the target budget.-- command-to-result latency is measured against a manual baseline.-- LLM output is validated before it changes controller configuration.-- Local model UI understanding, segmentation, and OCR are cropped and measured before live use.-- The runtime coordinator can start, pause, abort, timeout, and complete a run.-- Abort releases held input and publishes a terminal lifecycle event.-- Session queue drops stale live-control work instead of building backlog.-- Permission policy can deny unsafe input before action execution.-- Transcript and trace writes stay ordered under concurrent model/tool/reflex events.-- Context compaction keeps planner input bounded while preserving the latest goal, state, failures, and valid hints.--## Current Supported Slice--The runtime foundation now supports a product-shaped local-navigation slice of the off-the-shelf loop:--- typed reflex trace records with capture, preprocessing, model, perception, state, controller, action, and input timestamps-- bounded target-window frame capture for dry-run frames without PNG/JPEG hot-path encoding-- cheap metadata perception and swappable world-state projection-- recorded off-the-shelf detector/template/OCR/segmentation evidence projection with crop ids, model/component ids, confidence, coordinate spaces, and measured preprocessing/model latency-- loop-integrated metadata-only local-navigation dry-run selection with optional browser-tab metadata-- latest-frame-wins queue depth 1 with dropped-frame counting-- p50/p95/p99 latency reports across capture, preprocess, model, perception, state update, controller decision, action projection, and input stages-- action-engine permission, focus, rate, hold-duration, release, and backend-execution guardrails-- guarded live-action smoke through an injected backend only after dry-run latency evidence, explicit input policy allowance, and focus guard success-- generic local-app task catalog, intent contracts, built-in benchmark definitions across Weather lookup, Music playback, and PDF/document form-fill, local JSON/JSONL task-definition loading, local-model command parsing, deterministic fallback parsing, local task-context intake, Accessibility control discovery, review/approval-first document form-fill planning, pointer-prompt typed command submission, dry-run workflow-step projection, guarded keyboard and Accessibility command templates, macOS launch/focus, guarded macOS keyboard input, guarded `AXPress`/`AXSetValue` backend, Accessibility visible-text observation when trusted, and visible-text verification-- screenshot segmentation model-candidate metadata and runner evidence boundary for Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`)-- local voice transcription adapter boundary that routes bounded local audio to the selected local ASR runtime and emits transcript text for the normal command parser-- optional slow-planner sidecar that publishes only validated hints without blocking reflex latency-- coordinator event publication for pointer-prompt local-app task runs, including lifecycle and tool events for launch/focus, guarded input, Accessibility actions, observation, and terminal status-- user-visible document form-fill review UI that applies only approved field proposals through guarded Accessibility input-- live local-app visual fallback policy that uses bounded screenshot UI understanding only when Accessibility/window metadata do not provide required controls or verification text-- continuous target-window frame streaming source for longer dry-run reflex sessions while preserving latest-frame-wins queue behavior--This slice can replay and trace compact local vision evidence, name a current YOLO segmentation candidate, load local task definitions, discover Accessibility controls, build approval-gated document form-fill commands, run a guarded keyboard/AX local-app task path, publish coordinator events for local-app runs, open a document form-fill approval UI, use local UI understanding only as an observation fallback, and stream target-window frames for longer dry-run sessions. Broader visual model runtime expansion is intentionally outside this plan.--## Required Before This Plan Is Done--No remaining implementation items are tracked in this plan. Benchmarking and broader model-runtime expansion are intentionally ignored here; create or activate a separate plan before pursuing them.--## Where To Look--- Ultralytics supported models: https://docs.ultralytics.com/models/-- Ultralytics YOLO26 model docs: https://docs.ultralytics.com/models/yolo26/-- Ultralytics segmentation task docs: https://docs.ultralytics.com/tasks/segment/-- YOLO11 model card: https://huggingface.co/Ultralytics/YOLO11-- Segment Anything repository: https://github.com/facebookresearch/segment-anything-- SAM2 repository: https://github.com/facebookresearch/sam2-- FastSAM repository: https://github.com/CASIA-LMC-Lab/FastSAM-- ONNX Runtime execution providers: https://onnxruntime.ai/docs/execution-providers/-- ONNX Runtime TensorRT EP: https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html-- ONNX Runtime DirectML EP: https://onnxruntime.ai/docs/execution-providers/DirectML-ExecutionProvider.html-- Microsoft DXGI Desktop Duplication API: https://learn.microsoft.com/en-us/windows/win32/direct3ddxgi/desktop-dup-api-- Apple ScreenCaptureKit: https://developer.apple.com/documentation/screencapturekit-- Apple Core ML: https://developer.apple.com/machine-learning/core-ml/-- OpenAI model guide: https://developers.openai.com/api/docs/models-- OpenAI Responses API: https://platform.openai.com/docs/api-reference/responsesdiff --git a/plans/done/15-gamepad-controller.md b/plans/done/15-gamepad-controller.mddeleted file mode 100644index 3cf6b520..00000000--- a/plans/done/15-gamepad-controller.md+++ /dev/null@@ -1,5 +0,0 @@-# Gamepad Controller--> Consolidated into `plans/14-synthetic-controller.md`.--This historical plan duplicated the synthetic-controller abstraction. Its useful gamepad-specific details now live in the canonical synthetic controller plan as the gamepad backend shape, backend contract, iPhone Mirroring caveat, measurement notes, testing plan, and acceptance criteria.diff --git a/plans/done/19-ai-harness.md b/plans/done/19-ai-harness.mdindex 5a8067a1..fcf596d3 100644--- a/plans/done/19-ai-harness.md+++ b/plans/done/19-ai-harness.md@@ -1,6 +1,6 @@# AI Harness Memory And Voice Cleanup-> Active status: implemented. This plan was narrowed to semantic-memory wiring, provider memory write proposals, live voice audio hardening, and focused tests. Those slices are now supported in local code. Benchmarking is out of scope for this plan.+> Completed. This plan was narrowed to semantic-memory wiring, provider memory write proposals, live voice audio hardening, and focused tests. Those slices are now supported in local code.## 1. Wire Real Semantic Memory Retrievaldiff --git a/plans/done/21-swiftui-pointer-ui.md b/plans/done/21-swiftui-pointer-ui.mdindex ede6f7f8..692fe897 100644--- a/plans/done/21-swiftui-pointer-ui.md+++ b/plans/done/21-swiftui-pointer-ui.md@@ -14,7 +14,6 @@ Add the production macOS SwiftUI pointer prompt UI while keeping the future real- The prompt follows the mouse at bottom right by default, flips to the opposite side near screen edges, and stays clamped inside the visible screen.- The active pointer renders with a shadow and supports theme-color customization.- Contracts, UI, runtime boundary, AI boundary, and app entrypoint are separate Swift targets.-- Runtime boundary references `plans/20-off-the-shelf-run-loop.md`.- AI boundary references `plans/done/19-ai-harness.md`.- No Screen Recording, Accessibility, model calls, capture loop, or input execution is included in this slice.diff --git a/plans/done/manual-target-context-capture-master-plan.md b/plans/done/manual-target-context-capture-master-plan.mdindex aa6211a8..80e50119 100644--- a/plans/done/manual-target-context-capture-master-plan.md+++ b/plans/done/manual-target-context-capture-master-plan.md@@ -34,4 +34,4 @@ Supported behavior and engineering guidance belong in `docs/guides/agent-harness## Completion-This milestone is complete. Supported behavior and engineering guidance live in `docs/guides/agent-harness.md`; future implementation should continue from the active capture, Accessibility, benchmarking, and off-the-shelf run-loop plans.+This milestone is complete. Supported behavior and engineering guidance live in `docs/guides/agent-harness.md`; future implementation should start from `plans/master-plan.md`.