Skip to content

Open source CapCut alternative.

TypeScript

Add generic AX, voice, and segmentation pipeline support

David Lebfb427b63cac
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
index 133abc59..63cc0c49 100644
--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
@@ -20,7 +20,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
var liveRunner: LocalAppTaskLiveRunner
init(
- catalog: LocalAppTaskCatalog = LocalAppTaskCatalog(taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults),
+ catalog: LocalAppTaskCatalog = .defaultLocal(),
localModelResolver: LocalModelTaskIntentResolver? = nil,
liveRunner: LocalAppTaskLiveRunner? = nil
) {
@@ -70,6 +70,10 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
case .completed:
return "Done"
case .needsUserReview:
+ if let proposalCount = result.documentFormFillPlan?.proposals.count,
+ proposalCount > 0 {
+ return "Review \(proposalCount) fields"
+ }
return "Needs review"
case .needsConfirmation:
if let reason = result.resolution.metadata["reason"] {
diff --git a/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
new file mode 100644
index 00000000..1f8481fa
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
@@ -0,0 +1,240 @@
+import DonkeyContracts
+import Foundation
+
+public struct LocalVoiceAudioBuffer: Equatable, Sendable {
+ public var id: String
+ public var format: String
+ public var sampleRateHz: Int
+ public var channelCount: Int
+ public var durationMS: Double
+ public var data: Data
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ format: String = "wav",
+ sampleRateHz: Int = 16_000,
+ channelCount: Int = 1,
+ durationMS: Double,
+ data: Data,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.format = format
+ self.sampleRateHz = sampleRateHz
+ self.channelCount = channelCount
+ self.durationMS = max(0, durationMS)
+ self.data = data
+ self.metadata = metadata
+ }
+}
+
+public struct LocalVoiceTranscriptionRequest: Equatable, Sendable {
+ public var audio: LocalVoiceAudioBuffer
+ public var sourceTraceID: String
+ public var routeRequest: AIModelRouteRequest
+
+ public init(
+ audio: LocalVoiceAudioBuffer,
+ sourceTraceID: String,
+ routeRequest: AIModelRouteRequest = AIModelRouteRequest(
+ jobType: .voiceTranscription,
+ requiredCapabilities: [.audioInput],
+ allowedProviders: [.localRuntime]
+ )
+ ) {
+ self.audio = audio
+ self.sourceTraceID = sourceTraceID
+ self.routeRequest = routeRequest
+ }
+}
+
+public struct LocalVoiceTranscript: Codable, Equatable, Sendable {
+ public var text: String
+ public var language: String?
+ public var confidence: Double
+ public var segments: [String]
+ public var metadata: [String: String]
+
+ public init(
+ text: String,
+ language: String? = nil,
+ confidence: Double,
+ segments: [String] = [],
+ metadata: [String: String] = [:]
+ ) {
+ self.text = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ self.language = language
+ self.confidence = min(max(confidence, 0), 1)
+ self.segments = segments
+ self.metadata = metadata
+ }
+}
+
+public struct LocalVoiceTranscriptionResult: Equatable, Sendable {
+ public var transcript: LocalVoiceTranscript?
+ public var trace: AIModelCallTrace
+
+ public init(transcript: LocalVoiceTranscript?, trace: AIModelCallTrace) {
+ self.transcript = transcript
+ self.trace = trace
+ }
+}
+
+public protocol LocalVoiceTranscriptionRuntime: Sendable {
+ func transcribe(
+ audio: LocalVoiceAudioBuffer,
+ model: AIModelRegistryEntry
+ ) async throws -> LocalVoiceTranscript
+}
+
+public struct UnavailableLocalVoiceTranscriptionRuntime: LocalVoiceTranscriptionRuntime {
+ public init() {}
+
+ public func transcribe(
+ audio: LocalVoiceAudioBuffer,
+ model: AIModelRegistryEntry
+ ) async throws -> LocalVoiceTranscript {
+ throw LocalVoiceTranscriptionRuntimeError.runtimeUnavailable(model.id)
+ }
+}
+
+public enum LocalVoiceTranscriptionRuntimeError: Error, Equatable, Sendable {
+ case runtimeUnavailable(String)
+ case emptyTranscript
+}
+
+public struct LocalVoiceTranscriptionAdapter: Sendable {
+ public var router: AIModelRouter
+ public var runtime: any LocalVoiceTranscriptionRuntime
+ public var now: @Sendable () -> RunTraceTimestamp
+
+ public init(
+ router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),
+ runtime: any LocalVoiceTranscriptionRuntime = UnavailableLocalVoiceTranscriptionRuntime(),
+ now: @escaping @Sendable () -> RunTraceTimestamp = Self.defaultNow
+ ) {
+ self.router = router
+ self.runtime = runtime
+ self.now = now
+ }
+
+ public func transcribe(_ request: LocalVoiceTranscriptionRequest) async -> LocalVoiceTranscriptionResult {
+ let startedAt = now()
+ let entry: AIModelRegistryEntry
+ do {
+ entry = try router.route(request.routeRequest)
+ } catch {
+ return LocalVoiceTranscriptionResult(
+ transcript: nil,
+ trace: trace(
+ model: nil,
+ sourceTraceID: request.sourceTraceID,
+ startedAt: startedAt,
+ status: .providerOutage,
+ validationStatus: "routingFailed",
+ metadata: ["reason": String(describing: error)]
+ )
+ )
+ }
+
+ do {
+ let transcript = try await runtime.transcribe(audio: request.audio, model: entry)
+ guard !transcript.text.isEmpty else {
+ throw LocalVoiceTranscriptionRuntimeError.emptyTranscript
+ }
+ return LocalVoiceTranscriptionResult(
+ transcript: transcript,
+ trace: trace(
+ model: entry,
+ sourceTraceID: request.sourceTraceID,
+ startedAt: startedAt,
+ status: .completed,
+ validationStatus: "transcriptDecoded",
+ metadata: metadata(for: request.audio, transcript: transcript)
+ )
+ )
+ } catch is CancellationError {
+ return LocalVoiceTranscriptionResult(
+ transcript: nil,
+ trace: trace(
+ model: entry,
+ sourceTraceID: request.sourceTraceID,
+ startedAt: startedAt,
+ status: .cancelled,
+ validationStatus: "notValidated",
+ metadata: metadata(for: request.audio)
+ )
+ )
+ } catch {
+ return LocalVoiceTranscriptionResult(
+ transcript: nil,
+ trace: trace(
+ model: entry,
+ sourceTraceID: request.sourceTraceID,
+ startedAt: startedAt,
+ status: .providerOutage,
+ validationStatus: "notValidated",
+ metadata: metadata(for: request.audio).merging([
+ "reason": String(describing: error)
+ ]) { current, _ in current }
+ )
+ )
+ }
+ }
+
+ private func trace(
+ model: AIModelRegistryEntry?,
+ sourceTraceID: String,
+ startedAt: RunTraceTimestamp,
+ status: AIModelCallStatus,
+ validationStatus: String,
+ metadata: [String: String]
+ ) -> AIModelCallTrace {
+ let completedAt = now()
+ return AIModelCallTrace(
+ id: "voice-transcription-\(sourceTraceID)",
+ role: .voiceTranscription,
+ provider: model?.provider ?? .localRuntime,
+ modelID: model?.modelID ?? "unrouted",
+ promptVersion: model?.promptVersion ?? "voice-transcription-v1",
+ schemaID: "voice-transcript-v1",
+ latencyMS: startedAt.milliseconds(until: completedAt),
+ timeoutMS: model?.timeoutMS ?? 0,
+ status: status,
+ validationStatus: validationStatus,
+ sourceTraceID: sourceTraceID,
+ metadata: metadata.merging([
+ "localOnly": "true",
+ "transcriptFeedsCommandParser": "true"
+ ]) { current, _ in current }
+ )
+ }
+
+ private func metadata(
+ for audio: LocalVoiceAudioBuffer,
+ transcript: LocalVoiceTranscript? = nil
+ ) -> [String: String] {
+ var values = [
+ "audio.id": audio.id,
+ "audio.format": audio.format,
+ "audio.sampleRateHz": String(audio.sampleRateHz),
+ "audio.channelCount": String(audio.channelCount),
+ "audio.durationMS": String(audio.durationMS),
+ "audio.byteCount": String(audio.data.count)
+ ]
+ if let transcript {
+ values["transcript.confidence"] = String(transcript.confidence)
+ values["transcript.language"] = transcript.language ?? ""
+ values["transcript.segmentCount"] = String(transcript.segments.count)
+ }
+ return values
+ }
+
+ public static func defaultNow() -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(),
+ monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillPlanner.swift b/apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillPlanner.swift
new file mode 100644
index 00000000..8de2e4ac
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillPlanner.swift
@@ -0,0 +1,251 @@
+import DonkeyContracts
+import Foundation
+
+public enum DocumentFormFillPlanStatus: String, Codable, Equatable, Sendable {
+ case readyForReview
+ case needsDocumentContext
+ case needsStructuredData
+ case needsFieldDiscovery
+}
+
+public struct DocumentFormFillProposal: Codable, Equatable, Sendable {
+ public var fieldID: String
+ public var fieldLabel: String
+ public var proposedValue: String
+ public var sourceKey: String
+ public var confidence: Double
+ public var metadata: [String: String]
+
+ public init(
+ fieldID: String,
+ fieldLabel: String,
+ proposedValue: String,
+ sourceKey: String,
+ confidence: Double,
+ metadata: [String: String] = [:]
+ ) {
+ self.fieldID = fieldID
+ self.fieldLabel = fieldLabel
+ self.proposedValue = proposedValue
+ self.sourceKey = sourceKey
+ self.confidence = min(max(confidence, 0), 1)
+ self.metadata = metadata
+ }
+}
+
+public struct DocumentFormFillPlan: Codable, Equatable, Sendable {
+ public var status: DocumentFormFillPlanStatus
+ public var proposals: [DocumentFormFillProposal]
+ public var unmappedRequiredFieldIDs: [String]
+ public var unusedDataKeys: [String]
+ public var metadata: [String: String]
+
+ public init(
+ status: DocumentFormFillPlanStatus,
+ proposals: [DocumentFormFillProposal] = [],
+ unmappedRequiredFieldIDs: [String] = [],
+ unusedDataKeys: [String] = [],
+ metadata: [String: String] = [:]
+ ) {
+ self.status = status
+ self.proposals = proposals
+ self.unmappedRequiredFieldIDs = unmappedRequiredFieldIDs
+ self.unusedDataKeys = unusedDataKeys
+ self.metadata = metadata
+ }
+}
+
+public enum DocumentFormFillApprovalStatus: String, Codable, Equatable, Sendable {
+ case approved
+ case rejected
+ case partiallyApproved
+}
+
+public struct DocumentFormFillApproval: Codable, Equatable, Sendable {
+ public var id: String
+ public var traceID: String
+ public var status: DocumentFormFillApprovalStatus
+ public var approvedProposals: [DocumentFormFillProposal]
+ public var rejectedFieldIDs: [String]
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ traceID: String,
+ status: DocumentFormFillApprovalStatus,
+ approvedProposals: [DocumentFormFillProposal],
+ rejectedFieldIDs: [String] = [],
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.traceID = traceID
+ self.status = status
+ self.approvedProposals = approvedProposals
+ self.rejectedFieldIDs = rejectedFieldIDs
+ self.metadata = metadata
+ }
+}
+
+public struct DocumentFormFillPlanner: Sendable {
+ public init() {}
+
+ public func plan(
+ intent: TaskIntent,
+ definition: LocalAppTaskDefinition,
+ context: LocalAppTaskContext
+ ) -> DocumentFormFillPlan {
+ guard definition.taskType == "document_form_fill" else {
+ return DocumentFormFillPlan(
+ status: .needsDocumentContext,
+ metadata: ["reason": "unsupportedTaskType"]
+ )
+ }
+
+ guard hasDocumentContext(intent: intent, context: context) else {
+ return DocumentFormFillPlan(
+ status: .needsDocumentContext,
+ metadata: ["reason": "missingDocumentContext"]
+ )
+ }
+
+ let data = effectiveStructuredData(intent: intent, context: context)
+ guard !data.isEmpty else {
+ return DocumentFormFillPlan(
+ status: .needsStructuredData,
+ metadata: ["reason": "missingStructuredData"]
+ )
+ }
+
+ let fields = context.observedFormFields
+ guard !fields.isEmpty else {
+ return DocumentFormFillPlan(
+ status: .needsFieldDiscovery,
+ unusedDataKeys: data.keys.sorted(),
+ metadata: [
+ "reason": "missingObservedFields",
+ "dataKeyCount": String(data.count)
+ ]
+ )
+ }
+
+ var usedKeys: Set<String> = []
+ let proposals = fields.compactMap { field -> DocumentFormFillProposal? in
+ guard let match = bestDataMatch(for: field, data: data, usedKeys: usedKeys) else {
+ return nil
+ }
+ usedKeys.insert(match.key)
+ return DocumentFormFillProposal(
+ fieldID: field.id,
+ fieldLabel: field.label,
+ proposedValue: match.value,
+ sourceKey: match.key,
+ confidence: match.exact ? 0.94 : 0.72,
+ metadata: ["match": match.exact ? "exact" : "fuzzy"]
+ )
+ }
+
+ let mappedFieldIDs = Set(proposals.map(\.fieldID))
+ let unmappedRequired = fields
+ .filter { $0.isRequired && !mappedFieldIDs.contains($0.id) }
+ .map(\.id)
+ .sorted()
+ let unusedKeys = data.keys
+ .filter { !usedKeys.contains($0) }
+ .sorted()
+
+ return DocumentFormFillPlan(
+ status: .readyForReview,
+ proposals: proposals,
+ unmappedRequiredFieldIDs: unmappedRequired,
+ unusedDataKeys: unusedKeys,
+ metadata: [
+ "proposalCount": String(proposals.count),
+ "fieldCount": String(fields.count),
+ "dataKeyCount": String(data.count),
+ "requiresReview": "true"
+ ]
+ )
+ }
+
+ public func approval(
+ for plan: DocumentFormFillPlan,
+ traceID: String,
+ approvedFieldIDs: Set<String>
+ ) -> DocumentFormFillApproval {
+ let approved = plan.proposals.filter { approvedFieldIDs.contains($0.fieldID) }
+ let rejected = plan.proposals
+ .filter { !approvedFieldIDs.contains($0.fieldID) }
+ .map(\.fieldID)
+ .sorted()
+ let status: DocumentFormFillApprovalStatus
+ if approved.isEmpty {
+ status = .rejected
+ } else if rejected.isEmpty {
+ status = .approved
+ } else {
+ status = .partiallyApproved
+ }
+
+ return DocumentFormFillApproval(
+ id: "document-form-fill-approval-\(traceID)",
+ traceID: traceID,
+ status: status,
+ approvedProposals: approved,
+ rejectedFieldIDs: rejected,
+ metadata: [
+ "requiresUserApproval": "true",
+ "approvedProposalCount": String(approved.count),
+ "rejectedProposalCount": String(rejected.count)
+ ]
+ )
+ }
+
+ private func hasDocumentContext(
+ intent: TaskIntent,
+ context: LocalAppTaskContext
+ ) -> Bool {
+ intent.normalizedEntities["document"] != nil
+ || context.focusedWindowTitle != nil
+ || !context.attachedFileURLs.isEmpty
+ }
+
+ private func effectiveStructuredData(
+ intent: TaskIntent,
+ context: LocalAppTaskContext
+ ) -> [String: String] {
+ if !context.structuredData.isEmpty {
+ return context.structuredData
+ }
+
+ return intent.normalizedEntities
+ .filter { key, _ in
+ key != "document" && key != "dataSource"
+ }
+ }
+
+ private func bestDataMatch(
+ for field: LocalDocumentFormField,
+ data: [String: String],
+ usedKeys: Set<String>
+ ) -> (key: String, value: String, exact: Bool)? {
+ let fieldName = normalized(field.label)
+ let unused = data.filter { !usedKeys.contains($0.key) }
+
+ if let exact = unused.first(where: { normalized($0.key) == fieldName }) {
+ return (exact.key, exact.value, true)
+ }
+
+ if let fuzzy = unused.first(where: { item in
+ let key = normalized(item.key)
+ return fieldName.contains(key) || key.contains(fieldName)
+ }) {
+ return (fuzzy.key, fuzzy.value, false)
+ }
+
+ return nil
+ }
+
+ private func normalized(_ value: String) -> String {
+ LocalAppTaskIntentParser.normalizedPhrase(value)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
new file mode 100644
index 00000000..53bfc70d
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
@@ -0,0 +1,441 @@
+@preconcurrency import ApplicationServices
+import AppKit
+import DonkeyContracts
+import Foundation
+
+public enum LocalAppControlKind: String, Codable, Equatable, Sendable {
+ case button
+ case textField
+ case searchField
+ case checkbox
+ case menuItem
+ case group
+ case unknown
+}
+
+public struct LocalAppDiscoveredControl: Codable, Equatable, Sendable {
+ public var id: String
+ public var kind: LocalAppControlKind
+ public var role: String?
+ public var label: String
+ public var valueSummary: String?
+ public var frame: WindowTargetBounds?
+ public var isEnabled: Bool
+ public var actions: [String]
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ kind: LocalAppControlKind,
+ role: String? = nil,
+ label: String,
+ valueSummary: String? = nil,
+ frame: WindowTargetBounds? = nil,
+ isEnabled: Bool = true,
+ actions: [String] = [],
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.kind = kind
+ self.role = role
+ self.label = label
+ self.valueSummary = valueSummary
+ self.frame = frame
+ self.isEnabled = isEnabled
+ self.actions = actions
+ self.metadata = metadata
+ }
+}
+
+public struct LocalAppAccessibilityControlIndex: Codable, Equatable, Sendable {
+ public var controls: [LocalAppDiscoveredControl]
+ public var visibleText: String
+ public var metadata: [String: String]
+
+ public init(
+ controls: [LocalAppDiscoveredControl],
+ visibleText: String,
+ metadata: [String: String] = [:]
+ ) {
+ self.controls = controls
+ self.visibleText = visibleText
+ self.metadata = metadata
+ }
+
+ public func firstControl(
+ matching controlID: String,
+ acceptedKinds: Set<LocalAppControlKind> = []
+ ) -> LocalAppDiscoveredControl? {
+ let normalizedID = LocalAppTaskIntentParser.normalizedPhrase(controlID)
+ return controls.first { control in
+ let normalizedLabel = LocalAppTaskIntentParser.normalizedPhrase(control.label)
+ let normalizedMetadataID = control.metadata["controlID"]
+ .map(LocalAppTaskIntentParser.normalizedPhrase)
+ let kindMatches = acceptedKinds.isEmpty || acceptedKinds.contains(control.kind)
+ return kindMatches
+ && (
+ normalizedLabel.contains(normalizedID)
+ || normalizedMetadataID == normalizedID
+ || LocalAppTaskIntentParser.normalizedPhrase(control.id) == normalizedID
+ )
+ }
+ }
+}
+
+public struct LocalAppAccessibilityControlDiscovery: Sendable {
+ public init() {}
+
+ public func discover(in snapshot: MacAccessibilitySnapshot) -> LocalAppAccessibilityControlIndex {
+ var controls: [LocalAppDiscoveredControl] = []
+ var visibleText: [String] = []
+ visit(snapshot.root, controls: &controls, visibleText: &visibleText)
+ return LocalAppAccessibilityControlIndex(
+ controls: controls,
+ visibleText: visibleText.joined(separator: " "),
+ metadata: [
+ "observer": "local-app-accessibility-control-discovery",
+ "target.windowID": String(snapshot.target.windowID),
+ "target.processID": String(snapshot.target.processID),
+ "controlCount": String(controls.count),
+ "treeTruncated": String(snapshot.isTreeTruncated)
+ ]
+ )
+ }
+
+ public func observedFormFields(in snapshot: MacAccessibilitySnapshot) -> [LocalDocumentFormField] {
+ discover(in: snapshot).controls
+ .filter { [.textField, .searchField, .checkbox].contains($0.kind) }
+ .map { control in
+ LocalDocumentFormField(
+ id: control.id,
+ label: control.label,
+ isRequired: control.metadata["required"] == "true",
+ currentValue: control.valueSummary,
+ metadata: control.metadata.merging([
+ "controlKind": control.kind.rawValue,
+ "accessibility.role": control.role ?? "",
+ "accessibility.actions": control.actions.joined(separator: ",")
+ ]) { current, _ in current }
+ )
+ }
+ }
+
+ private func visit(
+ _ node: MacAccessibilitySnapshotNode,
+ controls: inout [LocalAppDiscoveredControl],
+ visibleText: inout [String]
+ ) {
+ let label = bestLabel(for: node)
+ if let label {
+ visibleText.append(label)
+ }
+
+ let kind = controlKind(for: node)
+ if kind != .unknown, let label {
+ controls.append(
+ LocalAppDiscoveredControl(
+ id: node.nodeID,
+ kind: kind,
+ role: node.role,
+ label: label,
+ valueSummary: node.valueSummary,
+ frame: node.frame,
+ isEnabled: node.isEnabled ?? true,
+ actions: node.actions,
+ metadata: [
+ "accessibility.nodeID": node.nodeID,
+ "controlID": inferredControlID(label: label, kind: kind)
+ ]
+ )
+ )
+ }
+
+ for child in node.children {
+ visit(child, controls: &controls, visibleText: &visibleText)
+ }
+ }
+
+ private func bestLabel(for node: MacAccessibilitySnapshotNode) -> String? {
+ [node.label, node.title, node.valueSummary, node.role]
+ .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .first { !$0.isEmpty }
+ }
+
+ private func controlKind(for node: MacAccessibilitySnapshotNode) -> LocalAppControlKind {
+ let role = node.role ?? ""
+ if role == "AXButton" { return .button }
+ if role == "AXCheckBox" { return .checkbox }
+ if role == "AXMenuItem" { return .menuItem }
+ if role == "AXSearchField" { return .searchField }
+ if role == "AXTextField" || role == "AXTextArea" || role == "AXComboBox" {
+ return .textField
+ }
+ if role == "AXGroup" { return .group }
+ if node.actions.contains("AXPress") { return .button }
+ return .unknown
+ }
+
+ private func inferredControlID(label: String, kind: LocalAppControlKind) -> String {
+ let normalized = LocalAppTaskIntentParser.normalizedPhrase(label)
+ if kind == .searchField || normalized.contains("search") {
+ return "search"
+ }
+ return normalized.replacingOccurrences(of: " ", with: "-")
+ }
+}
+
+public struct LocalAppAccessibilityActionPlanner: Sendable {
+ public init() {}
+
+ public func commands(
+ for intent: TaskIntent,
+ definition: LocalAppTaskDefinition,
+ index: LocalAppAccessibilityControlIndex,
+ issuedAt: RunTraceTimestamp
+ ) -> [ActionEngineCommand] {
+ let adapter = LocalAppTaskAdapter(definition: definition)
+ return definition.workflowSteps.compactMap { step in
+ switch step.role {
+ case .focusControl:
+ guard let controlID = step.metadata["controlID"],
+ let control = index.firstControl(
+ matching: controlID,
+ acceptedKinds: [.searchField, .textField, .button]
+ )
+ else {
+ return nil
+ }
+ return command(
+ id: "\(intent.intentID)-ax-\(step.id)",
+ traceID: intent.metadata["traceID"] ?? intent.intentID,
+ targetID: adapter.targetID,
+ issuedAt: issuedAt,
+ kind: .tap,
+ control: control,
+ definition: definition,
+ step: step,
+ metadata: [
+ "accessibility.action": "AXPress",
+ "accessibility.nodeID": control.id,
+ "inputStrategy": "accessibility"
+ ]
+ )
+ case .enterText:
+ let entityName = step.metadata["entityName"] ?? definition.verificationEntityName
+ guard let entityName,
+ let text = intent.normalizedEntities[entityName],
+ let control = index.firstControl(
+ matching: step.metadata["controlID"] ?? "search",
+ acceptedKinds: [.searchField, .textField]
+ )
+ else {
+ return nil
+ }
+ return command(
+ id: "\(intent.intentID)-ax-\(step.id)",
+ traceID: intent.metadata["traceID"] ?? intent.intentID,
+ targetID: adapter.targetID,
+ issuedAt: issuedAt,
+ kind: .key,
+ control: control,
+ definition: definition,
+ step: step,
+ metadata: [
+ "accessibility.action": "AXSetValue",
+ "accessibility.nodeID": control.id,
+ "accessibility.value": text,
+ "inputStrategy": "accessibility",
+ "text": text
+ ]
+ )
+ case .submit:
+ return nil
+ case .parseIntent, .launchOrFocusApp, .observeApp, .verifyResult, .custom:
+ return nil
+ }
+ }
+ }
+
+ public func fillCommands(
+ approval: DocumentFormFillApproval,
+ definition: LocalAppTaskDefinition,
+ issuedAt: RunTraceTimestamp
+ ) -> [ActionEngineCommand] {
+ let adapter = LocalAppTaskAdapter(definition: definition)
+ return approval.approvedProposals.enumerated().map { index, proposal in
+ ActionEngineCommand(
+ id: "\(approval.id)-fill-\(index)",
+ traceID: approval.traceID,
+ targetID: adapter.targetID,
+ kind: .key,
+ issuedAt: Self.timestamp(issuedAt, advancedByMilliseconds: Double(index) * 60),
+ key: proposal.proposedValue,
+ metadata: [
+ "taskType": definition.taskType,
+ "workflowStepRole": "enterText",
+ "inputStrategy": "accessibility",
+ "accessibility.action": "AXSetValue",
+ "accessibility.nodeID": proposal.fieldID,
+ "accessibility.value": proposal.proposedValue,
+ "documentFormFill.approvalID": approval.id,
+ "documentFormFill.sourceKey": proposal.sourceKey,
+ "documentFormFill.fieldLabel": proposal.fieldLabel
+ ]
+ )
+ }
+ }
+
+ private func command(
+ id: String,
+ traceID: String,
+ targetID: String,
+ issuedAt: RunTraceTimestamp,
+ kind: ActionEngineCommandKind,
+ control: LocalAppDiscoveredControl,
+ definition: LocalAppTaskDefinition,
+ step: LocalAppTaskWorkflowStepDefinition,
+ metadata: [String: String]
+ ) -> ActionEngineCommand {
+ ActionEngineCommand(
+ id: id,
+ traceID: traceID,
+ targetID: targetID,
+ kind: kind,
+ issuedAt: issuedAt,
+ targetBounds: control.frame.map {
+ HotLoopRect(
+ x: $0.x,
+ y: $0.y,
+ width: $0.width,
+ height: $0.height,
+ space: .screen
+ )
+ },
+ metadata: step.metadata.merging(metadata) { current, _ in current }
+ .merging([
+ "taskType": definition.taskType,
+ "bundleIdentifier": definition.targetApp.bundleIdentifier ?? "",
+ "workflowStepID": step.id,
+ "workflowStepRole": step.role.rawValue
+ ]) { current, _ in current }
+ )
+ }
+
+ private static func timestamp(
+ _ timestamp: RunTraceTimestamp,
+ advancedByMilliseconds milliseconds: Double
+ ) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: timestamp.wallClock.addingTimeInterval(milliseconds / 1_000),
+ monotonicUptimeNanoseconds: timestamp.monotonicUptimeNanoseconds + UInt64(milliseconds * 1_000_000)
+ )
+ }
+}
+
+public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackend {
+ public init() {}
+
+ public func execute(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {
+ await MainActor.run {
+ executeOnMainActor(command)
+ }
+ }
+
+ @MainActor
+ private func executeOnMainActor(_ command: ActionEngineCommand) -> ActionEngineInputBackendResult {
+ guard AXIsProcessTrusted() else {
+ return result(command, executed: false, reason: "accessibilityNotTrusted")
+ }
+ guard let nodeID = command.metadata["accessibility.nodeID"],
+ let action = command.metadata["accessibility.action"]
+ else {
+ return result(command, executed: false, reason: "missingAccessibilityTarget")
+ }
+ guard let bundleIdentifier = command.metadata["bundleIdentifier"],
+ let application = NSWorkspace.shared.frontmostApplication,
+ application.bundleIdentifier == bundleIdentifier
+ else {
+ return result(command, executed: false, reason: "targetAppNotFrontmost")
+ }
+
+ let appElement = AXUIElementCreateApplication(application.processIdentifier)
+ guard let element = resolveElement(nodeID: nodeID, application: appElement) else {
+ return result(command, executed: false, reason: "accessibilityNodeNotFound")
+ }
+
+ switch action {
+ case "AXPress":
+ let error = AXUIElementPerformAction(element, kAXPressAction as CFString)
+ return result(command, executed: error == .success, reason: String(describing: error))
+ case "AXSetValue":
+ guard let value = command.metadata["accessibility.value"] ?? command.key else {
+ return result(command, executed: false, reason: "missingAccessibilityValue")
+ }
+ let error = AXUIElementSetAttributeValue(
+ element,
+ kAXValueAttribute as CFString,
+ value as CFTypeRef
+ )
+ return result(command, executed: error == .success, reason: String(describing: error))
+ default:
+ return result(command, executed: false, reason: "unsupportedAccessibilityAction")
+ }
+ }
+
+ @MainActor
+ private func resolveElement(nodeID: String, application: AXUIElement) -> AXUIElement? {
+ let indexes = nodeID
+ .split(separator: ".")
+ .dropFirst()
+ .compactMap { Int($0).map { $0 - 1 } }
+ let roots = windows(from: application)
+ let root = roots.first ?? application
+ return indexes.reduce(Optional(root)) { element, index in
+ guard let element else { return nil }
+ let children = children(from: element)
+ guard children.indices.contains(index) else { return nil }
+ return children[index]
+ }
+ }
+
+ @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 children(from element: AXUIElement) -> [AXUIElement] {
+ var value: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(
+ element,
+ kAXChildrenAttribute as CFString,
+ &value
+ ) == .success else {
+ return []
+ }
+ return value as? [AXUIElement] ?? []
+ }
+
+ private func result(
+ _ command: ActionEngineCommand,
+ executed: Bool,
+ reason: String
+ ) -> ActionEngineInputBackendResult {
+ ActionEngineInputBackendResult(
+ executed: executed,
+ completedAt: command.issuedAt,
+ metadata: [
+ "liveInputBackend": "mac-accessibility",
+ "accessibility.result": reason
+ ]
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskContext.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskContext.swift
new file mode 100644
index 00000000..2a8b7a0e
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskContext.swift
@@ -0,0 +1,162 @@
+@preconcurrency import ApplicationServices
+import AppKit
+import DonkeyContracts
+import Foundation
+
+public struct LocalDocumentFormField: Codable, Equatable, Sendable {
+ public var id: String
+ public var label: String
+ public var isRequired: Bool
+ public var currentValue: String?
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ label: String,
+ isRequired: Bool = false,
+ currentValue: String? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.label = label
+ self.isRequired = isRequired
+ self.currentValue = currentValue
+ self.metadata = metadata
+ }
+}
+
+public struct LocalAppTaskContext: Equatable, Sendable {
+ public var focusedAppName: String?
+ public var focusedBundleIdentifier: String?
+ public var focusedWindowTitle: String?
+ public var focusedWindowID: UInt32?
+ public var clipboardText: String?
+ public var attachedFileURLs: [URL]
+ public var structuredData: [String: String]
+ public var observedFormFields: [LocalDocumentFormField]
+ public var metadata: [String: String]
+
+ public init(
+ focusedAppName: String? = nil,
+ focusedBundleIdentifier: String? = nil,
+ focusedWindowTitle: String? = nil,
+ focusedWindowID: UInt32? = nil,
+ clipboardText: String? = nil,
+ attachedFileURLs: [URL] = [],
+ structuredData: [String: String] = [:],
+ observedFormFields: [LocalDocumentFormField] = [],
+ metadata: [String: String] = [:]
+ ) {
+ self.focusedAppName = focusedAppName
+ self.focusedBundleIdentifier = focusedBundleIdentifier
+ self.focusedWindowTitle = focusedWindowTitle
+ self.focusedWindowID = focusedWindowID
+ self.clipboardText = clipboardText
+ self.attachedFileURLs = attachedFileURLs
+ self.structuredData = structuredData
+ self.observedFormFields = observedFormFields
+ self.metadata = metadata
+ }
+}
+
+public protocol LocalAppTaskContextProviding: Sendable {
+ @MainActor
+ func snapshot() -> LocalAppTaskContext
+}
+
+public struct StaticLocalAppTaskContextProvider: LocalAppTaskContextProviding {
+ public var context: LocalAppTaskContext
+
+ public init(context: LocalAppTaskContext) {
+ self.context = context
+ }
+
+ @MainActor
+ public func snapshot() -> LocalAppTaskContext {
+ context
+ }
+}
+
+public struct MacLocalAppTaskContextProvider: LocalAppTaskContextProviding {
+ public init() {}
+
+ @MainActor
+ public func snapshot() -> LocalAppTaskContext {
+ let focusedWindow = try? MacWindowResolver().selectTarget()
+ let clipboardText = NSPasteboard.general.string(forType: .string)
+ let structuredData = Self.structuredData(from: clipboardText)
+ let observedFormFields = Self.observedFormFields(from: focusedWindow)
+
+ return LocalAppTaskContext(
+ focusedAppName: focusedWindow?.appName,
+ focusedBundleIdentifier: focusedWindow?.bundleIdentifier,
+ focusedWindowTitle: focusedWindow?.title,
+ focusedWindowID: focusedWindow?.windowID,
+ clipboardText: clipboardText,
+ structuredData: structuredData,
+ observedFormFields: observedFormFields,
+ metadata: [
+ "provider": "mac-local-app-task-context",
+ "clipboard.hasText": String(clipboardText?.isEmpty == false),
+ "focusedWindow.resolved": String(focusedWindow != nil),
+ "observedFormFieldCount": String(observedFormFields.count)
+ ]
+ )
+ }
+
+ @MainActor
+ private static func observedFormFields(
+ from focusedWindow: MacWindowTargetCandidate?
+ ) -> [LocalDocumentFormField] {
+ guard let focusedWindow,
+ AXIsProcessTrusted()
+ else {
+ return []
+ }
+
+ let capturer = ApplicationServicesMacAccessibilitySnapshotCapturer()
+ guard let tree = try? capturer.captureTree(
+ target: focusedWindow,
+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6, maxChildrenPerNode: 80, maxTotalNodes: 500)
+ ) else {
+ return []
+ }
+
+ let snapshot = MacAccessibilitySnapshot(
+ target: focusedWindow,
+ limits: MacAccessibilitySnapshotLimits(maxDepth: 6, maxChildrenPerNode: 80, maxTotalNodes: 500),
+ root: tree.root,
+ totalNodeCount: tree.totalNodeCount,
+ isTreeTruncated: tree.isTreeTruncated
+ )
+ return LocalAppAccessibilityControlDiscovery().observedFormFields(in: snapshot)
+ }
+
+ private static func structuredData(from text: String?) -> [String: String] {
+ guard let text, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
+ return [:]
+ }
+
+ if let jsonData = text.data(using: .utf8),
+ let object = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] {
+ return object.reduce(into: [:]) { result, item in
+ if let value = item.value as? String {
+ result[item.key] = value
+ } else if let value = item.value as? NSNumber {
+ result[item.key] = value.stringValue
+ }
+ }
+ }
+
+ return text
+ .split(whereSeparator: \.isNewline)
+ .reduce(into: [:]) { result, line in
+ let parts = line.split(separator: ":", maxSplits: 1)
+ guard parts.count == 2 else { return }
+ let key = parts[0].trimmingCharacters(in: .whitespacesAndNewlines)
+ let value = parts[1].trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !key.isEmpty, !value.isEmpty else { return }
+ result[key] = value
+ }
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift
new file mode 100644
index 00000000..cee5c8cd
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift
@@ -0,0 +1,100 @@
+import DonkeyContracts
+import Foundation
+
+public enum LocalAppTaskDefinitionLoaderError: Error, Equatable, Sendable {
+ case unsupportedFileExtension(String)
+ case unreadableDirectory(URL)
+ case decodeFailed(URL, String)
+}
+
+public struct LocalAppTaskDefinitionLoader: Sendable {
+ public var decoder: JSONDecoder
+
+ public init(decoder: JSONDecoder = JSONDecoder()) {
+ self.decoder = decoder
+ }
+
+ public static var defaultDirectoryURL: URL {
+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("Donkey", isDirectory: true)
+ .appendingPathComponent("TaskDefinitions", isDirectory: true)
+ }
+
+ public func load(from url: URL) throws -> [LocalAppTaskDefinition] {
+ switch url.pathExtension.lowercased() {
+ case "json":
+ return try loadJSON(from: url)
+ case "jsonl":
+ return try loadJSONLines(from: url)
+ default:
+ throw LocalAppTaskDefinitionLoaderError.unsupportedFileExtension(url.pathExtension)
+ }
+ }
+
+ public func loadDirectory(_ directoryURL: URL) throws -> [LocalAppTaskDefinition] {
+ guard let fileURLs = FileManager.default.enumerator(
+ at: directoryURL,
+ includingPropertiesForKeys: [.isRegularFileKey],
+ options: [.skipsHiddenFiles]
+ ) else {
+ throw LocalAppTaskDefinitionLoaderError.unreadableDirectory(directoryURL)
+ }
+
+ var definitions: [LocalAppTaskDefinition] = []
+ for case let fileURL as URL in fileURLs {
+ guard ["json", "jsonl"].contains(fileURL.pathExtension.lowercased()) else {
+ continue
+ }
+ definitions.append(contentsOf: try load(from: fileURL))
+ }
+ return definitions
+ }
+
+ public func mergedWithBuiltIns(from directoryURL: URL) throws -> [LocalAppTaskDefinition] {
+ BuiltInLocalAppTaskDefinitions.defaults + (try loadDirectory(directoryURL))
+ }
+
+ public func defaultDefinitions() -> [LocalAppTaskDefinition] {
+ (try? mergedWithBuiltIns(from: Self.defaultDirectoryURL))
+ ?? BuiltInLocalAppTaskDefinitions.defaults
+ }
+
+ private func loadJSON(from url: URL) throws -> [LocalAppTaskDefinition] {
+ do {
+ let data = try Data(contentsOf: url)
+ if let array = try? decoder.decode([LocalAppTaskDefinition].self, from: data) {
+ return array
+ }
+ return [try decoder.decode(LocalAppTaskDefinition.self, from: data)]
+ } catch {
+ throw LocalAppTaskDefinitionLoaderError.decodeFailed(url, String(describing: error))
+ }
+ }
+
+ private func loadJSONLines(from url: URL) throws -> [LocalAppTaskDefinition] {
+ do {
+ let text = try String(contentsOf: url, encoding: .utf8)
+ return try text
+ .split(separator: "\n")
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ .map { line in
+ try decoder.decode(LocalAppTaskDefinition.self, from: Data(line.utf8))
+ }
+ } catch {
+ throw LocalAppTaskDefinitionLoaderError.decodeFailed(url, String(describing: error))
+ }
+ }
+}
+
+public extension LocalAppTaskCatalog {
+ static func defaultLocal(
+ availabilityProvider: any LocalAppAvailabilityProviding = MacLocalAppAvailabilityProvider(),
+ loader: LocalAppTaskDefinitionLoader = LocalAppTaskDefinitionLoader()
+ ) -> LocalAppTaskCatalog {
+ LocalAppTaskCatalog(
+ taskDefinitions: loader.defaultDefinitions(),
+ availabilityProvider: availabilityProvider
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
index 7393a9b6..66dbfcc0 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
@@ -20,6 +20,7 @@ public struct LocalAppTaskLiveRunResult: Equatable, Sendable {
public var initialPlan: LocalAppTaskDryRunPlan?
public var finalPlan: LocalAppTaskDryRunPlan?
public var observation: LocalAppTaskObservation?
+ public var documentFormFillPlan: DocumentFormFillPlan?
public var actionTraces: [ActionEngineCommandTrace]
public var metadata: [String: String]
@@ -31,6 +32,7 @@ public struct LocalAppTaskLiveRunResult: Equatable, Sendable {
initialPlan: LocalAppTaskDryRunPlan? = nil,
finalPlan: LocalAppTaskDryRunPlan? = nil,
observation: LocalAppTaskObservation? = nil,
+ documentFormFillPlan: DocumentFormFillPlan? = nil,
actionTraces: [ActionEngineCommandTrace] = [],
metadata: [String: String] = [:]
) {
@@ -41,6 +43,7 @@ public struct LocalAppTaskLiveRunResult: Equatable, Sendable {
self.initialPlan = initialPlan
self.finalPlan = finalPlan
self.observation = observation
+ self.documentFormFillPlan = documentFormFillPlan
self.actionTraces = actionTraces
self.metadata = metadata
}
@@ -62,17 +65,23 @@ public struct LocalAppTaskLiveRunner: Sendable {
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 init(
- catalog: LocalAppTaskCatalog = LocalAppTaskCatalog(taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults),
+ catalog: LocalAppTaskCatalog = .defaultLocal(),
appController: any LocalAppTaskAppControlling = MacLocalAppTaskController(),
+ contextProvider: any LocalAppTaskContextProviding = MacLocalAppTaskContextProvider(),
+ documentFormFillPlanner: DocumentFormFillPlanner = DocumentFormFillPlanner(),
actionEngineFactory: @escaping ActionEngineFactory = Self.defaultActionEngine(for:),
permissionPolicy: ToolCallPolicy = ToolCallPolicy(deniedCapabilities: [])
) {
self.catalog = catalog
self.appController = appController
+ self.contextProvider = contextProvider
+ self.documentFormFillPlanner = documentFormFillPlanner
self.actionEngineFactory = actionEngineFactory
self.permissionPolicy = permissionPolicy
}
@@ -119,6 +128,46 @@ public struct LocalAppTaskLiveRunner: Sendable {
intent.metadata["traceID"] = traceID
let adapter = catalog.adapter(for: definition)
+ if definition.metadata["guardedLiveDefault"] == "reviewOnly" {
+ let context = await contextProvider.snapshot()
+ 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 initialPlan = adapter.dryRunPlan(for: intent, observation: observation)
+ return LocalAppTaskLiveRunResult(
+ command: command,
+ traceID: traceID,
+ status: .needsUserReview,
+ resolution: resolution,
+ initialPlan: initialPlan,
+ finalPlan: initialPlan,
+ observation: observation,
+ documentFormFillPlan: documentPlan,
+ metadata: metadata.merging([
+ "reason": "reviewOnlyTask",
+ "documentFormFillPlan.status": documentPlan.status.rawValue,
+ "documentFormFillPlan.proposalCount": String(documentPlan.proposals.count)
+ ]) { current, _ in current }
+ )
+ }
+
let launchObservation = await appController.launchOrFocus(
definition: definition,
availability: availability
@@ -136,12 +185,38 @@ public struct LocalAppTaskLiveRunner: Sendable {
)
}
- let engine = actionEngineFactory(definition)
var actionTraces: [ActionEngineCommandTrace] = []
+ let accessibilityCommands = await accessibilityCommandTemplates(
+ intent: intent,
+ definition: definition
+ )
+ if !accessibilityCommands.isEmpty {
+ let accessibilityEngine = Self.accessibilityActionEngine(for: definition)
+ for (index, actionCommand) in accessibilityCommands.enumerated() {
+ let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 60))
+ let trace = await accessibilityEngine.handle(
+ spacedCommand,
+ permissionPolicy: permissionPolicy
+ )
+ actionTraces.append(trace)
+ guard trace.executed || trace.decision == .projectedDryRun else {
+ break
+ }
+ }
+ }
+
+ let engine = actionEngineFactory(definition)
+ let accessibilityHandledStepIDs: Set<String> = Set(actionTraces.compactMap { trace -> String? in
+ guard trace.executed || trace.decision == ActionEngineCommandDecision.projectedDryRun else { return nil }
+ return trace.command.metadata["workflowStepID"]
+ })
let commands = adapter.guardedKeyboardCommandTemplates(
for: intent,
issuedAt: Self.now()
- )
+ ).filter { command in
+ guard let workflowStepID = command.metadata["workflowStepID"] else { return true }
+ return !accessibilityHandledStepIDs.contains(workflowStepID)
+ }
for (index, actionCommand) in commands.enumerated() {
let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 40))
@@ -151,7 +226,7 @@ public struct LocalAppTaskLiveRunner: Sendable {
)
actionTraces.append(trace)
- guard trace.executed || trace.decision == .projectedDryRun else {
+ guard trace.executed || trace.decision == ActionEngineCommandDecision.projectedDryRun else {
let finalObservation = await appController.observe(definition: definition)
let finalPlan = adapter.dryRunPlan(for: intent, observation: finalObservation)
return LocalAppTaskLiveRunResult(
@@ -198,6 +273,17 @@ public struct LocalAppTaskLiveRunner: Sendable {
)
}
+ 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,
@@ -225,6 +311,41 @@ public struct LocalAppTaskLiveRunner: Sendable {
)
}
+ @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 status(for terminalState: LocalAppTaskTerminalState) -> LocalAppTaskLiveRunStatus {
switch terminalState {
case .completed:
@@ -289,7 +410,8 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
public func observe(definition: LocalAppTaskDefinition) async -> LocalAppTaskObservation {
let runningApplication = runningApplication(for: definition.targetApp)
let isFocused = NSWorkspace.shared.frontmostApplication?.bundleIdentifier == definition.targetApp.bundleIdentifier
- let visibleText = accessibilityVisibleText(for: runningApplication)
+ let accessibilityIndex = accessibilityControlIndex(for: definition, runningApplication: runningApplication)
+ let visibleText = accessibilityIndex?.visibleText ?? accessibilityVisibleText(for: runningApplication)
let verificationKey = definition.metadata["verificationTextKey"]
?? definition.verificationEntityName
?? "visibleText"
@@ -300,7 +422,8 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
else {
return nil
}
- return (controlID, step.metadata["key"] != nil || visibleText != nil)
+ let discovered = accessibilityIndex?.firstControl(matching: controlID) != nil
+ return (controlID, discovered || step.metadata["key"] != nil || visibleText != nil)
}
)
@@ -315,14 +438,46 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
appIsFocused: isFocused,
availableControls: controls,
visibleText: textValues,
- confidence: visibleText == nil ? 0.4 : 0.75,
+ confidence: accessibilityIndex == nil ? (visibleText == nil ? 0.4 : 0.75) : 0.86,
metadata: [
"observer": "mac-local-app-controller",
- "accessibilityTrusted": String(AXIsProcessTrusted())
+ "accessibilityTrusted": String(AXIsProcessTrusted()),
+ "accessibilityControlDiscovery": String(accessibilityIndex != nil),
+ "accessibilityControlCount": accessibilityIndex?.metadata["controlCount"] ?? "0"
]
)
}
+ @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 }
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
index 600e9bb4..8097661a 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
@@ -272,7 +272,7 @@ public final class MacAccessibilitySnapshotCaptureService {
}
}
-private final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {
+final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {
func trustStatus() -> MacAccessibilityTrustStatus {
AXIsProcessTrusted() ? .trusted : .notTrusted
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift
new file mode 100644
index 00000000..c1cf432b
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift
@@ -0,0 +1,185 @@
+import DonkeyContracts
+import Foundation
+
+public struct ScreenshotSegmentationRequest: Equatable, Sendable {
+ public var traceID: String
+ public var frameID: String
+ public var targetID: String
+ public var cropID: String
+ public var cropBounds: HotLoopRect
+ public var pixelSize: HotLoopSize
+ public var metadata: [String: String]
+
+ public init(
+ traceID: String,
+ frameID: String,
+ targetID: String,
+ cropID: String,
+ cropBounds: HotLoopRect,
+ pixelSize: HotLoopSize,
+ metadata: [String: String] = [:]
+ ) {
+ self.traceID = traceID
+ self.frameID = frameID
+ self.targetID = targetID
+ self.cropID = cropID
+ self.cropBounds = cropBounds
+ self.pixelSize = pixelSize
+ self.metadata = metadata
+ }
+}
+
+public struct ScreenshotSegmentationMask: Codable, Equatable, Sendable {
+ public var id: String
+ public var label: String
+ public var bounds: HotLoopRect
+ public var confidence: Double
+ public var pointCount: Int
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ label: String,
+ bounds: HotLoopRect,
+ confidence: Double,
+ pointCount: Int = 0,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.label = label
+ self.bounds = bounds
+ self.confidence = min(max(confidence, 0), 1)
+ self.pointCount = max(0, pointCount)
+ self.metadata = metadata
+ }
+}
+
+public struct ScreenshotSegmentationBackendResult: Equatable, Sendable {
+ public var masks: [ScreenshotSegmentationMask]
+ public var preprocessMS: Double
+ public var modelInferenceMS: Double
+ public var metadata: [String: String]
+
+ public init(
+ masks: [ScreenshotSegmentationMask],
+ preprocessMS: Double,
+ modelInferenceMS: Double,
+ metadata: [String: String] = [:]
+ ) {
+ self.masks = masks
+ self.preprocessMS = max(0, preprocessMS)
+ self.modelInferenceMS = max(0, modelInferenceMS)
+ self.metadata = metadata
+ }
+}
+
+public struct ScreenshotSegmentationResult: Equatable, Sendable {
+ public var request: ScreenshotSegmentationRequest
+ public var model: OffTheShelfVisionModelCandidate
+ public var signal: RecordedOffTheShelfVisionSignal
+ public var metadata: [String: String]
+
+ public init(
+ request: ScreenshotSegmentationRequest,
+ model: OffTheShelfVisionModelCandidate,
+ signal: RecordedOffTheShelfVisionSignal,
+ metadata: [String: String]
+ ) {
+ self.request = request
+ self.model = model
+ self.signal = signal
+ self.metadata = metadata
+ }
+}
+
+public protocol ScreenshotSegmentationBackend: Sendable {
+ func segment(
+ request: ScreenshotSegmentationRequest,
+ model: OffTheShelfVisionModelCandidate
+ ) async throws -> ScreenshotSegmentationBackendResult
+}
+
+public enum ScreenshotSegmentationRunnerError: Error, Equatable, Sendable {
+ case noModelCandidate
+ case backendUnavailable(String)
+}
+
+public struct UnavailableScreenshotSegmentationBackend: ScreenshotSegmentationBackend {
+ public init() {}
+
+ public func segment(
+ request: ScreenshotSegmentationRequest,
+ model: OffTheShelfVisionModelCandidate
+ ) async throws -> ScreenshotSegmentationBackendResult {
+ throw ScreenshotSegmentationRunnerError.backendUnavailable(model.id)
+ }
+}
+
+public struct YOLOScreenshotSegmentationRunner: Sendable {
+ public var model: OffTheShelfVisionModelCandidate
+ public var backend: any ScreenshotSegmentationBackend
+ public var now: @Sendable () -> RunTraceTimestamp
+
+ public init(
+ model: OffTheShelfVisionModelCandidate = OffTheShelfVisionModelCatalog.yolo26NanoScreenshotSegmentation,
+ backend: any ScreenshotSegmentationBackend = UnavailableScreenshotSegmentationBackend(),
+ now: @escaping @Sendable () -> RunTraceTimestamp = Self.defaultNow
+ ) {
+ self.model = model
+ self.backend = backend
+ self.now = now
+ }
+
+ public func run(_ request: ScreenshotSegmentationRequest) async throws -> ScreenshotSegmentationResult {
+ let startedAt = now()
+ let backendResult = try await backend.segment(request: request, model: model)
+ let completedAt = now()
+ let totalMS = startedAt.milliseconds(until: completedAt) ?? 0
+ let adapterOverheadMS = max(0, totalMS - backendResult.preprocessMS - backendResult.modelInferenceMS)
+ let signal = RecordedOffTheShelfVisionSignal(
+ id: "segmentation-\(request.frameID)-\(request.cropID)",
+ kind: .segmentation,
+ componentID: model.componentID,
+ modelID: model.id,
+ cropID: request.cropID,
+ confidence: backendResult.masks.map(\.confidence).max() ?? 0,
+ observations: backendResult.masks.map { mask in
+ RecordedOffTheShelfVisionObservation(
+ id: mask.id,
+ label: mask.label,
+ bounds: mask.bounds,
+ confidence: mask.confidence,
+ metadata: mask.metadata.merging([
+ "mask.pointCount": String(mask.pointCount)
+ ]) { current, _ in current }
+ )
+ },
+ preprocessMS: backendResult.preprocessMS,
+ modelInferenceMS: backendResult.modelInferenceMS,
+ adapterOverheadMS: adapterOverheadMS,
+ metadata: [
+ "runner": "yolo-screenshot-segmentation",
+ "modelFamily": model.family,
+ "modelName": model.modelName,
+ "inputSource": model.preferredInputSource.rawValue,
+ "liveDefault": model.metadata["liveDefault"] ?? "false",
+ "requiresLocalBenchmark": model.metadata["requiresLocalBenchmark"] ?? "true",
+ "latency.totalMS": String(totalMS)
+ ].merging(backendResult.metadata) { current, _ in current }
+ )
+
+ return ScreenshotSegmentationResult(
+ request: request,
+ model: model,
+ signal: signal,
+ metadata: RecordedOffTheShelfVisionMetadataCodec.encode(signals: [signal])
+ )
+ }
+
+ public static func defaultNow() -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(),
+ monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)
+ )
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index 58e131ff..c06592d9 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -127,6 +127,39 @@ struct AIHarnessAdapterTests {
#expect(selected.modelID == "openai/whisper-large-v3-turbo")
}
+ @Test
+ func localVoiceTranscriptionAdapterReturnsTranscriptForCommandParser() async {
+ let adapter = LocalVoiceTranscriptionAdapter(
+ runtime: FakeVoiceRuntime(
+ transcript: LocalVoiceTranscript(
+ text: "play Coldplay",
+ language: "en",
+ confidence: 0.91,
+ segments: ["play Coldplay"]
+ )
+ ),
+ now: fixedClock([10, 42])
+ )
+ let result = await adapter.transcribe(
+ LocalVoiceTranscriptionRequest(
+ audio: LocalVoiceAudioBuffer(
+ id: "audio-1",
+ durationMS: 1_200,
+ data: Data([0, 1, 2])
+ ),
+ sourceTraceID: "trace-voice"
+ )
+ )
+
+ #expect(result.transcript?.text == "play Coldplay")
+ #expect(result.trace.status == .completed)
+ #expect(result.trace.role == .voiceTranscription)
+ #expect(result.trace.modelID == "nvidia/parakeet-tdt-0.6b-v3")
+ #expect(result.trace.validationStatus == "transcriptDecoded")
+ #expect(result.trace.metadata["transcriptFeedsCommandParser"] == "true")
+ #expect(result.trace.metadata["localOnly"] == "true")
+ }
+
@Test
func ollamaTaskIntentAdapterBuildsLocalRequestAndDecodesValidatedIntent() async throws {
let httpClient = FakeAIHTTPClient(
@@ -506,6 +539,42 @@ struct AIHarnessAdapterTests {
monotonicUptimeNanoseconds: milliseconds * 1_000_000
)
}
+
+ private func fixedClock(_ milliseconds: [UInt64]) -> @Sendable () -> RunTraceTimestamp {
+ let clock = FixedTraceClock(milliseconds: milliseconds)
+ return {
+ clock.next()
+ }
+ }
+}
+
+private final class FixedTraceClock: @unchecked Sendable {
+ private var milliseconds: [UInt64]
+ private var index = 0
+
+ init(milliseconds: [UInt64]) {
+ self.milliseconds = milliseconds
+ }
+
+ func next() -> RunTraceTimestamp {
+ let value = milliseconds[min(index, milliseconds.count - 1)]
+ index += 1
+ return RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(value) / 1_000),
+ monotonicUptimeNanoseconds: value * 1_000_000
+ )
+ }
+}
+
+private struct FakeVoiceRuntime: LocalVoiceTranscriptionRuntime {
+ var transcript: LocalVoiceTranscript
+
+ func transcribe(
+ audio: LocalVoiceAudioBuffer,
+ model: AIModelRegistryEntry
+ ) async throws -> LocalVoiceTranscript {
+ transcript
+ }
}
private final class FakeAIHTTPClient: AIHTTPClient, @unchecked Sendable {
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
index 2136b9a7..d39eae33 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
@@ -187,6 +187,203 @@ struct LocalAppTaskTests {
#expect(unavailableCatalog.resolve(command: "show me the weather for SF").status == .appUnavailable)
}
+ @Test
+ func taskDefinitionLoaderLoadsLocalJSONDefinitions() throws {
+ let directoryURL = FileManager.default.temporaryDirectory
+ .appendingPathComponent("DonkeyTaskDefinitionLoader-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directoryURL) }
+
+ let definition = LocalAppTaskDefinition(
+ taskType: "notes_capture",
+ targetApp: LocalAppTarget(appName: "Notes", bundleIdentifier: "com.apple.Notes"),
+ triggerTerms: ["note", "remember"],
+ entityRules: [
+ LocalAppTaskEntityRule(
+ name: "note",
+ markers: ["note", "remember"],
+ metadata: ["capture": "afterTrigger"]
+ )
+ ],
+ workflowSteps: [
+ LocalAppTaskWorkflowStepDefinition(
+ id: "parse-intent",
+ role: .parseIntent,
+ summary: "Parse note intent"
+ )
+ ],
+ verificationEntityName: "note",
+ metadata: ["source": "test-json"]
+ )
+ let fileURL = directoryURL.appendingPathComponent("notes.json")
+ try JSONEncoder().encode(definition).write(to: fileURL)
+
+ let definitions = try LocalAppTaskDefinitionLoader().mergedWithBuiltIns(from: directoryURL)
+ let loaded = try #require(definitions.first(where: { $0.taskType == "notes_capture" }))
+ #expect(loaded.targetApp.bundleIdentifier == "com.apple.Notes")
+ #expect(loaded.metadata["source"] == "test-json")
+
+ let catalog = LocalAppTaskCatalog(
+ taskDefinitions: definitions,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Notes"])
+ )
+ #expect(catalog.resolve(command: "remember buy milk").status == .resolved)
+ }
+
+ @Test
+ func documentFormFillPlannerMapsStructuredDataToObservedFieldsForReview() throws {
+ let intent = try #require(parser().parse("fill out this PDF using this data"))
+ let context = LocalAppTaskContext(
+ focusedAppName: "Preview",
+ focusedBundleIdentifier: "com.apple.Preview",
+ focusedWindowTitle: "W-9.pdf",
+ structuredData: [
+ "Name": "Ada Lovelace",
+ "Address": "12 Algorithm Ave"
+ ],
+ observedFormFields: [
+ LocalDocumentFormField(id: "field-name", label: "Name", isRequired: true),
+ LocalDocumentFormField(id: "field-address", label: "Mailing Address", isRequired: true)
+ ]
+ )
+
+ let plan = DocumentFormFillPlanner().plan(
+ intent: intent,
+ definition: BuiltInLocalAppTaskDefinitions.documentFormFill,
+ context: context
+ )
+
+ #expect(plan.status == .readyForReview)
+ #expect(plan.proposals.count == 2)
+ #expect(plan.proposals.first(where: { $0.fieldID == "field-name" })?.proposedValue == "Ada Lovelace")
+ #expect(plan.metadata["requiresReview"] == "true")
+ }
+
+ @Test
+ func documentFormFillApprovalBuildsOnlyApprovedAccessibilityCommands() throws {
+ let intent = try #require(parser().parse("fill out this PDF using this data"))
+ let context = LocalAppTaskContext(
+ focusedWindowTitle: "W-9.pdf",
+ structuredData: [
+ "Name": "Ada Lovelace",
+ "Address": "12 Algorithm Ave"
+ ],
+ observedFormFields: [
+ LocalDocumentFormField(id: "ax-1.1", label: "Name", isRequired: true),
+ LocalDocumentFormField(id: "ax-1.2", label: "Address", isRequired: true)
+ ]
+ )
+ let planner = DocumentFormFillPlanner()
+ let plan = planner.plan(
+ intent: intent,
+ definition: BuiltInLocalAppTaskDefinitions.documentFormFill,
+ context: context
+ )
+ let approval = planner.approval(
+ for: plan,
+ traceID: "trace-approval",
+ approvedFieldIDs: ["ax-1.1"]
+ )
+ let commands = LocalAppAccessibilityActionPlanner().fillCommands(
+ approval: approval,
+ definition: BuiltInLocalAppTaskDefinitions.documentFormFill,
+ issuedAt: timestamp(200)
+ )
+
+ #expect(approval.status == .partiallyApproved)
+ #expect(approval.approvedProposals.map(\.fieldID) == ["ax-1.1"])
+ #expect(approval.rejectedFieldIDs == ["ax-1.2"])
+ #expect(commands.count == 1)
+ #expect(commands.first?.metadata["accessibility.action"] == "AXSetValue")
+ #expect(commands.first?.metadata["accessibility.nodeID"] == "ax-1.1")
+ #expect(commands.first?.metadata["documentFormFill.approvalID"] == approval.id)
+ }
+
+ @Test
+ func accessibilityControlDiscoveryIndexesControlsAndFormFields() throws {
+ let target = MacWindowTargetCandidate(
+ windowID: 7,
+ processID: 99,
+ appName: "Preview",
+ bundleIdentifier: "com.apple.Preview",
+ title: "Form.pdf",
+ bounds: WindowTargetBounds(x: 0, y: 0, width: 600, height: 800),
+ isVisible: true,
+ isOnScreen: true,
+ isFrontmost: true,
+ isFocused: true,
+ isIPhoneMirroring: false,
+ safetyAssessment: WindowTargetSafetyAssessment(status: .allowed, summary: "allowed")
+ )
+ let snapshot = MacAccessibilitySnapshot(
+ target: target,
+ limits: .default,
+ root: MacAccessibilitySnapshotNode(
+ nodeID: "ax-1",
+ role: "AXWindow",
+ title: "Form.pdf",
+ children: [
+ MacAccessibilitySnapshotNode(
+ nodeID: "ax-1.1",
+ role: "AXSearchField",
+ label: "Search",
+ frame: WindowTargetBounds(x: 20, y: 20, width: 200, height: 30),
+ actions: ["AXPress"]
+ ),
+ MacAccessibilitySnapshotNode(
+ nodeID: "ax-1.2",
+ role: "AXTextField",
+ label: "Name",
+ valueSummary: "",
+ frame: WindowTargetBounds(x: 40, y: 90, width: 240, height: 30)
+ )
+ ]
+ ),
+ totalNodeCount: 3,
+ isTreeTruncated: false
+ )
+ let discovery = LocalAppAccessibilityControlDiscovery()
+ let index = discovery.discover(in: snapshot)
+ let fields = discovery.observedFormFields(in: snapshot)
+
+ #expect(index.controls.count == 2)
+ #expect(index.firstControl(matching: "search")?.id == "ax-1.1")
+ #expect(fields.map(\.id) == ["ax-1.1", "ax-1.2"])
+ #expect(fields.first(where: { $0.id == "ax-1.2" })?.label == "Name")
+ }
+
+ @Test @MainActor
+ func liveRunnerReturnsReviewPlanForDocumentFormFillWithoutExecutingInput() async throws {
+ let catalog = LocalAppTaskCatalog(
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ 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 result = await runner.run(
+ command: "fill out this PDF using this data",
+ traceID: "trace-document-fill"
+ )
+
+ #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")
+ }
+
@Test @MainActor
func liveRunnerLaunchesFocusesExecutesGuardedCommandsAndVerifies() async throws {
let backend = RecordingLocalAppTaskInputBackend()
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift
index 971a00c1..e5c78058 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift
@@ -115,6 +115,36 @@ struct OffTheShelfVisionPerceptionTests {
#expect(report.decisionMS.p95 == 1)
}
+ @Test
+ func yoloScreenshotSegmentationRunnerProducesRecordedLocalEvidence() async throws {
+ let runner = YOLOScreenshotSegmentationRunner(
+ backend: FakeScreenshotSegmentationBackend(),
+ now: fixedClock([100, 118])
+ )
+ let result = try await runner.run(
+ ScreenshotSegmentationRequest(
+ traceID: "trace-yolo",
+ frameID: "frame-yolo",
+ targetID: "target-yolo",
+ cropID: "crop-search",
+ cropBounds: HotLoopRect(x: 0, y: 0, width: 320, height: 180, space: .window),
+ pixelSize: HotLoopSize(width: 320, height: 180, space: .crop)
+ )
+ )
+ let decoded = RecordedOffTheShelfVisionMetadataCodec.decode(from: result.metadata)
+ let signal = try #require(decoded.first)
+
+ #expect(result.model.id == "ultralytics-yolo26n-seg-screenshot")
+ #expect(signal.kind == .segmentation)
+ #expect(signal.modelID == "ultralytics-yolo26n-seg-screenshot")
+ #expect(signal.cropID == "crop-search")
+ #expect(signal.preprocessMS == 3)
+ #expect(signal.modelInferenceMS == 9)
+ #expect(signal.adapterOverheadMS == 6)
+ #expect(signal.observations.first?.label == "search-field")
+ #expect(signal.metadata["requiresLocalBenchmark"] == "true")
+ }
+
private func recordedSignal(
kind: OffTheShelfVisionSignalKind,
id: String,
@@ -177,4 +207,51 @@ struct OffTheShelfVisionPerceptionTests {
monotonicUptimeNanoseconds: milliseconds * 1_000_000
)
}
+
+ private func fixedClock(_ milliseconds: [UInt64]) -> @Sendable () -> RunTraceTimestamp {
+ let clock = FixedVisionClock(milliseconds: milliseconds)
+ return {
+ clock.next()
+ }
+ }
+}
+
+private final class FixedVisionClock: @unchecked Sendable {
+ private var milliseconds: [UInt64]
+ private var index = 0
+
+ init(milliseconds: [UInt64]) {
+ self.milliseconds = milliseconds
+ }
+
+ func next() -> RunTraceTimestamp {
+ let value = milliseconds[min(index, milliseconds.count - 1)]
+ index += 1
+ return RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(value) / 1_000),
+ monotonicUptimeNanoseconds: value * 1_000_000
+ )
+ }
+}
+
+private struct FakeScreenshotSegmentationBackend: ScreenshotSegmentationBackend {
+ func segment(
+ request: ScreenshotSegmentationRequest,
+ model: OffTheShelfVisionModelCandidate
+ ) async throws -> ScreenshotSegmentationBackendResult {
+ ScreenshotSegmentationBackendResult(
+ masks: [
+ ScreenshotSegmentationMask(
+ id: "mask-search",
+ label: "search-field",
+ bounds: HotLoopRect(x: 0.1, y: 0.2, width: 0.5, height: 0.1, space: .normalizedTarget),
+ confidence: 0.87,
+ pointCount: 18
+ )
+ ],
+ preprocessMS: 3,
+ modelInferenceMS: 9,
+ metadata: ["backend": "fake-yolo"]
+ )
+ }
}
diff --git a/docs/README.md b/docs/README.md
index 0022988a..21589093 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -4,7 +4,7 @@ This folder is the product and engineering source of truth for capabilities that
Plans describe what we might build. Guides describe what Donkey currently supports and how to maintain it.
-There is an active milestone plan in `plans/master-plan.md`. It tracks the unfinished work needed before the fast local navigation and AI-harness roadmap can be considered complete: generic local-app task knowledge, installed-app/task resolution, local-model command parsing with catalog validation, local voice-transcription model selection, local navigation, guarded input, result verification, latency reporting, and optional slow planner recovery. Weather lookup, media playback, and document form-fill are benchmark definitions for this generic system, not source-specific architectures.
+There is an active milestone plan in `plans/master-plan.md`. It tracks the unfinished work needed before the fast local navigation and AI-harness roadmap can be considered complete: generic local-app task knowledge, local JSON/JSONL task-definition loading, installed-app/task resolution, local-model command parsing with catalog validation, local task-context intake, Accessibility control discovery and action planning, review-first document form-fill planning, local voice-transcription model selection and adapter wiring, YOLO screenshot segmentation runner boundaries, local navigation, guarded input, result verification, latency reporting, and optional slow planner recovery. Weather lookup, media playback, and document form-fill are benchmark definitions for this generic system, not source-specific architectures.
## Product Guides
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index 6b1c91de..89ef276e 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -26,7 +26,7 @@ Donkey also supports the first cheap perception and deterministic controller sli
Donkey also supports the first off-the-shelf local vision evidence boundary inside the dry-run reflex loop. `RecordedOffTheShelfVisionMetadataCodec` can carry recorded detector, template, OCR, or segmentation observations with crop ids, component ids, model ids, confidence, coordinate spaces, and measured preprocessing/model latency. `OffTheShelfVisionPerceptionAdapter` converts that local evidence into compact `HotLoopPerceptionSignal` values, and `OffTheShelfVisionWorldStateProjector` exposes only typed affordances to the deterministic controller. This is a local perception contract and replay path; it does not yet run a live Core ML, ONNX, OCR, or template matcher over captured pixels.
-Donkey also tracks the first screenshot segmentation model candidate for the off-the-shelf vision boundary. `OffTheShelfVisionModelCatalog` lists Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`) as the current screenshot/crop segmentation candidate, with official docs rechecked on May 17, 2026. This is catalog metadata only; live screenshot segmentation still requires a local runner, crop pipeline, export/runtime choice, and measured latency before it can enter a guarded live loop.
+Donkey also tracks the first screenshot segmentation model candidate for the off-the-shelf vision boundary. `OffTheShelfVisionModelCatalog` lists Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`) as the current screenshot/crop segmentation candidate, with official docs rechecked on May 17, 2026. The runner boundary can convert injected local backend masks into traceable segmentation evidence, but live screenshot segmentation still requires an installed backend, crop pipeline integration, export/runtime choice, and measured latency before it can enter a guarded live loop.
Donkey also supports the first action-engine guardrail boundary. `ActionEngineGuardrail` accepts typed tap, swipe, key, mouse, controller, and `releaseAll` commands; checks input permission policy, focus guard status, command rate, and maximum hold duration; tracks held-input state; and records replayable command traces. Live input remains disabled by default and requires explicit configuration, an input-allowing policy, a passing focus guard, and an injected input backend. The local-app live runner injects a narrow macOS keyboard backend for guarded key/text commands; other action-engine use still records dry-run traces unless a caller opts into live input. Allowed non-live commands are projected as dry-run traces, live commands record backend execution evidence, denied commands include explicit denial reasons, and `releaseAll` clears held-input state.
@@ -34,7 +34,7 @@ Donkey also supports reflex latency reports and a synthetic replay benchmark. `R
Donkey also supports the first fast local-navigation dry-run slice end to end through the dry-run reflex loop. `LocalNavigationMetadataFrameSource` can turn macOS window candidate metadata and optional browser-tab metadata supplied by callers into metadata-only hot-loop frames. `LocalNavigationDryRunPerceptionAdapter` and `LocalNavigationDryRunWorldStateProjector` keep the local-navigation path swappable while preserving the no-remote-model fallback. `LocalNavigationControllerPolicy` can choose traceable dry-run semantic actions such as `focusWindow`, `activateCandidate`, `switchTab`, `wait`, or `observe` from typed state. This slice is metadata-only and side-effect free by default; guarded live-action smoke requires an injected backend, and richer visual inference remains future work.
-Donkey also supports the first generic local-app task catalog, intent, and live runner boundary. `TaskIntent` can represent a parsed task, target app, normalized entities, parser source, confidence, and confirmation state. `LocalAppTaskDefinition` describes app-task knowledge as data: target app metadata, deterministic trigger terms, required entities and aliases, workflow steps, observation strategies, and verification rules. `LocalAppTaskCatalog` resolves validated intents against known task definitions, checks target-app availability through an injected provider, and exposes built-in definitions such as Weather lookup, Music playback, and PDF/document form-fill as data rather than source-specific adapters. `OllamaTaskIntentAdapter` is the supported primary command parser: it sends the user command and available task definitions to a local Ollama-compatible structured-output model, decodes a `TaskIntent`, and validates it against the catalog before execution can proceed. `LocalAppTaskIntentParser` remains a deterministic fallback and test scaffold for known commands, not the preferred command-understanding path. `LocalAppTaskAdapter` can build a target-app local-navigation metadata request, project dry-run workflow steps, emit guarded keyboard command templates, and verify observed visible text against the requested entity. `LocalAppTaskLiveRunner` can launch or focus the resolved app, execute the task's guarded keyboard templates through `ActionEngineGuardrail`, observe visible Accessibility text when trusted, and return a final verification plan. Review-only tasks, such as document form-fill with external data, can resolve and plan without attempting live input until document/data context and field mapping are available. Accessibility actions, robust control discovery, live local-model UI understanding, and live visual fallback remain unsupported.
+Donkey also supports the first generic local-app task catalog, intent, live runner, and local task-definition loading boundary. `TaskIntent` can represent a parsed task, target app, normalized entities, parser source, confidence, and confirmation state. `LocalAppTaskDefinition` describes app-task knowledge as data: target app metadata, deterministic trigger terms, required entities and aliases, workflow steps, observation strategies, and verification rules. `LocalAppTaskDefinitionLoader` can load additional JSON or JSONL task definitions from `~/Library/Application Support/Donkey/TaskDefinitions/` and merge them with built-ins, so new use cases do not require Swift source changes. `LocalAppTaskCatalog` resolves validated intents against known task definitions, checks target-app availability through an injected provider, and exposes built-in definitions such as Weather lookup, Music playback, and PDF/document form-fill as data rather than source-specific adapters. `OllamaTaskIntentAdapter` is the supported primary command parser: it sends the user command and available task definitions to a local Ollama-compatible structured-output model, decodes a `TaskIntent`, and validates it against the catalog before execution can proceed. `LocalAppTaskIntentParser` remains a deterministic fallback and test scaffold for known commands, not the preferred command-understanding path. `LocalAppTaskAdapter` can build a target-app local-navigation metadata request, project dry-run workflow steps, emit guarded keyboard command templates, and verify observed visible text against the requested entity. `LocalAppAccessibilityControlDiscovery` can index controls and form fields from bounded Accessibility snapshots, and `MacAccessibilityActionEngineInputBackend` can execute guarded `AXPress` and `AXSetValue` commands when Accessibility is trusted, focus guard passes, and input policy allows it. `LocalAppTaskLiveRunner` can launch or focus the resolved app, prefer discovered Accessibility commands when available, fall back to guarded keyboard templates, observe visible Accessibility text when trusted, and return a final verification plan. Review-only tasks, such as document form-fill with external data, resolve into a local context snapshot and `DocumentFormFillPlanner` review plan; approved proposals can be converted to guarded Accessibility fill commands, but user-visible approval UI is still required before enabling default live form filling. Live local-model UI understanding remains unsupported.
Donkey also supports a guarded live-action smoke boundary for local-navigation behavior. `GuardedLiveActionSmokeRunner` requires an end-to-end dry-run result, a latency report with p95 evidence, a non-fallback latest action, explicit input policy allowance, and a passing action-engine focus guard before mapping semantic local-navigation actions to typed action-engine commands. The smoke path records replayable action traces and can execute only through an injected backend.
@@ -42,7 +42,9 @@ Donkey also supports slow-path planner hint contracts. `StructuredPlannerHint` c
Donkey also supports the first slow-planner sidecar beside the dry-run reflex loop. `DryRunSlowPlannerSidecar` can trigger on scene changes, low confidence, repeated fallback/failure, already-complete local-navigation goals, or explicit user instruction. It builds compact planner snapshots from the latest world state, action, bounded trace summaries, optional screenshot artifact references, and run memory. Planner work is notified from the dry-run loop after reflex trace publication in a fire-and-forget task, so model latency is not included in reflex p95. `ValidatedPlannerHintBus` publishes only validated hints, and `PlannerHintAwareControllerPolicy` can expose the latest still-valid hint to a controller without letting planner output become direct input.
-Donkey also supports the first AI harness model registry and router boundary. `AIModelRegistry` stores model roles, providers, literal model ids, endpoints, capabilities, timeouts, prompt versions, eval status, docs URLs, and rollback ids as registry data. `AIModelRouter` routes slow-path jobs by job type, risk, privacy mode, latency tolerance, capabilities, failed-model history, and allowed providers. Privacy-sensitive planner routes prefer local Ollama-compatible entries when they are available. Privacy-sensitive voice-transcription routes prefer local runtime entries and currently select NVIDIA Parakeet TDT 0.6B v3, with Whisper large-v3-turbo as a local rollback candidate. Literal provider model ids should stay in registry entries, not planner/controller logic.
+Donkey also supports the first AI harness model registry and router boundary. `AIModelRegistry` stores model roles, providers, literal model ids, endpoints, capabilities, timeouts, prompt versions, eval status, docs URLs, and rollback ids as registry data. `AIModelRouter` routes slow-path jobs by job type, risk, privacy mode, latency tolerance, capabilities, failed-model history, and allowed providers. Privacy-sensitive planner routes prefer local Ollama-compatible entries when they are available. Privacy-sensitive voice-transcription routes prefer local runtime entries and currently select NVIDIA Parakeet TDT 0.6B v3, with Whisper large-v3-turbo as a local rollback candidate. `LocalVoiceTranscriptionAdapter` accepts bounded local audio buffers, routes to the selected local runtime model, returns transcript text plus timing/confidence trace metadata, and marks transcripts as inputs to the normal command parser rather than actions. The default transcription runtime is injectable and unavailable until a local NeMo/Whisper runtime is installed. Literal provider model ids should stay in registry entries, not planner/controller logic.
+
+Donkey also supports the first measured screenshot segmentation runner boundary for the YOLO26 screenshot candidate. `YOLOScreenshotSegmentationRunner` accepts bounded crop requests, calls an injected local segmentation backend, converts masks into recorded off-the-shelf vision evidence, and preserves preprocessing/model/adapter latency in the same metadata codec used by the dry-run perception adapter. The default backend is unavailable; live segmentation requires an installed local runtime and target-specific benchmark evidence before it can affect live control.
Donkey also supports the first provider-neutral planner-hint adapter boundary using OpenAI's Responses API. `OpenAIPlannerHintAdapter` reads `OPENAI_API_KEY` from the environment, routes through the model registry, sends a structured-output Responses request with `store: false`, decodes a strict planner-hint JSON response, and records a model-call trace with role, provider, model id, prompt version, schema id, latency, timeout, validation status, and source trace/state ids. Missing credentials, cancellation, timeout, rate limit, invalid output, and provider outage return traceable failures without stopping the reflex loop. Official OpenAI docs were rechecked on May 16, 2026 for the Responses API, `text.format` JSON schema structured outputs, `store: false`, and current model registry default guidance.
@@ -73,7 +75,7 @@ Donkey supports a runtime-level manual target context capture service that wires
The installed executable also supports a developer-only launch-argument entrypoint for manual verification. `--list-window-candidates` prints the current candidate-list labels and durable `windowID` values. `--manual-capture` runs one manual capture, optionally with `--window-id <id>`, `--run-id <safe-id>`, and `--trace-id <safe-id>`, then prints the run folder and artifact paths. These commands are non-interactive and exit before showing the pointer prompt overlay.
-This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, cheap metadata perception, recorded off-the-shelf local vision evidence, screenshot segmentation model-candidate catalog, deterministic controller, local-navigation dry-run, generic local-app task catalog/intent/live-runner boundary, sample task definitions across weather/media/document domains, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, local voice-transcription model selection, OpenAI and Ollama-compatible planner adapters, memory, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run live transcription, live vision models, or OCR over captured pixels, perform Accessibility actions, provide robust UI control discovery, provide a manual capture UI, persist high-volume reflex traces to disk, provide continuous streaming capture, or make model calls required for reflex ticks.
+This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, cheap metadata perception, recorded off-the-shelf local vision evidence, screenshot segmentation model-candidate catalog and runner boundary, deterministic controller, local-navigation dry-run, generic local-app task catalog/intent/live-runner boundary, local JSON/JSONL task-definition loading, local task-context intake, Accessibility control discovery/action execution boundary, document form-fill review and approval planning, sample task definitions across weather/media/document domains, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, local voice-transcription model selection and adapter boundary, OpenAI and Ollama-compatible planner adapters, memory, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not bundle live transcription or vision model runtimes, run OCR over captured pixels, provide the user-visible form-fill approval UI, provide a manual capture UI, persist high-volume reflex traces to disk, provide continuous streaming capture, or make model calls required for reflex ticks.
## Technical Guidelines
@@ -99,17 +101,19 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic
- Keep controller fallback explicit. Low confidence, stale signals, missing affordances, and missing signals should produce traceable `wait` or `observe` actions, not silent no-ops.
- Keep every chosen controller action trace-linked with action id, state id, frame id, policy name, confidence, rationale, fallback metadata, and any compact source-evidence metadata needed to explain the rule.
- Keep action-engine commands typed and replayable. Guardrails must run before live input and record permission, focus, rate-limit, hold-duration, release, backend, issued time, backend completion time, and execution status. Live held-input tracking starts only after the backend reports execution.
-- Keep live OS input disabled unless a caller explicitly configures live mode, allows input in policy, passes focus guard, and supplies an input backend. The macOS keyboard backend is narrow: it is for guarded local-app key/text commands, not arbitrary controller output.
+- Keep live OS input disabled unless a caller explicitly configures live mode, allows input in policy, passes focus guard, and supplies an input backend. The macOS keyboard backend is narrow: it is for guarded local-app key/text commands, not arbitrary controller output. The macOS Accessibility backend is narrow too: it may execute only traceable `AXPress` or `AXSetValue` commands against discovered nodes in the focused target app.
- Use monotonic timestamps for latency math. Wall-clock timestamps are for human labels and trace correlation only.
- Use latency reports for any p50/p95/p99 claim. Reports should include dropped frames, stale actions, tick rates, and worst traces.
- Keep local-navigation decisions typed and side-effect free until the guarded live-action slice. Metadata projectors may use window, browser-tab, and Accessibility facts when available, but controllers should emit semantic actions only.
- Keep local-model task intents separate from planner hints. A supported local command should first parse to a validated `TaskIntent` through the local Ollama-compatible command parser; deterministic parsing is only a fallback/validator path, and slow planner output may only help app-knowledge lookup or recovery after validation.
- Keep local-app task adapter output inspectable before live control. Dry-run steps should show the normalized entities, target app identity, observation boundary, guarded command templates, and verification status before the live runner is allowed to launch, focus, type, or submit.
+- Keep local task definitions data-driven. Built-ins are examples; local JSON/JSONL definitions in Application Support are the extension point for more apps and workflows.
+- Keep document form filling review-first. Field detection, data mapping, proposed values, unmapped required fields, unused data keys, and approval IDs must be inspectable before any live fill action is enabled.
- Prefer Accessibility and metadata for app observation. When visual interpretation is needed, route bounded screenshot/crop context to a local model UI-understanding path before introducing OCR-specific plumbing; OCR remains an optional measured adapter, not the default fallback.
- Treat planner hints as validated, expiring advice. Controllers may use the latest valid hint, but planner output must never become direct input.
- Keep slow planner work beside the reflex loop. Trigger it from compact state, trace, memory, and artifact references; never await model calls from the hot tick before recording the reflex trace.
- Keep model selection in `AIModelRegistry` data. Do not scatter provider model ids through planner code.
-- Keep local voice transcription as a model-routed local runtime job. The pointer prompt can capture microphone levels today, but speech-to-text still needs an adapter that consumes bounded audio buffers, calls the selected local runtime model, and emits validated transcript text before it enters command parsing.
+- Keep local voice transcription as a model-routed local runtime job. Transcription output is transcript text only and must enter the same validated command path as typed input before any task can run.
- Keep privacy-sensitive Responses API calls configured with `store: false` unless an explicit later policy changes that default.
- Treat provider failures as sidecar failures. Missing credentials, timeout, rate limit, invalid output, or outage should leave the controller running on local state and existing valid hints.
- Keep memory writes source-linked and scoped. Model-proposed memory writes must pass the deterministic approver before storage; target and user records require TTL or explicit durable retention.
@@ -126,7 +130,7 @@ From `apps/Donkey/`:
swift test
```
-The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, recorded off-the-shelf vision evidence projection, screenshot segmentation model-candidate selection, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, local-model task intent request shaping and validation, deterministic local-app task parsing fallback and alias expansion, local-app catalog resolution and app availability checks, local-app navigation request construction, generic dry-run step projection, guarded keyboard command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, local voice-transcription model routing, OpenAI Responses request shaping and failure handling, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.
+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, recorded off-the-shelf vision evidence projection, screenshot segmentation model-candidate selection and runner evidence encoding, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, local-model task intent request shaping and validation, deterministic local-app task parsing fallback and alias expansion, local task-definition loading, local-app catalog resolution and app availability checks, local task-context intake, Accessibility control discovery, document form-fill review and approval planning, local-app navigation request construction, generic dry-run step projection, guarded keyboard and Accessibility command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, local voice-transcription model routing and adapter tracing, OpenAI Responses request shaping and failure handling, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.
Manual smoke commands:
@@ -161,9 +165,15 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi
- Local-navigation metadata projection and dry-run action selection live in `apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swift`.
- Local-navigation dry-run frame source, loop adapter, world-state projector, and generic controller wrapper live in `apps/Donkey/Sources/DonkeyRuntime/LocalNavigationDryRunLoop.swift`.
- Local-app task catalog resolution and built-in benchmark definitions live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift`.
+- Local task-definition loading lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift`.
+- Local task context intake lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskContext.swift`.
+- Local Accessibility control discovery and Accessibility action planning live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift`.
+- Document form-fill review planning lives in `apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillPlanner.swift`.
- Deterministic local-app task parsing lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift`.
- Generic local-app dry-run adapter and guarded keyboard command templates live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift`.
- Ollama-compatible local task-intent parsing lives in `apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift`.
+- Local voice transcription adapter boundary lives in `apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift`.
+- YOLO screenshot segmentation runner boundary lives in `apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift`.
- Slow-planner sidecar triggers, snapshots, validated hint bus, and hint-aware controller wrapper live in `apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift`.
- AI model registry and routing live in `apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift`.
- The OpenAI Responses planner-hint adapter lives in `apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift`.
diff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.md
index 6f3d2163..7c2e9d06 100644
--- a/docs/guides/pointer-prompt-overlay.md
+++ b/docs/guides/pointer-prompt-overlay.md
@@ -19,7 +19,7 @@ Donkey supports a floating macOS pointer prompt overlay:
- keeps that fixed offset at screen edges instead of flipping or clamping to the visible screen bounds
- submits typed prompt text through the local-app command pipeline while keeping model parsing, task validation, and live input outside the SwiftUI rendering path
-This is a visual, typed-command, and microphone-level UI capability. Typed submissions go to the local-app command handler, which prefers local-model task-intent parsing, validates the intent against the app-task catalog, and then runs the guarded local-app live runner. The overlay itself does not capture the screen, synthesize input, transcribe speech, or require Accessibility permission. It does request microphone permission so the waveform can reflect live local audio levels. The AI harness has a local voice-transcription model route, but the overlay has not yet wired microphone buffers into a speech-to-text adapter.
+This is a visual, typed-command, and microphone-level UI capability. Typed submissions go to the local-app command handler, which loads built-in plus local JSON/JSONL task definitions, prefers local-model task-intent parsing, validates the intent against the app-task catalog, and then runs the guarded local-app live runner. Review-only document tasks can return a compact review summary such as the number of mapped fields. The overlay itself does not capture the screen, synthesize input, transcribe speech, or require Accessibility permission. It does request microphone permission so the waveform can reflect live local audio levels. The AI harness has a local voice-transcription adapter boundary, but the overlay has not yet wired microphone buffers into that speech-to-text adapter.
## Technical Guidelines
@@ -43,6 +43,7 @@ This is a visual, typed-command, and microphone-level UI capability. Typed submi
- Double-Command prompt activation should require two clean Command down/up taps within 450ms. Any intervening key press, mouse press, extra modifier, or overlong Command hold should reset the sequence so normal shortcuts do not summon the modal.
- Holding the second clean Command press for the shortcut's configured hold duration should activate the prompt modal and start microphone level capture instead of waiting for the second release.
- Keep the overlay non-invasive: no screen capture loop, input execution, Accessibility prompt, or direct model call in SwiftUI rendering. Submit text to a command handler boundary instead.
+- Keep the command handler data-driven. It should resolve task knowledge from the local catalog, including local task definitions in Application Support, before invoking the guarded runtime path.
- Keep voice capture separate from transcription. The overlay may publish bounded local audio buffers to a future transcription adapter, but model execution and command parsing should remain outside the SwiftUI view/controller rendering path.
## Verification
@@ -59,5 +60,6 @@ Launch Donkey and confirm the inactive overlay does not render a visible cursor.
## Source Entry Points
- App orchestration starts in `apps/Donkey/Sources/Donkey/`.
+- Typed prompt command handling lives in `apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift`.
- Reusable SwiftUI rendering lives in `apps/Donkey/Sources/DonkeyUI/`.
- Historical completion notes live in `plans/done/21-swiftui-pointer-ui.md`.
diff --git a/plans/19-ai-harness.md b/plans/19-ai-harness.md
index 32d21944..6e79c8a8 100644
--- a/plans/19-ai-harness.md
+++ b/plans/19-ai-harness.md
@@ -1,6 +1,6 @@
# AI Harness
-> Active status: not complete. The current repo now has OpenAI and Ollama-compatible planner adapters, model routing, local task-intent parsing, local voice-transcription model selection, memory scaffolding, and a provider-backed slow-planner generator, but live transcription, semantic retrieval, redaction, aggregate model observability, and provider-decoded memory write proposals still remain.
+> Active status: not complete. The current repo now has OpenAI and Ollama-compatible planner adapters, model routing, local task-intent parsing, local voice-transcription model selection and adapter boundary, memory scaffolding, and a provider-backed slow-planner generator, but installed live transcription runtime wiring, semantic retrieval, redaction, aggregate model observability, and provider-decoded memory write proposals still remain.
## Goal
@@ -349,7 +349,7 @@ Voice input should become plain transcript text before it enters command parsing
The current default candidate is NVIDIA Parakeet TDT 0.6B v3 through a local NeMo-style runtime. It is selected because the official model card describes a current 600M-parameter ASR model with automatic language detection across 25 languages, punctuation/capitalization, word and segment timestamps, 16kHz mono `.wav`/`.flac` input, and a permissive CC BY 4.0 license. Whisper large-v3-turbo remains the local rollback candidate because it is widely supported in Transformers and local speech stacks.
-The next implementation slice should add an adapter that accepts bounded local microphone buffers, normalizes the audio format, invokes the selected local runtime model, emits transcript text plus timing/confidence metadata, and then passes the transcript to the same validated `TaskIntent` path used by typed commands.
+The current implementation has the adapter boundary: it accepts bounded local audio buffers, routes through `AIModelRouter`, invokes an injectable local transcription runtime, emits transcript text plus timing/confidence metadata, and marks transcript text as input to the same validated `TaskIntent` path used by typed commands. The next slice is installing concrete Parakeet/Whisper runtime adapters and wiring pointer-prompt microphone buffers into this adapter.
## Model Roles
diff --git a/plans/20-off-the-shelf-run-loop.md b/plans/20-off-the-shelf-run-loop.md
index b7ba4f97..dcecb8db 100644
--- a/plans/20-off-the-shelf-run-loop.md
+++ b/plans/20-off-the-shelf-run-loop.md
@@ -1,6 +1,6 @@
# Off-The-Shelf Run Loop
-> Active status: not complete. The current repo supports metadata-only local-navigation dry-run scaffolding, generic local-app task catalog parsing/adaptation, local JSON/JSONL task-definition loading, local-model command parsing, local task-context intake, review-first document form-fill planning, pointer-prompt typed command submission, macOS app launch/focus, guarded macOS keyboard input, local voice-transcription model selection, target-app availability checks, Accessibility visible-text observation when trusted, built-in task definitions across weather/media/document domains, and guarded live-action smoke. It still needs real-session verification and richer control discovery before any benchmark should be treated as done.
+> Active status: not complete. The current repo supports metadata-only local-navigation dry-run scaffolding, generic local-app task catalog parsing/adaptation, local JSON/JSONL task-definition loading, local-model command parsing, local task-context intake, Accessibility control discovery and guarded AX action commands, review/approval-first document form-fill planning, pointer-prompt typed command submission, macOS app launch/focus, guarded macOS keyboard input, local voice-transcription model selection and adapter boundary, target-app availability checks, Accessibility visible-text observation when trusted, built-in task definitions across weather/media/document domains, YOLO26 screenshot segmentation runner boundary, and guarded live-action smoke. It still needs installed local model runtimes, user-visible document approval UI, benchmark evidence, and real-session verification before any benchmark should be treated as done.
## Goal
@@ -515,20 +515,21 @@ The runtime foundation now supports a product-shaped local-navigation slice of t
- 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, review-first document form-fill planning, pointer-prompt typed command submission, dry-run workflow-step projection, guarded keyboard command templates, macOS launch/focus, guarded macOS keyboard input, Accessibility visible-text observation when trusted, and visible-text verification
-- screenshot segmentation model-candidate metadata for Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`)
+- 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
-This is still not the full off-the-shelf vision stack and must not be treated as completion. It can replay and trace compact local vision evidence, name a current YOLO segmentation candidate, load local task definitions, build reviewable document form-fill plans, and run a guarded keyboard-based local-app task path, but it does not ship live local detector/local-model/OCR/segmentation adapters over captured pixels, continuous streaming capture, Accessibility action execution, approved form-fill execution, robust UI control discovery, high-volume persisted replay traces, or target-specific visual calibration.
+This is still not the full off-the-shelf vision stack and must not be treated as completion. It 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, and run a guarded keyboard/AX local-app task path, but it does not bundle live local detector/local-model/OCR/segmentation runtimes, continuous streaming capture, user-visible form-fill approval UI, high-volume persisted replay traces, or target-specific visual calibration.
## Required Before This Plan Is Done
- Manually verify measured guarded-live execution for the first local-app task benchmark command "show me the weather for SF".
- Prove fast local navigation from parsed intent, local app observation, deterministic controller state, and guarded live input, not remote planning.
-- Extend the narrow macOS app-control backend from keyboard-only workflows to Accessibility action/control discovery where available.
-- Add the user-visible review and approval UI for document form-fill proposals before enabling guarded field entry.
+- Add the user-visible review and approval UI for document form-fill proposals before enabling default guarded field entry.
- Add result verification through Accessibility plus local model UI-understanding fallback, with OCR only if a narrow benchmark justifies it.
-- Add measured YOLO26 screenshot/crop segmentation inference for visual fallback, including export/runtime choice, crop size, mask quality, and p95 latency.
+- Add installed measured YOLO26 screenshot/crop segmentation inference for visual fallback, including export/runtime choice, crop size, mask quality, and p95 latency.
+- Add installed measured local ASR runtime wiring for Parakeet/Whisper and route transcripts through command parsing.
- Add continuous streaming capture once queue-depth, stale-result, and trace sinks are ready for longer sessions.
- Add durable high-volume replay trace persistence and target-specific benchmark baselines.
- Keep local model UI understanding, segmentation, and OCR optional in the live path until each has cropped, measured, target-specific evidence.
diff --git a/plans/master-plan.md b/plans/master-plan.md
index 735b28e3..cf4d75ce 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -56,9 +56,9 @@ The normal Weather benchmark path should work without a remote model call. A tin
## Supported Boundary
- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, in-memory reflex trace retention, and stage-split latency reports are supported.
-- Fast navigation hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, recorded off-the-shelf detector/template/OCR/segmentation evidence projection, screenshot segmentation model-candidate catalog with Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`), swappable world-state projection, deterministic controller, loop-integrated metadata-only local-navigation dry-run action selection, optional caller-supplied browser-tab metadata, dry-run action projection, generic local-app task intent contracts, data-driven task definitions, local JSON/JSONL task-definition loading, Ollama-compatible local-model command parsing to validated `TaskIntent`, deterministic parsing as fallback/validator, catalog command resolution, target-app availability checks, local task-context intake, document form-fill review planning, generic dry-run task adaptation, local-navigation request construction, step projection, guarded keyboard command templates, macOS app launch/focus, guarded macOS keyboard input, pointer-prompt typed command submission, Accessibility visible-text observation when trusted, visible-text verification, and built-in task definitions for Weather lookup, media playback, and document form-fill are supported. This is not yet a complete live fast-navigation agent: there is no Accessibility action execution, no robust live control discovery, no live local-model UI-understanding fallback, no live YOLO screenshot segmentation runner, no live voice-transcription adapter, and no manually verified live command-to-result Weather trace yet.
-- Safety boundary: action-engine command contracts, permission/focus/rate/hold/release guardrails, guarded live-action smoke with injected backends, the narrow macOS keyboard backend for local-app tasks, and replayable command traces are supported before any Accessibility-action backend exists.
-- Slow AI boundary: local-model task-intent parsing, local voice-transcription model routing, structured planner hints, validation/expiry/latest-valid selection, loop-adjacent slow-planner trigger/snapshot sidecar, model registry/router, OpenAI Responses and Ollama-compatible planner adapters, provider-backed local/online planner fallback, source-linked memory, and replay/eval scaffolding are supported as optional sidecar pieces. NVIDIA Parakeet TDT 0.6B v3 is the selected local voice-transcription default, with Whisper large-v3-turbo as a local rollback candidate. This is not yet the complete AI harness because semantic retrieval, redaction, aggregate model observability, live microphone transcription, live local visual UI understanding, and provider-decoded memory write proposals remain active.
+- Fast navigation hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, recorded off-the-shelf detector/template/OCR/segmentation evidence projection, screenshot segmentation model-candidate catalog and runner boundary with Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`), swappable world-state projection, deterministic controller, loop-integrated metadata-only local-navigation dry-run action selection, optional caller-supplied browser-tab metadata, dry-run action projection, generic local-app task intent contracts, data-driven task definitions, local JSON/JSONL task-definition loading, Ollama-compatible local-model command parsing to validated `TaskIntent`, deterministic parsing as fallback/validator, catalog command resolution, target-app availability checks, local task-context intake, Accessibility control discovery, document form-fill review and approval planning, generic dry-run task adaptation, local-navigation request construction, step projection, guarded keyboard and Accessibility command templates, macOS app launch/focus, guarded macOS keyboard input, guarded `AXPress`/`AXSetValue` backend, pointer-prompt typed command submission, Accessibility visible-text observation when trusted, visible-text verification, and built-in task definitions for Weather lookup, media playback, and document form-fill are supported. This is not yet a complete live fast-navigation agent: there is no live local-model UI-understanding fallback, no bundled live YOLO runtime, no bundled live voice-transcription runtime, no user-visible document approval UI, and no manually verified live command-to-result Weather trace yet.
+- Safety boundary: action-engine command contracts, permission/focus/rate/hold/release guardrails, guarded live-action smoke with injected backends, the narrow macOS keyboard backend for local-app tasks, the narrow macOS Accessibility backend for discovered nodes, and replayable command traces are supported.
+- Slow AI boundary: local-model task-intent parsing, local voice-transcription model routing and adapter tracing, structured planner hints, validation/expiry/latest-valid selection, loop-adjacent slow-planner trigger/snapshot sidecar, model registry/router, OpenAI Responses and Ollama-compatible planner adapters, provider-backed local/online planner fallback, source-linked memory, and replay/eval scaffolding are supported as optional sidecar pieces. NVIDIA Parakeet TDT 0.6B v3 is the selected local voice-transcription default, with Whisper large-v3-turbo as a local rollback candidate. This is not yet the complete AI harness because semantic retrieval, redaction, aggregate model observability, installed local microphone transcription runtime, live local visual UI understanding, and provider-decoded memory write proposals remain active.
- Source of truth: detailed supported behavior lives in `docs/guides/minimal-run-coordinator.md`; active unfinished work lives in this plan and its primary/supporting plans.
## Non-Negotiable Rules
@@ -84,18 +84,16 @@ Recent commits completed these pieces:
- current slice: generic local-app task catalog, local-model command parser, deterministic fallback parser, app availability check, and dry-run adapter boundary, with Weather lookup represented as built-in benchmark data.
- `d6e48c9`: archived plans, which was premature for this milestone.
-The code now includes the first generic local-app task catalog, local JSON/JSONL task-definition loader, local task context provider, document form-fill review planner, Ollama-compatible local-model command parser, deterministic fallback parser, app availability check, dry-run adapter boundary, local-app live runner, macOS launch/focus and keyboard-input backend, pointer-prompt typed command wiring, sample app-task definitions across weather/media/document domains, YOLO26 screenshot segmentation model-candidate metadata, and local voice-transcription model routing. It does not yet include Accessibility action execution, robust live control discovery, live local-model UI understanding over bounded screenshots/crops, live YOLO screenshot segmentation inference, live microphone transcription, semantic memory retrieval, remote-input redaction hooks, aggregate model observability, or provider-decoded memory write proposals.
+The code now includes the first generic local-app task catalog, local JSON/JSONL task-definition loader, local task context provider, Accessibility control discovery/action planning, document form-fill review and approval planner, Ollama-compatible local-model command parser, deterministic fallback parser, app availability check, dry-run adapter boundary, local-app live runner, macOS launch/focus, keyboard-input and Accessibility-input backends, pointer-prompt typed command wiring, sample app-task definitions across weather/media/document domains, YOLO26 screenshot segmentation model-candidate metadata and runner boundary, local voice-transcription model routing, and local voice-transcription adapter boundary. It does not yet include live local-model UI understanding over bounded screenshots/crops, bundled live YOLO screenshot segmentation inference, bundled live microphone transcription, semantic memory retrieval, remote-input redaction hooks, aggregate model observability, provider-decoded memory write proposals, or a user-visible approval UI for document fill proposals.
## What Should Be Done Next
-1. Manually verify the pointer-prompt-to-Weather and pointer-prompt-to-Music paths on a real macOS session: typed command submission, local-model intent parse or deterministic fallback, app launch/focus, guarded key/text execution, Accessibility visible-text observation, and final verification trace.
-2. Add robust live control discovery and Accessibility actions for local-app workflows so tasks can find controls instead of relying only on keyboard shortcuts.
-3. Extend document form-fill from review planning to guarded execution: discover fields from Accessibility/local UI understanding, map structured data, present review, then execute only approved field fills.
+1. Add the user-visible document approval UI in the pointer prompt or a companion review surface, then route approved proposals through the existing guarded Accessibility fill-command path.
+2. Wire pointer-prompt voice capture buffers into `LocalVoiceTranscriptionAdapter`, including bounded audio file/buffer handoff, transcript display, and routing transcript text through the same validated command-intent path as typed input.
+3. Add installed local runtime adapters for Parakeet/Whisper and YOLO26 segmentation behind the injectable runtime protocols, with model availability checks and clear unavailable states.
4. Add a local model UI-understanding fallback for bounded screenshot/crop context when Accessibility and metadata are insufficient. Prefer this before OCR-specific extraction; OCR can remain a measured optional adapter.
-5. Add a measured local screenshot segmentation runner for the YOLO26 candidate only after choosing export/runtime format and crop size; keep it outside live control until p95 latency and mask quality are recorded.
-6. Wire pointer-prompt voice input to a local transcription adapter: capture bounded microphone buffers, run the selected local runtime ASR model, emit transcript text, and pass that transcript through the same validated command-intent path as typed input.
-7. Add benchmark/reporting evidence for command-to-result latency, local navigation/action latency, verification confidence, visual fallback latency, voice transcription latency/accuracy, and comparison against manual/chat-style workflows.
-8. Keep the current dry-run/guarded-live safety boundary: local or online LLM output can only become validated intent, task definitions, app-knowledge updates, observation summaries, transcripts, or planner hints, never direct input.
+5. Add benchmark/reporting evidence for command-to-result latency, local navigation/action latency, verification confidence, Accessibility action latency, visual fallback latency, voice transcription latency/accuracy, YOLO mask quality/latency, and comparison against manual/chat-style workflows.
+6. Keep the current dry-run/guarded-live safety boundary: local or online LLM output can only become validated intent, task definitions, app-knowledge updates, observation summaries, transcripts, or planner hints, never direct input.
## Completion Gates