Skip to content

Open source CapCut alternative.

TypeScript

Restrict sidecars to request-driven actions

David Le427cd6b16b14
diff --git a/apps/Donkey/Sources/Donkey/DocumentFormFillReviewWindowController.swift b/apps/Donkey/Sources/Donkey/DocumentFormFillReviewWindowController.swift
new file mode 100644
index 00000000..952edf21
--- /dev/null
+++ b/apps/Donkey/Sources/Donkey/DocumentFormFillReviewWindowController.swift
@@ -0,0 +1,174 @@
+import AppKit
+import DonkeyRuntime
+import SwiftUI
+
+@MainActor
+final class DocumentFormFillReviewWindowController {
+ private var window: NSWindow?
+ private var viewModel: DocumentFormFillReviewViewModel?
+
+ func show(request: DocumentFormFillReviewRequest) {
+ let viewModel = DocumentFormFillReviewViewModel(
+ request: request,
+ close: { [weak self] in self?.close() }
+ )
+ self.viewModel = viewModel
+
+ let hostingView = NSHostingView(
+ rootView: DocumentFormFillReviewView(viewModel: viewModel)
+ )
+ let window = NSWindow(
+ contentRect: CGRect(x: 0, y: 0, width: 560, height: 420),
+ styleMask: [.titled, .closable, .miniaturizable],
+ backing: .buffered,
+ defer: false
+ )
+ window.title = "Review Form Fill"
+ window.contentView = hostingView
+ window.isReleasedWhenClosed = false
+ window.center()
+ window.makeKeyAndOrderFront(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ self.window = window
+ }
+
+ private func close() {
+ window?.close()
+ window = nil
+ viewModel = nil
+ }
+}
+
+@MainActor
+private final class DocumentFormFillReviewViewModel: ObservableObject {
+ @Published var selectedFieldIDs: Set<String>
+ @Published private(set) var statusText: String
+ @Published private(set) var isExecuting = false
+
+ let request: DocumentFormFillReviewRequest
+ private let close: @MainActor () -> Void
+ private let runner: DocumentFormFillApprovalLiveRunner
+
+ init(
+ request: DocumentFormFillReviewRequest,
+ close: @escaping @MainActor () -> Void,
+ runner: DocumentFormFillApprovalLiveRunner = DocumentFormFillApprovalLiveRunner(
+ coordinator: RunCoordinator()
+ )
+ ) {
+ self.request = request
+ self.close = close
+ self.runner = runner
+ selectedFieldIDs = Set(request.plan.proposals.map(\.fieldID))
+ statusText = "\(request.plan.proposals.count) proposed fields"
+ }
+
+ func approveSelected() {
+ guard !isExecuting else { return }
+
+ let fieldIDs = Array(selectedFieldIDs)
+ isExecuting = true
+ statusText = "Applying approved fields..."
+ close()
+
+ Task { [request, runner] in
+ _ = await runner.run(
+ plan: request.plan,
+ definition: request.definition,
+ traceID: request.traceID,
+ approvedFieldIDs: fieldIDs
+ )
+ }
+ }
+
+ func cancel() {
+ close()
+ }
+}
+
+private struct DocumentFormFillReviewView: View {
+ @ObservedObject var viewModel: DocumentFormFillReviewViewModel
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ header
+ proposalList
+ footer
+ }
+ .padding(20)
+ .frame(minWidth: 560, minHeight: 420)
+ }
+
+ private var header: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Review field values")
+ .font(.title3.weight(.semibold))
+ Text(viewModel.statusText)
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ }
+ }
+
+ private var proposalList: some View {
+ ScrollView {
+ LazyVStack(spacing: 8) {
+ ForEach(viewModel.request.plan.proposals, id: \.fieldID) { proposal in
+ Toggle(isOn: selectionBinding(for: proposal.fieldID)) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(proposal.fieldLabel)
+ .font(.system(size: 13, weight: .semibold))
+ Text(proposal.proposedValue)
+ .font(.system(size: 13))
+ .foregroundStyle(.primary)
+ Text("From \(proposal.sourceKey)")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .toggleStyle(.checkbox)
+ .padding(10)
+ .background(Color(nsColor: .controlBackgroundColor))
+ .clipShape(RoundedRectangle(cornerRadius: 8))
+ }
+ }
+ }
+ }
+
+ private var footer: some View {
+ HStack {
+ if !viewModel.request.plan.unmappedRequiredFieldIDs.isEmpty {
+ Text("\(viewModel.request.plan.unmappedRequiredFieldIDs.count) required fields are unmapped")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+
+ Spacer()
+
+ Button("Cancel") {
+ viewModel.cancel()
+ }
+
+ Button("Apply Approved") {
+ viewModel.approveSelected()
+ }
+ .keyboardShortcut(.defaultAction)
+ .disabled(viewModel.selectedFieldIDs.isEmpty || viewModel.isExecuting)
+ }
+ }
+
+ private func selectionBinding(for fieldID: String) -> Binding<Bool> {
+ Binding(
+ get: {
+ viewModel.selectedFieldIDs.contains(fieldID)
+ },
+ set: { isSelected in
+ if isSelected {
+ viewModel.selectedFieldIDs.insert(fieldID)
+ } else {
+ viewModel.selectedFieldIDs.remove(fieldID)
+ }
+ }
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift b/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift
index f69b6a99..6358c6ea 100644
--- a/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift
+++ b/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift
@@ -112,6 +112,18 @@ struct ManualCaptureDebugLaunchHandler {
"removed=\(removed)"
])
return 0
+ case .localAppTask(let options):
+ let result = await LocalAppPointerPromptCommandHandler()
+ .handleSubmittedCommand(options.command)
+ printLines(
+ ManualCaptureDebugCommandFormatter.lines(
+ status: result.status.rawValue,
+ summary: result.summary,
+ traceID: result.traceID,
+ metadata: result.metadata
+ )
+ )
+ return result.status == .completed || result.status == .needsUserReview ? 0 : 2
}
} catch {
printError(ManualCaptureDebugCommandFormatter.errorLine(for: error))
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
index 19e5c694..cc6cdbe4 100644
--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
@@ -8,6 +8,13 @@ struct PointerPromptCommandHandlingResult: Equatable, Sendable {
var summary: String
var traceID: String
var metadata: [String: String]
+ var documentReviewRequest: DocumentFormFillReviewRequest?
+}
+
+struct DocumentFormFillReviewRequest: Equatable, Sendable {
+ var plan: DocumentFormFillPlan
+ var definition: LocalAppTaskDefinition
+ var traceID: String
}
protocol PointerPromptCommandHandling: Sendable {
@@ -20,31 +27,30 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
var liveRunner: LocalAppTaskLiveRunner
var redactor: AIHarnessRedactor
var memoryRetriever: SemanticRunMemoryRetriever
+ var coordinator: RunCoordinator
+ var targetMemoryStore: TargetMemoryJSONLStore?
init(
catalog: LocalAppTaskCatalog = .defaultLocal(),
localModelResolver: LocalModelTaskIntentResolver? = nil,
liveRunner: LocalAppTaskLiveRunner? = nil,
redactor: AIHarnessRedactor = AIHarnessRedactor(),
- memoryRetriever: SemanticRunMemoryRetriever = SemanticRunMemoryRetriever()
+ memoryRetriever: SemanticRunMemoryRetriever = SemanticRunMemoryRetriever(),
+ coordinator: RunCoordinator = RunCoordinator(),
+ targetMemoryStore: TargetMemoryJSONLStore? = try? TargetMemoryJSONLStore()
) {
self.catalog = catalog
+ self.coordinator = coordinator
self.localModelResolver = localModelResolver ?? LocalModelTaskIntentResolver(catalog: catalog)
- self.liveRunner = liveRunner ?? LocalAppTaskLiveRunner(catalog: catalog)
+ self.liveRunner = liveRunner ?? LocalAppTaskLiveRunner(catalog: catalog, coordinator: coordinator)
self.redactor = redactor
self.memoryRetriever = memoryRetriever
+ self.targetMemoryStore = targetMemoryStore
}
func handleSubmittedCommand(_ command: String) async -> PointerPromptCommandHandlingResult {
let traceID = "pointer-prompt-\(UUID().uuidString)"
let redaction = redactor.redact(command, surface: .modelContext)
- let semanticMemoryResults = await memoryRetriever.retrieve(
- query: RunMemorySemanticQuery(
- text: command,
- budget: RunMemoryRetrievalBudget(maxRecords: 3, maxPromptCharacters: 800)
- ),
- records: []
- )
let memoryProposalDecisions = (try? ProviderDecodedMemoryProposalHandler.decisions(
from: Data("[]".utf8),
decidedAt: Self.now()
@@ -56,6 +62,10 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
)
let resolution = localModelResult.resolution
let parseLatencyMS = Self.uptimeMilliseconds() - parseStartedAt
+ let semanticMemoryResults = await retrieveSemanticMemory(
+ command: command,
+ resolution: resolution
+ )
let modelObservability = AIModelObservabilityReportBuilder.build(from: [localModelResult.trace])
let result = await liveRunner.run(
@@ -73,15 +83,81 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
"modelObservability.recoverySuccessCount": String(modelObservability.recoverySuccessCount),
"redaction.modelContext.count": String(redaction.redactionCount),
"semanticMemory.resultCount": String(semanticMemoryResults.count),
+ "semanticMemory.recordIDs": semanticMemoryResults.map(\.record.id).joined(separator: ","),
+ "semanticMemory.targetID": semanticMemoryTargetID(for: resolution) ?? "",
"memoryProposal.decisionCount": String(memoryProposalDecisions.count)
]
)
+ await coordinator.recordToolEvent(
+ capability: .model,
+ decision: .allow,
+ toolName: "local-task-intent-parser",
+ summary: "Parsed local app command",
+ traceID: traceID,
+ metadata: [
+ "modelCallID": localModelResult.trace.id,
+ "modelCallStatus": localModelResult.trace.status.rawValue,
+ "modelValidationStatus": localModelResult.trace.validationStatus
+ ]
+ )
return PointerPromptCommandHandlingResult(
status: result.status,
summary: summary(for: result),
traceID: traceID,
- metadata: result.metadata
+ metadata: result.metadata,
+ documentReviewRequest: documentReviewRequest(
+ traceID: traceID,
+ result: result
+ )
+ )
+ }
+
+ private func retrieveSemanticMemory(
+ command: String,
+ resolution: LocalAppTaskCatalogResolution
+ ) async -> [RunMemorySemanticResult] {
+ guard let targetMemoryStore,
+ let targetID = semanticMemoryTargetID(for: resolution),
+ let records = try? await targetMemoryStore.records(targetID: targetID),
+ !records.isEmpty
+ else {
+ return []
+ }
+
+ return await memoryRetriever.retrieve(
+ query: RunMemorySemanticQuery(
+ text: command,
+ targetID: targetID,
+ scope: .target,
+ budget: RunMemoryRetrievalBudget(maxRecords: 3, maxPromptCharacters: 800)
+ ),
+ records: records
+ )
+ }
+
+ private func semanticMemoryTargetID(
+ for resolution: LocalAppTaskCatalogResolution
+ ) -> String? {
+ guard let definition = resolution.definition else { return nil }
+ return LocalAppTaskAdapter(definition: definition).targetID
+ }
+
+ private func documentReviewRequest(
+ traceID: String,
+ result: LocalAppTaskLiveRunResult
+ ) -> DocumentFormFillReviewRequest? {
+ guard result.status == .needsUserReview,
+ let plan = result.documentFormFillPlan,
+ let definition = result.resolution.definition
+ else {
+ return nil
+ }
+
+ return DocumentFormFillReviewRequest(
+ plan: plan,
+ definition: definition,
+ traceID: traceID
)
}
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift
index 6b0b25c9..4fd97ebb 100644
--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift
+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift
@@ -15,6 +15,7 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
private let commandHandler: any PointerPromptCommandHandling
private let voiceTranscriber: LocalVoiceTranscriptionAdapter
private var updateChecker: any DonkeyUpdateChecking
+ private let documentReviewController: DocumentFormFillReviewWindowController
init(
aiProvider: any AIHarnessSnapshotProviding = AIHarnessBoundary(),
@@ -23,11 +24,13 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
runtime: ProcessBackedParakeetTranscriptionRuntime()
),
updateChecker: any DonkeyUpdateChecking = SparkleUpdateController(),
+ documentReviewController: DocumentFormFillReviewWindowController = DocumentFormFillReviewWindowController(),
theme: PointerPromptTheme = PointerPromptOverlayModel.bundledTheme()
) {
self.commandHandler = commandHandler
self.voiceTranscriber = voiceTranscriber
self.updateChecker = updateChecker
+ self.documentReviewController = documentReviewController
updateState = PointerPromptUpdateState(
currentVersion: updateChecker.currentVersion
)
@@ -140,6 +143,9 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
guard let self else { return }
self.promptState.leadingSignalLevel = result.status == .completed ? .ready : .idle
self.promptState.promptText = result.summary
+ if let documentReviewRequest = result.documentReviewRequest {
+ self.documentReviewController.show(request: documentReviewRequest)
+ }
}
}
}
diff --git a/apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swift b/apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swift
index 5af7cd18..1753b4f8 100644
--- a/apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swift
+++ b/apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swift
@@ -1,4 +1,5 @@
import DonkeyContracts
+import DonkeyRuntime
import Foundation
public enum AIHarnessRedactionSurface: String, Codable, Equatable, Sendable {
@@ -164,4 +165,87 @@ public enum ProviderDecodedMemoryProposalHandler {
)
}
}
+
+ public static func process(
+ proposals: [RunMemoryWriteProposal],
+ decidedAt: RunTraceTimestamp,
+ targetMemoryStore: TargetMemoryJSONLStore?
+ ) async -> ProviderMemoryProposalProcessingResult {
+ var decisions: [RunMemoryWriteDecision] = []
+ var approvedCount = 0
+ var rejectedCount = 0
+ var persistedCount = 0
+ var persistenceErrorCount = 0
+
+ for proposal in proposals {
+ let approval = RunMemoryApprover.evaluate(proposal, decidedAt: decidedAt)
+ guard approval.approved else {
+ rejectedCount += 1
+ decisions.append(
+ RunMemoryWriteDecision(
+ proposal: proposal,
+ approval: approval,
+ storedRecord: nil
+ )
+ )
+ continue
+ }
+
+ approvedCount += 1
+ if let targetMemoryStore,
+ proposal.record.scope == .target {
+ do {
+ let decision = try await targetMemoryStore.appendApprovedProposal(
+ proposal,
+ decidedAt: decidedAt
+ )
+ if decision.storedRecord != nil {
+ persistedCount += 1
+ }
+ decisions.append(decision)
+ } catch {
+ persistenceErrorCount += 1
+ decisions.append(
+ RunMemoryWriteDecision(
+ proposal: proposal,
+ approval: approval,
+ storedRecord: nil
+ )
+ )
+ }
+ } else {
+ decisions.append(
+ RunMemoryWriteDecision(
+ proposal: proposal,
+ approval: approval,
+ storedRecord: nil
+ )
+ )
+ }
+ }
+
+ return ProviderMemoryProposalProcessingResult(
+ decisions: decisions,
+ metadata: [
+ "memoryProposal.count": String(proposals.count),
+ "memoryProposal.approvedCount": String(approvedCount),
+ "memoryProposal.rejectedCount": String(rejectedCount),
+ "memoryProposal.persistedCount": String(persistedCount),
+ "memoryProposal.persistenceErrorCount": String(persistenceErrorCount)
+ ]
+ )
+ }
+}
+
+public struct ProviderMemoryProposalProcessingResult: Equatable, Sendable {
+ public var decisions: [RunMemoryWriteDecision]
+ public var metadata: [String: String]
+
+ public init(
+ decisions: [RunMemoryWriteDecision],
+ metadata: [String: String]
+ ) {
+ self.decisions = decisions
+ self.metadata = metadata
+ }
}
diff --git a/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
index 206ef679..b0c54dc0 100644
--- a/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
@@ -204,6 +204,142 @@ private struct ParakeetSidecarResponse: Codable, Equatable, Sendable {
}
}
+public enum LocalVoiceAudioNormalizer {
+ public static func parakeetCompatibleAudio(
+ from audio: LocalVoiceAudioBuffer
+ ) -> LocalVoiceAudioBuffer {
+ let normalizedFormat = audio.format.lowercased()
+ if ["wav", "flac"].contains(normalizedFormat),
+ audio.sampleRateHz == 16_000,
+ audio.channelCount == 1 {
+ return audio.withMetadata([
+ "audio.normalization.status": "notRequired",
+ "audio.normalization.target": "parakeet-16khz-mono"
+ ])
+ }
+
+ guard normalizedFormat == "pcm_f32le",
+ audio.channelCount == 1,
+ audio.sampleRateHz > 0,
+ !audio.data.isEmpty
+ else {
+ return audio.withMetadata([
+ "audio.normalization.status": "unsupportedInputFormat",
+ "audio.normalization.target": "parakeet-16khz-mono",
+ "audio.normalization.sourceFormat": audio.format,
+ "audio.normalization.sourceSampleRateHz": String(audio.sampleRateHz),
+ "audio.normalization.sourceChannelCount": String(audio.channelCount)
+ ])
+ }
+
+ let samples = float32Samples(from: audio.data)
+ guard !samples.isEmpty else {
+ return audio.withMetadata([
+ "audio.normalization.status": "emptyPCM",
+ "audio.normalization.target": "parakeet-16khz-mono"
+ ])
+ }
+
+ let resampled = resample(samples, sourceRate: audio.sampleRateHz, targetRate: 16_000)
+ let wavData = wavPCM16Data(samples: resampled, sampleRateHz: 16_000)
+ let durationMS = Double(resampled.count) / 16_000 * 1_000
+ return LocalVoiceAudioBuffer(
+ id: audio.id,
+ format: "wav",
+ sampleRateHz: 16_000,
+ channelCount: 1,
+ durationMS: durationMS,
+ data: wavData,
+ metadata: audio.metadata.merging([
+ "audio.normalization.status": "converted",
+ "audio.normalization.target": "parakeet-16khz-mono-wav",
+ "audio.normalization.sourceFormat": audio.format,
+ "audio.normalization.sourceSampleRateHz": String(audio.sampleRateHz),
+ "audio.normalization.sourceChannelCount": String(audio.channelCount),
+ "audio.normalization.sourceByteCount": String(audio.data.count),
+ "audio.normalization.outputByteCount": String(wavData.count)
+ ]) { current, _ in current }
+ )
+ }
+
+ private static func float32Samples(from data: Data) -> [Float] {
+ let sampleCount = data.count / MemoryLayout<UInt32>.size
+ guard sampleCount > 0 else { return [] }
+
+ var samples: [Float] = []
+ samples.reserveCapacity(sampleCount)
+ for index in 0..<sampleCount {
+ let offset = index * MemoryLayout<UInt32>.size
+ let bits = data[offset..<(offset + MemoryLayout<UInt32>.size)].reduce(UInt32(0)) { value, byte in
+ (value >> 8) | (UInt32(byte) << 24)
+ }
+ samples.append(Float(bitPattern: UInt32(littleEndian: bits)))
+ }
+ return samples
+ }
+
+ private static func resample(
+ _ samples: [Float],
+ sourceRate: Int,
+ targetRate: Int
+ ) -> [Float] {
+ guard sourceRate != targetRate else { return samples }
+ let outputCount = max(1, Int((Double(samples.count) * Double(targetRate) / Double(sourceRate)).rounded()))
+ guard samples.count > 1 else {
+ return Array(repeating: samples.first ?? 0, count: outputCount)
+ }
+
+ let sourceStep = Double(sourceRate) / Double(targetRate)
+ return (0..<outputCount).map { outputIndex in
+ let sourcePosition = Double(outputIndex) * sourceStep
+ let lowerIndex = min(samples.count - 1, Int(sourcePosition.rounded(.down)))
+ let upperIndex = min(samples.count - 1, lowerIndex + 1)
+ let fraction = Float(sourcePosition - Double(lowerIndex))
+ return samples[lowerIndex] + (samples[upperIndex] - samples[lowerIndex]) * fraction
+ }
+ }
+
+ private static func wavPCM16Data(samples: [Float], sampleRateHz: Int) -> Data {
+ var pcmData = Data(capacity: samples.count * MemoryLayout<Int16>.size)
+ for sample in samples {
+ let clamped = min(max(sample, -1), 1)
+ var value = Int16(clamped * Float(Int16.max)).littleEndian
+ pcmData.append(Data(bytes: &value, count: MemoryLayout<Int16>.size))
+ }
+
+ var data = Data()
+ appendASCII("RIFF", to: &data)
+ appendUInt32(UInt32(36 + pcmData.count), to: &data)
+ appendASCII("WAVE", to: &data)
+ appendASCII("fmt ", to: &data)
+ appendUInt32(16, to: &data)
+ appendUInt16(1, to: &data)
+ appendUInt16(1, to: &data)
+ appendUInt32(UInt32(sampleRateHz), to: &data)
+ appendUInt32(UInt32(sampleRateHz * 2), to: &data)
+ appendUInt16(2, to: &data)
+ appendUInt16(16, to: &data)
+ appendASCII("data", to: &data)
+ appendUInt32(UInt32(pcmData.count), to: &data)
+ data.append(pcmData)
+ return data
+ }
+
+ private static func appendASCII(_ value: String, to data: inout Data) {
+ data.append(contentsOf: value.utf8)
+ }
+
+ private static func appendUInt16(_ value: UInt16, to data: inout Data) {
+ var littleEndian = value.littleEndian
+ data.append(Data(bytes: &littleEndian, count: MemoryLayout<UInt16>.size))
+ }
+
+ private static func appendUInt32(_ value: UInt32, to data: inout Data) {
+ var littleEndian = value.littleEndian
+ data.append(Data(bytes: &littleEndian, count: MemoryLayout<UInt32>.size))
+ }
+}
+
public struct LocalVoiceTranscriptionAdapter: Sendable {
public var router: AIModelRouter
public var runtime: any LocalVoiceTranscriptionRuntime
@@ -238,8 +374,9 @@ public struct LocalVoiceTranscriptionAdapter: Sendable {
)
}
+ let preparedAudio = LocalVoiceAudioNormalizer.parakeetCompatibleAudio(from: request.audio)
do {
- let transcript = try await runtime.transcribe(audio: request.audio, model: entry)
+ let transcript = try await runtime.transcribe(audio: preparedAudio, model: entry)
guard !transcript.text.isEmpty else {
throw LocalVoiceTranscriptionRuntimeError.emptyTranscript
}
@@ -251,7 +388,7 @@ public struct LocalVoiceTranscriptionAdapter: Sendable {
startedAt: startedAt,
status: .completed,
validationStatus: "transcriptDecoded",
- metadata: metadata(for: request.audio, transcript: transcript)
+ metadata: metadata(for: request.audio, preparedAudio: preparedAudio, transcript: transcript)
)
)
} catch is CancellationError {
@@ -263,7 +400,7 @@ public struct LocalVoiceTranscriptionAdapter: Sendable {
startedAt: startedAt,
status: .cancelled,
validationStatus: "notValidated",
- metadata: metadata(for: request.audio)
+ metadata: metadata(for: request.audio, preparedAudio: preparedAudio)
)
)
} catch {
@@ -275,7 +412,7 @@ public struct LocalVoiceTranscriptionAdapter: Sendable {
startedAt: startedAt,
status: .providerOutage,
validationStatus: "notValidated",
- metadata: metadata(for: request.audio).merging([
+ metadata: metadata(for: request.audio, preparedAudio: preparedAudio).merging([
"reason": String(describing: error)
]) { current, _ in current }
)
@@ -313,6 +450,7 @@ public struct LocalVoiceTranscriptionAdapter: Sendable {
private func metadata(
for audio: LocalVoiceAudioBuffer,
+ preparedAudio: LocalVoiceAudioBuffer? = nil,
transcript: LocalVoiceTranscript? = nil
) -> [String: String] {
var values = [
@@ -323,6 +461,16 @@ public struct LocalVoiceTranscriptionAdapter: Sendable {
"audio.durationMS": String(audio.durationMS),
"audio.byteCount": String(audio.data.count)
]
+ if let preparedAudio {
+ values["audio.prepared.format"] = preparedAudio.format
+ values["audio.prepared.sampleRateHz"] = String(preparedAudio.sampleRateHz)
+ values["audio.prepared.channelCount"] = String(preparedAudio.channelCount)
+ values["audio.prepared.durationMS"] = String(preparedAudio.durationMS)
+ values["audio.prepared.byteCount"] = String(preparedAudio.data.count)
+ values.merge(preparedAudio.metadata.filter { key, _ in
+ key.hasPrefix("audio.normalization.")
+ }) { current, _ in current }
+ }
if let transcript {
values["transcript.confidence"] = String(transcript.confidence)
values["transcript.language"] = transcript.language ?? ""
@@ -338,3 +486,17 @@ public struct LocalVoiceTranscriptionAdapter: Sendable {
)
}
}
+
+private extension LocalVoiceAudioBuffer {
+ func withMetadata(_ values: [String: String]) -> LocalVoiceAudioBuffer {
+ LocalVoiceAudioBuffer(
+ id: id,
+ format: format,
+ sampleRateHz: sampleRateHz,
+ channelCount: channelCount,
+ durationMS: durationMS,
+ data: data,
+ metadata: metadata.merging(values) { current, _ in current }
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift
index b7133d3e..ceced236 100644
--- a/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift
@@ -7,13 +7,16 @@ public struct OllamaPlannerHintAdapter: Sendable {
public var router: AIModelRouter
public var httpClient: any AIHTTPClient
+ public var targetMemoryStore: TargetMemoryJSONLStore?
public init(
router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),
- httpClient: any AIHTTPClient = URLSessionAIHTTPClient()
+ httpClient: any AIHTTPClient = URLSessionAIHTTPClient(),
+ targetMemoryStore: TargetMemoryJSONLStore? = try? TargetMemoryJSONLStore()
) {
self.router = router
self.httpClient = httpClient
+ self.targetMemoryStore = targetMemoryStore
}
public func generatePlannerHint(
@@ -48,19 +51,28 @@ public struct OllamaPlannerHintAdapter: Sendable {
}
guard (200..<300).contains(response.statusCode),
- let outputText = try Self.outputText(from: data),
- let hint = try PlannerHintWireCodec.decodeHint(
- outputText,
- sourceTraceID: request.sourceTraceID,
- sourceFrameID: request.sourceFrameID,
- sourceStateID: request.sourceStateID,
- modelCallID: "model-call-\(request.sourceTraceID)",
- now: request.now
- )
+ let outputText = try Self.outputText(from: data)
else {
return result(entry: entry, request: request, status: .invalidOutput, validationStatus: "invalid", latencyMS: latencyMS)
}
+ let providerOutput = try PlannerHintWireCodec.decodeProviderOutput(
+ outputText,
+ sourceTraceID: request.sourceTraceID,
+ sourceFrameID: request.sourceFrameID,
+ sourceStateID: request.sourceStateID,
+ modelCallID: "model-call-\(request.sourceTraceID)",
+ now: request.now
+ )
+ guard let hint = providerOutput.hint else {
+ return result(entry: entry, request: request, status: .invalidOutput, validationStatus: "invalid", latencyMS: latencyMS)
+ }
+ let proposalProcessing = await ProviderDecodedMemoryProposalHandler.process(
+ proposals: providerOutput.memoryWriteProposals,
+ decidedAt: request.now,
+ targetMemoryStore: targetMemoryStore
+ )
+
return PlannerHintAdapterResult(
hint: hint,
trace: trace(
@@ -73,7 +85,10 @@ public struct OllamaPlannerHintAdapter: Sendable {
"http.status": String(response.statusCode),
"local.provider": "ollama"
]
- )
+ .merging(providerOutput.metadata) { current, _ in current }
+ .merging(proposalProcessing.metadata) { current, _ in current }
+ ),
+ memoryWriteDecisions: proposalProcessing.decisions
)
} catch is CancellationError {
return result(entry: entry, request: request, status: .cancelled, validationStatus: "notValidated", latencyMS: nil)
@@ -120,18 +135,27 @@ public struct OllamaPlannerHintAdapter: Sendable {
private func promptText(for request: PlannerHintAdapterRequest) -> String {
[
- "Return one planner hint as strict JSON. Hints are advisory and never direct input.",
+ "Return strict JSON with a planner hint and memoryWriteProposals. Hints are advisory and never direct input.",
"goal: \(request.context.userGoal)",
"target: \(request.context.targetID)",
"runtime: \(request.context.runtimeProfile)",
"latest_state: \(request.context.latestWorldState?.summary ?? "none")",
"source_state_id: \(request.sourceStateID ?? "none")",
"valid_hints: \(request.context.activeHints.map(\.summary).joined(separator: " | "))",
- "recent_failures: \(request.context.recentFailures.map(\.summary).joined(separator: " | "))"
+ "recent_failures: \(request.context.recentFailures.map(\.summary).joined(separator: " | "))",
+ "semantic_memory: \(semanticMemoryText(for: request.context.semanticMemoryResults))"
]
.joined(separator: "\n")
}
+ private func semanticMemoryText(for results: [RunMemorySemanticResult]) -> String {
+ guard !results.isEmpty else { return "none" }
+ return results.map { result in
+ "\(result.record.id)(\(String(format: "%.2f", result.relevance))): \(result.record.value)"
+ }
+ .joined(separator: " | ")
+ }
+
private func result(
entry: AIModelRegistryEntry?,
request: PlannerHintAdapterRequest,
diff --git a/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift
index 80cdfbea..ee271809 100644
--- a/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift
@@ -1,4 +1,5 @@
import DonkeyContracts
+import DonkeyRuntime
import Foundation
public enum AIModelCallStatus: String, Codable, Equatable, Sendable {
@@ -85,13 +86,16 @@ public struct PlannerHintAdapterRequest: Equatable, Sendable {
public struct PlannerHintAdapterResult: Equatable, Sendable {
public var hint: StructuredPlannerHint?
public var trace: AIModelCallTrace
+ public var memoryWriteDecisions: [RunMemoryWriteDecision]
public init(
hint: StructuredPlannerHint?,
- trace: AIModelCallTrace
+ trace: AIModelCallTrace,
+ memoryWriteDecisions: [RunMemoryWriteDecision] = []
) {
self.hint = hint
self.trace = trace
+ self.memoryWriteDecisions = memoryWriteDecisions
}
}
@@ -121,15 +125,18 @@ public struct OpenAIPlannerHintAdapter: Sendable {
public var router: AIModelRouter
public var httpClient: any AIHTTPClient
public var environment: [String: String]
+ public var targetMemoryStore: TargetMemoryJSONLStore?
public init(
router: AIModelRouter = AIModelRouter(),
httpClient: any AIHTTPClient = URLSessionAIHTTPClient(),
- environment: [String: String] = ProcessInfo.processInfo.environment
+ environment: [String: String] = ProcessInfo.processInfo.environment,
+ targetMemoryStore: TargetMemoryJSONLStore? = try? TargetMemoryJSONLStore()
) {
self.router = router
self.httpClient = httpClient
self.environment = environment
+ self.targetMemoryStore = targetMemoryStore
}
public func generatePlannerHint(
@@ -179,19 +186,29 @@ public struct OpenAIPlannerHintAdapter: Sendable {
}
guard (200..<300).contains(response.statusCode),
- let outputText = try Self.outputText(from: data),
- let hint = try Self.decodeHint(
- outputText,
- sourceTraceID: request.sourceTraceID,
- sourceFrameID: request.sourceFrameID,
- sourceStateID: request.sourceStateID,
- modelCallID: "model-call-\(request.sourceTraceID)",
- now: request.now
- )
+ let outputText = try Self.outputText(from: data)
else {
return result(entry: entry, request: request, status: .invalidOutput, validationStatus: "invalid", latencyMS: latencyMS)
}
+ let providerOutput = try PlannerHintWireCodec.decodeProviderOutput(
+ outputText,
+ sourceTraceID: request.sourceTraceID,
+ sourceFrameID: request.sourceFrameID,
+ sourceStateID: request.sourceStateID,
+ modelCallID: "model-call-\(request.sourceTraceID)",
+ now: request.now
+ )
+ guard let hint = providerOutput.hint else {
+ return result(entry: entry, request: request, status: .invalidOutput, validationStatus: "invalid", latencyMS: latencyMS)
+ }
+
+ let proposalProcessing = await ProviderDecodedMemoryProposalHandler.process(
+ proposals: providerOutput.memoryWriteProposals,
+ decidedAt: request.now,
+ targetMemoryStore: targetMemoryStore
+ )
+
return PlannerHintAdapterResult(
hint: hint,
trace: trace(
@@ -204,7 +221,10 @@ public struct OpenAIPlannerHintAdapter: Sendable {
"http.status": String(response.statusCode),
"privacy.store": "false"
]
- )
+ .merging(providerOutput.metadata) { current, _ in current }
+ .merging(proposalProcessing.metadata) { current, _ in current }
+ ),
+ memoryWriteDecisions: proposalProcessing.decisions
)
} catch is CancellationError {
return result(entry: entry, request: request, status: .cancelled, validationStatus: "notValidated", latencyMS: nil)
@@ -243,7 +263,7 @@ public struct OpenAIPlannerHintAdapter: Sendable {
[
"model": entry.modelID,
"store": false,
- "instructions": "Return one planner hint as strict JSON. Hints are advisory and never direct input.",
+ "instructions": "Return strict JSON with a planner hint and memoryWriteProposals. Hints are advisory and never direct input. Leave memoryWriteProposals empty unless a source-linked target memory should be proposed.",
"input": [
[
"role": "user",
@@ -279,7 +299,8 @@ public struct OpenAIPlannerHintAdapter: Sendable {
"source_state_id: \(request.sourceStateID ?? "none")",
"valid_hints: \(request.context.activeHints.map(\.summary).joined(separator: " | "))",
"recent_failures: \(request.context.recentFailures.map(\.summary).joined(separator: " | "))",
- "memory: \(memoryText(for: request.context.memorySnapshot))"
+ "memory: \(memoryText(for: request.context.memorySnapshot))",
+ "semantic_memory: \(semanticMemoryText(for: request.context.semanticMemoryResults))"
]
.joined(separator: "\n")
}
@@ -304,6 +325,14 @@ public struct OpenAIPlannerHintAdapter: Sendable {
return "\(label)=\(values.joined(separator: "; "))"
}
+ private func semanticMemoryText(for results: [RunMemorySemanticResult]) -> String {
+ guard !results.isEmpty else { return "none" }
+ return results.map { result in
+ "\(result.record.id)(\(String(format: "%.2f", result.relevance))): \(result.record.value)"
+ }
+ .joined(separator: " | ")
+ }
+
private func plannerHintJSONSchema() -> [String: Any] {
PlannerHintWireCodec.jsonSchema()
}
@@ -387,8 +416,33 @@ struct PlannerHintWireOutput: Decodable {
var expiryMilliseconds: UInt64
}
+struct PlannerProviderWireOutput: Equatable, Sendable {
+ var hint: StructuredPlannerHint?
+ var memoryWriteProposals: [RunMemoryWriteProposal]
+ var metadata: [String: String]
+}
+
enum PlannerHintWireCodec {
static func jsonSchema() -> [String: Any] {
+ providerOutputJSONSchema()
+ }
+
+ static func providerOutputJSONSchema() -> [String: Any] {
+ [
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["hint", "memoryWriteProposals"],
+ "properties": [
+ "hint": hintJSONSchema(),
+ "memoryWriteProposals": [
+ "type": "array",
+ "items": memoryWriteProposalJSONSchema()
+ ]
+ ]
+ ]
+ }
+
+ static func hintJSONSchema() -> [String: Any] {
[
"type": "object",
"additionalProperties": false,
@@ -406,6 +460,74 @@ enum PlannerHintWireCodec {
]
}
+ static func decodeProviderOutput(
+ _ text: String,
+ sourceTraceID: String,
+ sourceFrameID: String?,
+ sourceStateID: String?,
+ modelCallID: String,
+ now: RunTraceTimestamp
+ ) throws -> PlannerProviderWireOutput {
+ guard let data = text.data(using: .utf8) else {
+ return PlannerProviderWireOutput(
+ hint: nil,
+ memoryWriteProposals: [],
+ metadata: ["providerOutput.decodeStatus": "invalidUTF8"]
+ )
+ }
+
+ if let object = try JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let hintObject = object["hint"] {
+ let hintData = try JSONSerialization.data(withJSONObject: hintObject)
+ let hint = try decodeHintData(
+ hintData,
+ sourceTraceID: sourceTraceID,
+ sourceFrameID: sourceFrameID,
+ sourceStateID: sourceStateID,
+ modelCallID: modelCallID,
+ now: now
+ )
+ var proposals: [RunMemoryWriteProposal] = []
+ var metadata = [
+ "providerOutput.shape": "hintWithMemoryProposals",
+ "memoryProposal.decodeStatus": "notPresent"
+ ]
+
+ if let proposalsObject = object["memoryWriteProposals"] {
+ let proposalData = try JSONSerialization.data(withJSONObject: proposalsObject)
+ do {
+ proposals = try JSONDecoder().decode([RunMemoryWriteProposal].self, from: proposalData)
+ metadata["memoryProposal.decodeStatus"] = "decoded"
+ } catch {
+ metadata["memoryProposal.decodeStatus"] = "invalid"
+ metadata["memoryProposal.decodeError"] = String(describing: error)
+ }
+ }
+
+ return PlannerProviderWireOutput(
+ hint: hint,
+ memoryWriteProposals: proposals,
+ metadata: metadata
+ )
+ }
+
+ return PlannerProviderWireOutput(
+ hint: try decodeHintData(
+ data,
+ sourceTraceID: sourceTraceID,
+ sourceFrameID: sourceFrameID,
+ sourceStateID: sourceStateID,
+ modelCallID: modelCallID,
+ now: now
+ ),
+ memoryWriteProposals: [],
+ metadata: [
+ "providerOutput.shape": "legacyHintOnly",
+ "memoryProposal.decodeStatus": "notPresent"
+ ]
+ )
+ }
+
static func decodeHint(
_ text: String,
sourceTraceID: String,
@@ -415,6 +537,24 @@ enum PlannerHintWireCodec {
now: RunTraceTimestamp
) throws -> StructuredPlannerHint? {
guard let data = text.data(using: .utf8) else { return nil }
+ return try decodeHintData(
+ data,
+ sourceTraceID: sourceTraceID,
+ sourceFrameID: sourceFrameID,
+ sourceStateID: sourceStateID,
+ modelCallID: modelCallID,
+ now: now
+ )
+ }
+
+ private static func decodeHintData(
+ _ data: Data,
+ sourceTraceID: String,
+ sourceFrameID: String?,
+ sourceStateID: String?,
+ modelCallID: String,
+ now: RunTraceTimestamp
+ ) throws -> StructuredPlannerHint? {
let wire = try JSONDecoder().decode(PlannerHintWireOutput.self, from: data)
guard let preferredActions = actions(from: wire.preferredActions),
let avoidActions = actions(from: wire.avoidActions)
@@ -439,6 +579,97 @@ enum PlannerHintWireCodec {
)
}
+ private static func memoryWriteProposalJSONSchema() -> [String: Any] {
+ [
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id", "proposedBy", "record", "rationale"],
+ "properties": [
+ "id": ["type": "string"],
+ "proposedBy": ["type": "string", "enum": RunMemoryAuthor.allCasesRawValues],
+ "record": memoryRecordJSONSchema(),
+ "rationale": ["type": "string"]
+ ]
+ ]
+ }
+
+ private static func memoryRecordJSONSchema() -> [String: Any] {
+ [
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "id",
+ "scope",
+ "kind",
+ "targetID",
+ "runID",
+ "userID",
+ "value",
+ "createdAt",
+ "expiresAt",
+ "durable",
+ "source",
+ "metadata"
+ ],
+ "properties": [
+ "id": ["type": "string"],
+ "scope": ["type": "string", "enum": RunMemoryScope.allCasesRawValues],
+ "kind": ["type": "string", "enum": RunMemoryKind.allCasesRawValues],
+ "targetID": ["type": ["string", "null"]],
+ "runID": ["type": ["string", "null"]],
+ "userID": ["type": ["string", "null"]],
+ "value": ["type": "string"],
+ "createdAt": timestampJSONSchema(),
+ "expiresAt": ["anyOf": [timestampJSONSchema(), ["type": "null"]]],
+ "durable": ["type": "boolean"],
+ "source": memorySourceJSONSchema(),
+ "metadata": [
+ "type": "object",
+ "additionalProperties": ["type": "string"]
+ ]
+ ]
+ ]
+ }
+
+ private static func memorySourceJSONSchema() -> [String: Any] {
+ [
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "traceID",
+ "frameID",
+ "stateID",
+ "actionID",
+ "plannerHintID",
+ "modelCallID",
+ "eventSequence",
+ "summary"
+ ],
+ "properties": [
+ "traceID": ["type": ["string", "null"]],
+ "frameID": ["type": ["string", "null"]],
+ "stateID": ["type": ["string", "null"]],
+ "actionID": ["type": ["string", "null"]],
+ "plannerHintID": ["type": ["string", "null"]],
+ "modelCallID": ["type": ["string", "null"]],
+ "eventSequence": ["type": ["integer", "null"]],
+ "summary": ["type": "string"]
+ ]
+ ]
+ }
+
+ private static func timestampJSONSchema() -> [String: Any] {
+ [
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["wallClock", "monotonicUptimeNanoseconds"],
+ "properties": [
+ "wallClock": ["type": "number"],
+ "monotonicUptimeNanoseconds": ["type": "integer"]
+ ]
+ ]
+ }
+
private static func actions(from rawValues: [String]) -> [HotLoopActionKind]? {
var actions: [HotLoopActionKind] = []
for rawValue in rawValues {
@@ -491,3 +722,29 @@ private extension RunTraceTimestamp {
)
}
}
+
+private extension RunMemoryAuthor {
+ static var allCasesRawValues: [String] {
+ ["deterministicRuntime", "user", "model"]
+ }
+}
+
+private extension RunMemoryScope {
+ static var allCasesRawValues: [String] {
+ ["run", "target", "user"]
+ }
+}
+
+private extension RunMemoryKind {
+ static var allCasesRawValues: [String] {
+ [
+ "currentGoal",
+ "activeHint",
+ "recentState",
+ "failure",
+ "userInstruction",
+ "safetyStop",
+ "targetFact"
+ ]
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift b/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift
index b5f228e8..0c39c226 100644
--- a/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift
@@ -123,6 +123,7 @@ public enum RunMemoryApprovalIssue: String, Codable, Equatable, Sendable {
case missingUserID
case missingRetention
case unsupportedScope
+ case sensitiveContent
}
public struct RunMemoryWriteProposal: Codable, Equatable, Sendable {
@@ -279,6 +280,10 @@ public enum RunMemoryApprover {
issues.append(.emptyValue)
}
+ if containsSensitiveContent(record.value) {
+ issues.append(.sensitiveContent)
+ }
+
if !record.source.isLinked {
issues.append(.missingSourceLink)
}
@@ -311,4 +316,19 @@ public enum RunMemoryApprover {
decidedAt: decidedAt
)
}
+
+ private static func containsSensitiveContent(_ value: String) -> Bool {
+ let patterns = [
+ #"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}"#,
+ #"\b(?:\d[ -]*?){13,16}\b"#,
+ #"(?i)(password|token|api[_ -]?key)\s*[:=]\s*\S+"#
+ ]
+ let range = NSRange(value.startIndex..<value.endIndex, in: value)
+ return patterns.contains { pattern in
+ guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else {
+ return false
+ }
+ return regex.firstMatch(in: value, range: range) != nil
+ }
+ }
}
diff --git a/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift b/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift
index 23b8858b..19ef5529 100644
--- a/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift
@@ -258,6 +258,7 @@ public struct RunContextPackage: Codable, Equatable, Sendable {
public var activeHints: [RunPlannerHint]
public var recentFailures: [RunFailureSummary]
public var memorySnapshot: RunMemorySnapshot?
+ public var semanticMemoryResults: [RunMemorySemanticResult]
public init(
sessionID: String,
@@ -269,7 +270,8 @@ public struct RunContextPackage: Codable, Equatable, Sendable {
droppedTranscriptCharacterCount: Int = 0,
activeHints: [RunPlannerHint] = [],
recentFailures: [RunFailureSummary] = [],
- memorySnapshot: RunMemorySnapshot? = nil
+ memorySnapshot: RunMemorySnapshot? = nil,
+ semanticMemoryResults: [RunMemorySemanticResult] = []
) {
self.sessionID = sessionID
self.userGoal = userGoal
@@ -281,6 +283,7 @@ public struct RunContextPackage: Codable, Equatable, Sendable {
self.activeHints = activeHints
self.recentFailures = recentFailures
self.memorySnapshot = memorySnapshot
+ self.semanticMemoryResults = semanticMemoryResults
}
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillApprovalLiveRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillApprovalLiveRunner.swift
new file mode 100644
index 00000000..e4d26c19
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/DocumentFormFillApprovalLiveRunner.swift
@@ -0,0 +1,164 @@
+@preconcurrency import AppKit
+import DonkeyContracts
+import Foundation
+
+public enum DocumentFormFillApprovalRunStatus: String, Equatable, Sendable {
+ case completed
+ case partiallyCompleted
+ case noApprovedFields
+ case failedSafe
+}
+
+public struct DocumentFormFillApprovalRunResult: Equatable, Sendable {
+ public var status: DocumentFormFillApprovalRunStatus
+ public var approval: DocumentFormFillApproval
+ public var actionTraces: [ActionEngineCommandTrace]
+ public var metadata: [String: String]
+
+ public init(
+ status: DocumentFormFillApprovalRunStatus,
+ approval: DocumentFormFillApproval,
+ actionTraces: [ActionEngineCommandTrace],
+ metadata: [String: String] = [:]
+ ) {
+ self.status = status
+ self.approval = approval
+ self.actionTraces = actionTraces
+ self.metadata = metadata
+ }
+}
+
+public struct DocumentFormFillApprovalLiveRunner: Sendable {
+ public typealias ActionEngineFactory = @Sendable (LocalAppTaskDefinition) -> ActionEngineGuardrail
+
+ public var planner: DocumentFormFillPlanner
+ public var appController: any LocalAppTaskAppControlling
+ public var availabilityProvider: any LocalAppAvailabilityProviding
+ public var permissionPolicy: ToolCallPolicy
+ public var coordinator: RunCoordinator?
+ public var actionEngineFactory: ActionEngineFactory
+
+ public init(
+ planner: DocumentFormFillPlanner = DocumentFormFillPlanner(),
+ appController: any LocalAppTaskAppControlling = MacLocalAppTaskController(),
+ availabilityProvider: any LocalAppAvailabilityProviding = MacLocalAppAvailabilityProvider(),
+ permissionPolicy: ToolCallPolicy = ToolCallPolicy(
+ allowedCapabilities: ToolCallPolicy.defaultAllowedCapabilities.union([.input]),
+ deniedCapabilities: []
+ ),
+ coordinator: RunCoordinator? = nil,
+ actionEngineFactory: @escaping ActionEngineFactory = LocalAppTaskLiveRunner.accessibilityActionEngine(for:)
+ ) {
+ self.planner = planner
+ self.appController = appController
+ self.availabilityProvider = availabilityProvider
+ self.permissionPolicy = permissionPolicy
+ self.coordinator = coordinator
+ self.actionEngineFactory = actionEngineFactory
+ }
+
+ public func run(
+ plan: DocumentFormFillPlan,
+ definition: LocalAppTaskDefinition,
+ traceID: String,
+ approvedFieldIDs: [String]
+ ) async -> DocumentFormFillApprovalRunResult {
+ let approval = planner.approval(
+ for: plan,
+ traceID: traceID,
+ approvedFieldIDs: Set(approvedFieldIDs)
+ )
+ guard !approval.approvedProposals.isEmpty else {
+ return DocumentFormFillApprovalRunResult(
+ status: .noApprovedFields,
+ approval: approval,
+ actionTraces: [],
+ metadata: ["reason": "noApprovedFields"]
+ )
+ }
+
+ let targetID = LocalAppTaskAdapter(definition: definition).targetID
+ await coordinator?.setTraceID(traceID)
+ _ = await coordinator?.start(
+ RunSession(
+ userGoal: "approve document form fill",
+ targetID: targetID,
+ runtimeProfile: "document-form-fill-approval",
+ permissionPolicy: permissionPolicy
+ )
+ )
+
+ let availability = availabilityProvider.availability(for: definition.targetApp)
+ await coordinator?.recordToolEvent(
+ capability: .input,
+ decision: permissionPolicy.decision(for: .input),
+ toolName: "mac-launch-focus",
+ summary: "Refocusing document app before approved field entry",
+ traceID: traceID,
+ metadata: [
+ "targetApp": definition.targetApp.appName,
+ "bundleIdentifier": definition.targetApp.bundleIdentifier ?? ""
+ ]
+ )
+ _ = await appController.launchOrFocus(
+ definition: definition,
+ availability: availability
+ )
+
+ let commands = LocalAppAccessibilityActionPlanner().fillCommands(
+ approval: approval,
+ definition: definition,
+ issuedAt: Self.now()
+ )
+ let engine = actionEngineFactory(definition)
+ var traces: [ActionEngineCommandTrace] = []
+ for command in commands {
+ await coordinator?.recordToolEvent(
+ capability: .accessibility,
+ decision: permissionPolicy.decision(for: .accessibility),
+ toolName: "mac-accessibility-action-engine",
+ summary: "Executing approved document field entry",
+ traceID: traceID,
+ metadata: [
+ "commandID": command.id,
+ "fieldID": command.metadata["accessibility.nodeID"] ?? ""
+ ]
+ )
+ let trace = await engine.handle(command, permissionPolicy: permissionPolicy)
+ traces.append(trace)
+ guard trace.executed || trace.decision == .projectedDryRun else {
+ break
+ }
+ }
+
+ let executedCount = traces.filter(\.executed).count
+ let status: DocumentFormFillApprovalRunStatus
+ if executedCount == approval.approvedProposals.count {
+ status = .completed
+ await coordinator?.complete(reason: "Approved document form fields filled")
+ } else if executedCount > 0 {
+ status = .partiallyCompleted
+ await coordinator?.pause(reason: "Document form fill partially completed")
+ } else {
+ status = .failedSafe
+ await coordinator?.fail(reason: "Document form fill approval was not executed")
+ }
+
+ return DocumentFormFillApprovalRunResult(
+ status: status,
+ approval: approval,
+ actionTraces: traces,
+ metadata: [
+ "approvedFieldCount": String(approval.approvedProposals.count),
+ "executedCommandCount": String(executedCount)
+ ]
+ )
+ }
+
+ private static func now() -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(),
+ monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift b/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift
index 75988f95..4c7a204a 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/DryRunReflexLoop.swift
@@ -5,6 +5,28 @@ public protocol DryRunFrameSource: Sendable {
func frameBatches() async -> [[HotLoopFrame]]
}
+public protocol DryRunStreamingFrameSource: DryRunFrameSource {
+ func frameBatchStream() -> AsyncStream<[HotLoopFrame]>
+}
+
+public extension DryRunFrameSource {
+ func frameBatchStream() -> AsyncStream<[HotLoopFrame]> {
+ if let streamingSource = self as? any DryRunStreamingFrameSource {
+ return streamingSource.frameBatchStream()
+ }
+
+ return AsyncStream { continuation in
+ Task {
+ for batch in await frameBatches() {
+ guard !Task.isCancelled else { break }
+ continuation.yield(batch)
+ }
+ continuation.finish()
+ }
+ }
+ }
+}
+
public protocol DryRunPerceptionAdapting: Sendable {
func perceive(frame: HotLoopFrame) async -> [HotLoopPerceptionSignal]
}
@@ -123,7 +145,7 @@ public struct DryRunReflexLoop: Sendable {
var latestWorldState: HotLoopWorldState?
var latestAction: HotLoopControllerAction?
- for batch in await frameSource.frameBatches() {
+ for await batch in frameSource.frameBatchStream() {
for frame in batch {
await buffer.offer(frame)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
index 53bfc70d..f664205a 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
@@ -333,16 +333,27 @@ public struct LocalAppAccessibilityActionPlanner: Sendable {
}
public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackend {
- public init() {}
+ public var actionTimeoutNanoseconds: UInt64
+
+ public init(actionTimeoutNanoseconds: UInt64 = 200_000_000) {
+ self.actionTimeoutNanoseconds = actionTimeoutNanoseconds
+ }
public func execute(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {
- await MainActor.run {
- executeOnMainActor(command)
+ do {
+ return try await MacAccessibilityTimeout.run(
+ timeoutNanoseconds: actionTimeoutNanoseconds
+ ) {
+ executeSynchronously(command)
+ }
+ } catch MacAccessibilityTimeoutError.timedOut {
+ return result(command, executed: false, reason: "accessibilityTimedOut")
+ } catch {
+ return result(command, executed: false, reason: String(describing: error))
}
}
- @MainActor
- private func executeOnMainActor(_ command: ActionEngineCommand) -> ActionEngineInputBackendResult {
+ private func executeSynchronously(_ command: ActionEngineCommand) -> ActionEngineInputBackendResult {
guard AXIsProcessTrusted() else {
return result(command, executed: false, reason: "accessibilityNotTrusted")
}
@@ -352,7 +363,7 @@ public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackend
return result(command, executed: false, reason: "missingAccessibilityTarget")
}
guard let bundleIdentifier = command.metadata["bundleIdentifier"],
- let application = NSWorkspace.shared.frontmostApplication,
+ let application = frontmostApplication(),
application.bundleIdentifier == bundleIdentifier
else {
return result(command, executed: false, reason: "targetAppNotFrontmost")
@@ -382,7 +393,12 @@ public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackend
}
}
- @MainActor
+ private func frontmostApplication() -> FrontmostAccessibilityApplication? {
+ Thread.isMainThread
+ ? FrontmostAccessibilityApplication.current()
+ : DispatchQueue.main.sync { FrontmostAccessibilityApplication.current() }
+ }
+
private func resolveElement(nodeID: String, application: AXUIElement) -> AXUIElement? {
let indexes = nodeID
.split(separator: ".")
@@ -398,7 +414,6 @@ public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackend
}
}
- @MainActor
private func windows(from appElement: AXUIElement) -> [AXUIElement] {
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(
@@ -411,7 +426,6 @@ public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackend
return value as? [AXUIElement] ?? []
}
- @MainActor
private func children(from element: AXUIElement) -> [AXUIElement] {
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(
@@ -439,3 +453,19 @@ public struct MacAccessibilityActionEngineInputBackend: ActionEngineInputBackend
)
}
}
+
+private struct FrontmostAccessibilityApplication: Sendable {
+ var processIdentifier: pid_t
+ var bundleIdentifier: String?
+
+ static func current() -> FrontmostAccessibilityApplication? {
+ guard let application = NSWorkspace.shared.frontmostApplication else {
+ return nil
+ }
+
+ return FrontmostAccessibilityApplication(
+ processIdentifier: application.processIdentifier,
+ bundleIdentifier: application.bundleIdentifier
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift
index 9fff27e3..cd302955 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift
@@ -350,6 +350,7 @@ public struct LocalAppTaskAdapter: Sendable {
"taskType": intent.taskType,
"targetApp": definition.targetApp.appName,
"bundleIdentifier": definition.targetApp.bundleIdentifier ?? "",
+ "workflowStepID": idSuffix,
"workflowStepRole": role.rawValue
]) { current, _ in current }
)
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
index cc8f186e..c9ecb50c 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
@@ -245,6 +245,12 @@ public enum BuiltInLocalAppTaskDefinitions {
summary: "Submit the task",
metadata: ["key": "Return"]
),
+ LocalAppTaskWorkflowStepDefinition(
+ id: "select-city-result",
+ role: .submit,
+ summary: "Select the matching city result",
+ metadata: ["key": "Return"]
+ ),
LocalAppTaskWorkflowStepDefinition(
id: "verify-city",
role: .verifyResult,
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
index f2454214..5fe1d944 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
@@ -69,6 +69,7 @@ public struct LocalAppTaskLiveRunner: Sendable {
public var documentFormFillPlanner: DocumentFormFillPlanner
public var actionEngineFactory: ActionEngineFactory
public var permissionPolicy: ToolCallPolicy
+ public var coordinator: RunCoordinator?
public init(
catalog: LocalAppTaskCatalog = .defaultLocal(),
@@ -76,7 +77,11 @@ public struct LocalAppTaskLiveRunner: Sendable {
contextProvider: any LocalAppTaskContextProviding = MacLocalAppTaskContextProvider(),
documentFormFillPlanner: DocumentFormFillPlanner = DocumentFormFillPlanner(),
actionEngineFactory: @escaping ActionEngineFactory = Self.defaultActionEngine(for:),
- permissionPolicy: ToolCallPolicy = ToolCallPolicy(deniedCapabilities: [])
+ permissionPolicy: ToolCallPolicy = ToolCallPolicy(
+ allowedCapabilities: ToolCallPolicy.defaultAllowedCapabilities.union([.input]),
+ deniedCapabilities: []
+ ),
+ coordinator: RunCoordinator? = nil
) {
self.catalog = catalog
self.appController = appController
@@ -84,6 +89,7 @@ public struct LocalAppTaskLiveRunner: Sendable {
self.documentFormFillPlanner = documentFormFillPlanner
self.actionEngineFactory = actionEngineFactory
self.permissionPolicy = permissionPolicy
+ self.coordinator = coordinator
}
public func run(
@@ -107,6 +113,11 @@ public struct LocalAppTaskLiveRunner: Sendable {
let runStartedAt = Self.uptimeMilliseconds()
var runMetadata = metadata
guard resolution.status == .resolved else {
+ await publishUnresolvedRun(
+ command: command,
+ traceID: traceID,
+ resolution: resolution
+ )
return unresolvedResult(
command: command,
traceID: traceID,
@@ -121,6 +132,20 @@ public struct LocalAppTaskLiveRunner: Sendable {
var intent = resolution.intent,
let availability = resolution.availability
else {
+ await publishRunStart(
+ command: command,
+ traceID: traceID,
+ targetID: "local-app-task-incomplete-resolution"
+ )
+ await coordinator?.recordToolEvent(
+ capability: .controller,
+ decision: .deny(reason: "local app task resolution was incomplete"),
+ toolName: "local-app-task-live-runner",
+ summary: "Local app task resolution incomplete",
+ traceID: traceID,
+ metadata: ["reason": "incompleteResolution"]
+ )
+ await coordinator?.fail(reason: "Local app task resolution incomplete")
return LocalAppTaskLiveRunResult(
command: command,
traceID: traceID,
@@ -135,8 +160,20 @@ public struct LocalAppTaskLiveRunner: Sendable {
intent.metadata["traceID"] = traceID
let adapter = catalog.adapter(for: definition)
+ await publishRunStart(
+ command: command,
+ traceID: traceID,
+ targetID: adapter.targetID
+ )
if definition.metadata["guardedLiveDefault"] == "reviewOnly" {
let contextStartedAt = Self.uptimeMilliseconds()
+ await coordinator?.recordToolEvent(
+ capability: .capture,
+ decision: permissionPolicy.decision(for: .capture),
+ toolName: "local-app-task-context",
+ summary: "Captured local app task context",
+ traceID: traceID
+ )
let context = await contextProvider.snapshot()
runMetadata["latency.observationMS"] = Self.formatLatency(
Self.uptimeMilliseconds() - contextStartedAt
@@ -162,6 +199,7 @@ public struct LocalAppTaskLiveRunner: Sendable {
]
)
let initialPlan = adapter.dryRunPlan(for: intent, observation: observation)
+ await coordinator?.complete(reason: "Local app task requires document review")
return LocalAppTaskLiveRunResult(
command: command,
traceID: traceID,
@@ -181,6 +219,17 @@ public struct LocalAppTaskLiveRunner: Sendable {
}
let launchStartedAt = Self.uptimeMilliseconds()
+ await coordinator?.recordToolEvent(
+ capability: .input,
+ decision: permissionPolicy.decision(for: .input),
+ toolName: "mac-launch-focus",
+ summary: "Launching or focusing local app",
+ traceID: traceID,
+ metadata: [
+ "targetApp": definition.targetApp.appName,
+ "bundleIdentifier": definition.targetApp.bundleIdentifier ?? ""
+ ]
+ )
let launchObservation = await appController.launchOrFocus(
definition: definition,
availability: availability
@@ -188,6 +237,7 @@ public struct LocalAppTaskLiveRunner: Sendable {
runMetadata["latency.launchFocusMS"] = Self.formatLatency(Self.uptimeMilliseconds() - launchStartedAt)
let initialPlan = adapter.dryRunPlan(for: intent, observation: launchObservation)
guard initialPlan.canAttemptGuardedLive else {
+ await coordinator?.pause(reason: "Local app task dry-run plan blocked live input")
return LocalAppTaskLiveRunResult(
command: command,
traceID: traceID,
@@ -213,6 +263,17 @@ public struct LocalAppTaskLiveRunner: Sendable {
for (index, actionCommand) in accessibilityCommands.enumerated() {
let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 60))
let actionStartedAt = Self.uptimeMilliseconds()
+ await coordinator?.recordToolEvent(
+ capability: .accessibility,
+ decision: permissionPolicy.decision(for: .accessibility),
+ toolName: "mac-accessibility-action-engine",
+ summary: "Executing guarded Accessibility command",
+ traceID: traceID,
+ metadata: [
+ "commandID": spacedCommand.id,
+ "workflowStepID": spacedCommand.metadata["workflowStepID"] ?? ""
+ ]
+ )
let trace = await accessibilityEngine.handle(
spacedCommand,
permissionPolicy: permissionPolicy
@@ -229,8 +290,9 @@ public struct LocalAppTaskLiveRunner: Sendable {
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"]
+ return workflowStepID(from: trace.command)
})
+ runMetadata["accessibilityHandledStepIDs"] = accessibilityHandledStepIDs.sorted().joined(separator: ",")
let commands = adapter.guardedKeyboardCommandTemplates(
for: intent,
issuedAt: Self.now()
@@ -243,15 +305,45 @@ public struct LocalAppTaskLiveRunner: Sendable {
for (index, actionCommand) in commands.enumerated() {
let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 40))
let actionStartedAt = Self.uptimeMilliseconds()
- let trace = await engine.handle(
+ await coordinator?.recordToolEvent(
+ capability: .input,
+ decision: permissionPolicy.decision(for: .input),
+ toolName: "mac-keyboard-action-engine",
+ summary: "Executing guarded keyboard command",
+ traceID: traceID,
+ metadata: [
+ "commandID": spacedCommand.id,
+ "workflowStepID": spacedCommand.metadata["workflowStepID"] ?? ""
+ ]
+ )
+ var trace = await engine.handle(
spacedCommand,
permissionPolicy: permissionPolicy
)
keyboardActionMS += Self.uptimeMilliseconds() - actionStartedAt
actionTraces.append(trace)
+ if trace.decision == .denied(reason: "focus guard failed") {
+ _ = await appController.launchOrFocus(
+ definition: definition,
+ availability: availability
+ )
+ let retryCommand = spacedCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 40 + 25))
+ trace = await engine.handle(
+ retryCommand,
+ permissionPolicy: permissionPolicy
+ )
+ actionTraces.append(trace)
+ }
guard trace.executed || trace.decision == ActionEngineCommandDecision.projectedDryRun else {
let observationStartedAt = Self.uptimeMilliseconds()
+ await coordinator?.recordToolEvent(
+ capability: .perception,
+ decision: permissionPolicy.decision(for: .perception),
+ toolName: "local-app-observation",
+ summary: "Observing local app after denied action",
+ traceID: traceID
+ )
let finalObservation = await appController.observe(definition: definition)
runMetadata["latency.observationMS"] = Self.formatLatency(
Self.uptimeMilliseconds() - observationStartedAt
@@ -261,6 +353,7 @@ public struct LocalAppTaskLiveRunner: Sendable {
runMetadata["latency.verificationMS"] = Self.formatLatency(
Self.uptimeMilliseconds() - verificationStartedAt
)
+ await coordinator?.fail(reason: "Local app task action was denied")
return LocalAppTaskLiveRunResult(
command: command,
traceID: traceID,
@@ -272,6 +365,9 @@ public struct LocalAppTaskLiveRunner: Sendable {
actionTraces: actionTraces,
metadata: runMetadata.merging([
"reason": "actionDenied",
+ "actionDeniedReason": decisionReason(trace.decision),
+ "actionDeniedCommandID": trace.command.id,
+ "actionDeniedFocusGuardPassed": String(trace.focusGuardPassed),
"latency.keyboardActionMS": Self.formatLatency(keyboardActionMS),
"latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)
]) { current, _ in current }
@@ -282,16 +378,36 @@ public struct LocalAppTaskLiveRunner: Sendable {
try? await Task.sleep(nanoseconds: 700_000_000)
let observationStartedAt = Self.uptimeMilliseconds()
+ await coordinator?.recordToolEvent(
+ capability: .perception,
+ decision: permissionPolicy.decision(for: .perception),
+ toolName: "local-app-observation",
+ summary: "Observing local app for result verification",
+ traceID: traceID
+ )
let finalObservation = await appController.observe(definition: definition)
runMetadata["latency.observationMS"] = Self.formatLatency(Self.uptimeMilliseconds() - observationStartedAt)
let verificationStartedAt = Self.uptimeMilliseconds()
let finalPlan = adapter.dryRunPlan(for: intent, observation: finalObservation)
runMetadata["latency.verificationMS"] = Self.formatLatency(Self.uptimeMilliseconds() - verificationStartedAt)
runMetadata["latency.totalMS"] = Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)
+ if let verificationStep = finalPlan.steps.first(where: { $0.role == .verifyResult }) {
+ runMetadata["verification.summary"] = verificationStep.summary
+ runMetadata["verification.status"] = verificationStep.status.rawValue
+ for (key, value) in verificationStep.metadata {
+ runMetadata["verification.\(key)"] = value
+ }
+ }
+ let status = status(for: finalPlan.terminalState)
+ if status == .completed {
+ await coordinator?.complete(reason: "Local app task completed")
+ } else {
+ await coordinator?.pause(reason: "Local app task needs user review")
+ }
return LocalAppTaskLiveRunResult(
command: command,
traceID: traceID,
- status: status(for: finalPlan.terminalState),
+ status: status,
resolution: resolution,
initialPlan: initialPlan,
finalPlan: finalPlan,
@@ -353,6 +469,54 @@ public struct LocalAppTaskLiveRunner: Sendable {
)
}
+ private func publishUnresolvedRun(
+ command: String,
+ traceID: String,
+ resolution: LocalAppTaskCatalogResolution
+ ) async {
+ await publishRunStart(
+ command: command,
+ traceID: traceID,
+ targetID: resolution.definition.map { LocalAppTaskAdapter(definition: $0).targetID }
+ ?? "local-app-task-unresolved"
+ )
+ await coordinator?.recordToolEvent(
+ capability: .controller,
+ decision: .deny(reason: resolution.metadata["reason"] ?? resolution.status.rawValue),
+ toolName: "local-app-task-catalog",
+ summary: "Local app task could not be resolved",
+ traceID: traceID,
+ metadata: resolution.metadata.merging([
+ "resolution.status": resolution.status.rawValue
+ ]) { current, _ in current }
+ )
+
+ switch resolution.status {
+ case .needsConfirmation:
+ await coordinator?.pause(reason: "Local app task needs confirmation")
+ case .unsupportedCommand, .appUnavailable, .resolved:
+ await coordinator?.fail(reason: "Local app task could not be resolved")
+ }
+ }
+
+ private func publishRunStart(
+ command: String,
+ traceID: String,
+ targetID: String
+ ) async {
+ guard let coordinator else { return }
+
+ await coordinator.setTraceID(traceID)
+ _ = await coordinator.start(
+ RunSession(
+ userGoal: command,
+ targetID: targetID,
+ runtimeProfile: "local-app-task",
+ permissionPolicy: permissionPolicy
+ )
+ )
+ }
+
@MainActor
private func accessibilityCommandTemplates(
intent: TaskIntent,
@@ -399,6 +563,29 @@ public struct LocalAppTaskLiveRunner: Sendable {
}
}
+ private func decisionReason(_ decision: ActionEngineCommandDecision) -> String {
+ switch decision {
+ case .denied(let reason):
+ return reason
+ case .projectedDryRun:
+ return "projectedDryRun"
+ case .executedLive:
+ return "executedLive"
+ }
+ }
+
+ private func workflowStepID(from command: ActionEngineCommand) -> String? {
+ if let workflowStepID = command.metadata["workflowStepID"] {
+ return workflowStepID
+ }
+
+ guard let markerRange = command.id.range(of: "-ax-") else {
+ return command.metadata["workflowStepRole"]
+ }
+
+ return String(command.id[markerRange.upperBound...])
+ }
+
private static func now(advancedByMilliseconds milliseconds: Double = 0) -> RunTraceTimestamp {
let now = ProcessInfo.processInfo.systemUptime
return RunTraceTimestamp(
@@ -452,13 +639,13 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
definition: LocalAppTaskDefinition,
availability: LocalAppAvailability
) async -> LocalAppTaskObservation {
- if let runningApplication = runningApplication(for: definition.targetApp) {
- runningApplication.activate(options: [.activateAllWindows])
- } else if let appURL = availability.appURL {
+ if let appURL = availability.appURL {
await openApplication(at: appURL)
+ } else if let runningApplication = runningApplication(for: definition.targetApp) {
+ runningApplication.activate(options: [.activateAllWindows])
}
- try? await Task.sleep(nanoseconds: 350_000_000)
+ await waitForFrontmostApplication(definition.targetApp)
return await observe(definition: definition)
}
@@ -469,16 +656,6 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
let verificationKey = definition.metadata["verificationTextKey"]
?? definition.verificationEntityName
?? "visibleText"
- async let screenshotObservationTask: LocalAppTaskObservation? = shouldIncludeScreenshotUnderstanding(
- definition: definition
- )
- ? screenshotUnderstandingObservation(
- definition: definition,
- runningApplication: runningApplication,
- isFocused: isFocused,
- verificationKey: verificationKey
- )
- : nil
let accessibilityIndex = accessibilityControlIndex(for: definition, runningApplication: runningApplication)
let visibleText = accessibilityIndex?.visibleText ?? accessibilityVisibleText(for: runningApplication)
var controls: [String: Bool] = Dictionary(
@@ -513,11 +690,20 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
]
)
- guard shouldIncludeScreenshotUnderstanding(definition: definition) else {
+ guard shouldIncludeScreenshotUnderstanding(
+ definition: definition,
+ accessibilityObservation: accessibilityObservation,
+ verificationKey: verificationKey
+ ) else {
return accessibilityObservation
}
- guard let screenshotObservation = await screenshotObservationTask else {
+ guard let screenshotObservation = await screenshotUnderstandingObservation(
+ definition: definition,
+ runningApplication: runningApplication,
+ isFocused: isFocused,
+ verificationKey: verificationKey
+ ) else {
var metadata = accessibilityObservation.metadata
metadata["screenshotUnderstanding.status"] = "unavailable"
return LocalAppTaskObservation(
@@ -546,9 +732,15 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
}
private func shouldIncludeScreenshotUnderstanding(
- definition: LocalAppTaskDefinition
+ definition: LocalAppTaskDefinition,
+ accessibilityObservation: LocalAppTaskObservation,
+ verificationKey: String
) -> Bool {
- definition.observationStrategies.contains(.screenshotForLocalModel)
+ LocalAppTaskObservationFallbackPolicy.shouldUseScreenshotUnderstanding(
+ definition: definition,
+ accessibilityObservation: accessibilityObservation,
+ verificationKey: verificationKey
+ )
}
@MainActor
@@ -670,6 +862,17 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
}
}
+ @MainActor
+ private func waitForFrontmostApplication(_ target: LocalAppTarget) async {
+ let bundleIdentifier = target.bundleIdentifier
+ for _ in 0..<16 {
+ if NSWorkspace.shared.frontmostApplication?.bundleIdentifier == bundleIdentifier {
+ return
+ }
+ try? await Task.sleep(nanoseconds: 125_000_000)
+ }
+ }
+
@MainActor
private func accessibilityVisibleText(for application: NSRunningApplication?) -> String? {
guard AXIsProcessTrusted(),
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swift
new file mode 100644
index 00000000..8a9ff5fb
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swift
@@ -0,0 +1,28 @@
+import DonkeyContracts
+import Foundation
+
+public enum LocalAppTaskObservationFallbackPolicy {
+ public static func shouldUseScreenshotUnderstanding(
+ definition: LocalAppTaskDefinition,
+ accessibilityObservation: LocalAppTaskObservation,
+ verificationKey: String
+ ) -> Bool {
+ guard definition.observationStrategies.contains(.screenshotForLocalModel) else {
+ return false
+ }
+
+ if accessibilityObservation.visibleText[verificationKey]?.isEmpty == false {
+ return false
+ }
+
+ return definition.workflowSteps.contains { step in
+ guard step.role == .focusControl,
+ let controlID = step.metadata["controlID"]
+ else {
+ return false
+ }
+
+ return accessibilityObservation.availableControls[controlID] != true
+ } || accessibilityObservation.visibleText.isEmpty
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
index 8097661a..5bcf3a7a 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
@@ -10,6 +10,7 @@ public enum MacAccessibilitySnapshotCaptureError: Error, Equatable, Sendable {
status: WindowTargetSafetyStatus
)
case accessibilityNotTrusted(windowID: UInt32)
+ case captureTimedOut(windowID: UInt32, timeoutNanoseconds: UInt64)
case captureFailed(windowID: UInt32, reason: String)
}
@@ -47,7 +48,7 @@ public enum MacAccessibilitySnapshotCaptureOutcome: Equatable, Sendable {
case permissionDenied(MacAccessibilityPermissionDeniedResult)
}
-protocol MacAccessibilitySnapshotCapturing {
+protocol MacAccessibilitySnapshotCapturing: Sendable {
func trustStatus() -> MacAccessibilityTrustStatus
func captureTree(
target: MacWindowTargetCandidate,
@@ -59,6 +60,7 @@ public final class MacAccessibilitySnapshotCaptureService {
private let artifactStore: LocalRunArtifactStore
private let windowResolver: MacWindowResolver
private let capturer: any MacAccessibilitySnapshotCapturing
+ private let captureTimeoutNanoseconds: UInt64
public convenience init(artifactStore: LocalRunArtifactStore) {
self.init(
@@ -71,11 +73,13 @@ public final class MacAccessibilitySnapshotCaptureService {
init(
artifactStore: LocalRunArtifactStore,
windowResolver: MacWindowResolver,
- capturer: any MacAccessibilitySnapshotCapturing
+ capturer: any MacAccessibilitySnapshotCapturing,
+ captureTimeoutNanoseconds: UInt64 = 250_000_000
) {
self.artifactStore = artifactStore
self.windowResolver = windowResolver
self.capturer = capturer
+ self.captureTimeoutNanoseconds = captureTimeoutNanoseconds
}
public func captureSnapshot(
@@ -125,12 +129,14 @@ public final class MacAccessibilitySnapshotCaptureService {
let tree: MacAccessibilitySnapshotTree
do {
- tree = try capturer.captureTree(
- target: target,
- limits: limits
- )
+ tree = try await captureTreeWithTimeout(target: target, limits: limits)
} catch let error as MacAccessibilitySnapshotCaptureError {
throw error
+ } catch MacAccessibilityTimeoutError.timedOut(let timeoutNanoseconds) {
+ throw MacAccessibilitySnapshotCaptureError.captureTimedOut(
+ windowID: target.windowID,
+ timeoutNanoseconds: timeoutNanoseconds
+ )
} catch {
throw MacAccessibilitySnapshotCaptureError.captureFailed(
windowID: target.windowID,
@@ -145,6 +151,12 @@ public final class MacAccessibilitySnapshotCaptureService {
totalNodeCount: tree.totalNodeCount,
isTreeTruncated: tree.isTreeTruncated
)
+ if let dialogAssessment = MacAccessibilityNativeDialogDetector().safetyAssessment(for: snapshot) {
+ throw MacAccessibilitySnapshotCaptureError.unsafeTarget(
+ windowID: target.windowID,
+ status: dialogAssessment.status
+ )
+ }
let snapshotData = try Self.encoder().encode(snapshot)
let reservedPath = try await artifactStore.reserveArtifactPath(
runID: runID,
@@ -178,6 +190,19 @@ public final class MacAccessibilitySnapshotCaptureService {
)
}
+ private func captureTreeWithTimeout(
+ target: MacWindowTargetCandidate,
+ limits: MacAccessibilitySnapshotLimits
+ ) async throws -> MacAccessibilitySnapshotTree {
+ let capturer = capturer
+ let captureTimeoutNanoseconds = captureTimeoutNanoseconds
+ return try await MacAccessibilityTimeout.run(
+ timeoutNanoseconds: captureTimeoutNanoseconds
+ ) {
+ try capturer.captureTree(target: target, limits: limits)
+ }
+ }
+
private func permissionDeniedEvent(
summary: RunTraceSummary,
target: MacWindowTargetCandidate
@@ -272,7 +297,115 @@ public final class MacAccessibilitySnapshotCaptureService {
}
}
+public struct MacAccessibilityNativeDialogDetector: Sendable {
+ public init() {}
+
+ public func safetyAssessment(
+ for snapshot: MacAccessibilitySnapshot
+ ) -> WindowTargetSafetyAssessment? {
+ guard let dialogText = dialogTexts(in: snapshot.root).first else {
+ return nil
+ }
+
+ var reasons: [WindowTargetSafetyReason] = [.systemSurface]
+ let haystack = dialogText.lowercased()
+
+ if containsAny(haystack, [
+ "permission",
+ "privacy",
+ "accessibility",
+ "screen recording",
+ "allow",
+ "deny"
+ ]) {
+ reasons.append(.permissionSurface)
+ }
+
+ if containsAny(haystack, [
+ "sign in",
+ "signin",
+ "sign-in",
+ "log in",
+ "login",
+ "authentication",
+ "unlock"
+ ]) {
+ reasons.append(.loginSurface)
+ }
+
+ if containsAny(haystack, [
+ "password",
+ "passcode",
+ "credential",
+ "keychain"
+ ]) {
+ reasons.append(.passwordSurface)
+ }
+
+ if containsAny(haystack, [
+ "payment",
+ "checkout",
+ "billing",
+ "credit card",
+ "apple pay",
+ "purchase"
+ ]) {
+ reasons.append(.paymentSurface)
+ }
+
+ return WindowTargetSafetyAssessment(
+ status: .blocked,
+ reasons: reasons.uniqued(),
+ summary: "Native macOS dialog detected in Accessibility tree"
+ )
+ }
+
+ private func dialogTexts(in node: MacAccessibilitySnapshotNode) -> [String] {
+ let ownText = [node.role, node.title, node.label, node.valueSummary]
+ .compactMap { $0 }
+ .joined(separator: " ")
+ let descendantText = node.children.flatMap(dialogTexts(in:)).joined(separator: " ")
+ let combined = [ownText, descendantText]
+ .filter { !$0.isEmpty }
+ .joined(separator: " ")
+
+ if isDialogRole(node.role) || isDialogText(combined) {
+ return [combined]
+ }
+
+ return node.children.flatMap(dialogTexts(in:))
+ }
+
+ private func isDialogRole(_ role: String?) -> Bool {
+ guard let role else { return false }
+ return role == "AXSheet"
+ || role == "AXDialog"
+ || role == "AXSystemDialog"
+ || role == "AXPopover"
+ }
+
+ private func isDialogText(_ text: String) -> Bool {
+ let normalized = text.lowercased()
+ return normalized.contains("system dialog")
+ || normalized.contains("permission")
+ || normalized.contains("wants to access")
+ || normalized.contains("would like to access")
+ || normalized.contains("screen recording")
+ || normalized.contains("accessibility")
+ }
+
+ private func containsAny(_ value: String, _ needles: [String]) -> Bool {
+ needles.contains { value.contains($0) }
+ }
+}
+
final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {
+ private let maximumTraversalNanoseconds: UInt64
+
+ init(maximumTraversalNanoseconds: UInt64 = 200_000_000) {
+ self.maximumTraversalNanoseconds = maximumTraversalNanoseconds
+ }
+
func trustStatus() -> MacAccessibilityTrustStatus {
AXIsProcessTrusted() ? .trusted : .notTrusted
}
@@ -282,6 +415,8 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit
limits: MacAccessibilitySnapshotLimits
) throws -> MacAccessibilitySnapshotTree {
let application = AXUIElementCreateApplication(target.processID)
+ let deadlineUptime = ProcessInfo.processInfo.systemUptime
+ + Double(maximumTraversalNanoseconds) / 1_000_000_000
let rootElement = resolveWindowElement(
for: target,
in: application
@@ -292,6 +427,7 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit
rootElement,
depth: 0,
limits: limits,
+ deadlineUptime: deadlineUptime,
remainingNodeCount: &remainingNodeCount,
isTreeTruncated: &isTreeTruncated
) ?? RawMacAccessibilitySnapshotNode(
@@ -335,9 +471,15 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit
_ element: AXUIElement,
depth: Int,
limits: MacAccessibilitySnapshotLimits,
+ deadlineUptime: TimeInterval,
remainingNodeCount: inout Int,
isTreeTruncated: inout Bool
) -> RawMacAccessibilitySnapshotNode? {
+ guard !hasTimedOut(deadlineUptime) else {
+ isTreeTruncated = true
+ return nil
+ }
+
guard remainingNodeCount > 0 else {
isTreeTruncated = true
return nil
@@ -348,6 +490,7 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit
for: element,
depth: depth,
limits: limits,
+ deadlineUptime: deadlineUptime,
remainingNodeCount: &remainingNodeCount,
isTreeTruncated: &isTreeTruncated
)
@@ -369,9 +512,15 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit
for element: AXUIElement,
depth: Int,
limits: MacAccessibilitySnapshotLimits,
+ deadlineUptime: TimeInterval,
remainingNodeCount: inout Int,
isTreeTruncated: inout Bool
) -> [RawMacAccessibilitySnapshotNode] {
+ guard !hasTimedOut(deadlineUptime) else {
+ isTreeTruncated = true
+ return []
+ }
+
let childCount = elementArrayCount(
kAXChildrenAttribute as CFString,
from: element
@@ -398,12 +547,17 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit
child,
depth: depth + 1,
limits: limits,
+ deadlineUptime: deadlineUptime,
remainingNodeCount: &remainingNodeCount,
isTreeTruncated: &isTreeTruncated
)
}
}
+ private func hasTimedOut(_ deadlineUptime: TimeInterval) -> Bool {
+ ProcessInfo.processInfo.systemUptime >= deadlineUptime
+ }
+
private func matches(
_ element: AXUIElement,
target: MacWindowTargetCandidate
@@ -633,3 +787,10 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit
return value
}
}
+
+private extension Array where Element: Hashable {
+ func uniqued() -> [Element] {
+ var seen = Set<Element>()
+ return filter { seen.insert($0).inserted }
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilityTimeout.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilityTimeout.swift
new file mode 100644
index 00000000..dc3b80ed
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilityTimeout.swift
@@ -0,0 +1,62 @@
+import Foundation
+
+enum MacAccessibilityTimeoutError: Error, Equatable, Sendable {
+ case timedOut(timeoutNanoseconds: UInt64)
+}
+
+enum MacAccessibilityTimeout {
+ static func run<T: Sendable>(
+ timeoutNanoseconds: UInt64,
+ operation: @escaping @Sendable () throws -> T
+ ) async throws -> T {
+ guard timeoutNanoseconds > 0 else {
+ return try operation()
+ }
+
+ let box = TimeoutContinuationBox<T>()
+ return try await withCheckedThrowingContinuation { continuation in
+ box.install(continuation)
+
+ DispatchQueue.global(qos: .userInitiated).async {
+ do {
+ box.resume(.success(try operation()))
+ } catch {
+ box.resume(.failure(error))
+ }
+ }
+
+ DispatchQueue.global(qos: .userInitiated).asyncAfter(
+ deadline: .now() + .nanoseconds(Int(timeoutNanoseconds))
+ ) {
+ box.resume(.failure(
+ MacAccessibilityTimeoutError.timedOut(timeoutNanoseconds: timeoutNanoseconds)
+ ))
+ }
+ }
+ }
+}
+
+private final class TimeoutContinuationBox<T: Sendable>: @unchecked Sendable {
+ private let lock = NSLock()
+ private var continuation: CheckedContinuation<T, any Error>?
+ private var didResume = false
+
+ func install(_ continuation: CheckedContinuation<T, any Error>) {
+ lock.lock()
+ self.continuation = continuation
+ lock.unlock()
+ }
+
+ func resume(_ result: Result<T, any Error>) {
+ lock.lock()
+ guard !didResume, let continuation else {
+ lock.unlock()
+ return
+ }
+ didResume = true
+ self.continuation = nil
+ lock.unlock()
+
+ continuation.resume(with: result)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacTargetWindowFocusGuard.swift b/apps/Donkey/Sources/DonkeyRuntime/MacTargetWindowFocusGuard.swift
new file mode 100644
index 00000000..06037ce1
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacTargetWindowFocusGuard.swift
@@ -0,0 +1,99 @@
+import DonkeyContracts
+import Foundation
+
+public struct MacTargetWindowFocusGuard: ActionEngineFocusGuard {
+ public var targetID: String
+ public var windowID: UInt32
+ public var processID: Int32?
+ public var expectedBundleIdentifier: String?
+ public var expectedBounds: WindowTargetBounds?
+ public var boundsTolerance: Double
+ public var requireFocusedWindow: Bool
+
+ private let windowResolver: MacWindowResolver
+
+ public init(
+ targetID: String,
+ windowID: UInt32,
+ processID: Int32? = nil,
+ expectedBundleIdentifier: String? = nil,
+ expectedBounds: WindowTargetBounds? = nil,
+ boundsTolerance: Double = 2,
+ requireFocusedWindow: Bool = true,
+ windowResolver: MacWindowResolver = MacWindowResolver()
+ ) {
+ self.targetID = targetID
+ self.windowID = windowID
+ self.processID = processID
+ self.expectedBundleIdentifier = expectedBundleIdentifier
+ self.expectedBounds = expectedBounds
+ self.boundsTolerance = max(0, boundsTolerance)
+ self.requireFocusedWindow = requireFocusedWindow
+ self.windowResolver = windowResolver
+ }
+
+ init(
+ targetID: String,
+ target: MacWindowTargetCandidate,
+ boundsTolerance: Double = 2,
+ requireFocusedWindow: Bool = true,
+ windowResolver: MacWindowResolver = MacWindowResolver()
+ ) {
+ self.init(
+ targetID: targetID,
+ windowID: target.windowID,
+ processID: target.processID,
+ expectedBundleIdentifier: target.bundleIdentifier,
+ expectedBounds: target.bounds,
+ boundsTolerance: boundsTolerance,
+ requireFocusedWindow: requireFocusedWindow,
+ windowResolver: windowResolver
+ )
+ }
+
+ public func targetIsSafeForInput(targetID: String) async -> Bool {
+ guard targetID == self.targetID else { return false }
+ guard let target = windowResolver
+ .enumerateCandidates()
+ .first(where: { $0.windowID == windowID })
+ else {
+ return false
+ }
+
+ guard target.safetyAssessment.status == .allowed,
+ target.isVisible,
+ target.isOnScreen
+ else {
+ return false
+ }
+
+ if let processID, target.processID != processID {
+ return false
+ }
+
+ if let expectedBundleIdentifier,
+ target.bundleIdentifier != expectedBundleIdentifier {
+ return false
+ }
+
+ if requireFocusedWindow, !target.isFocused {
+ return false
+ }
+
+ if let expectedBounds,
+ !target.bounds.matches(expectedBounds, tolerance: boundsTolerance) {
+ return false
+ }
+
+ return true
+ }
+}
+
+private extension WindowTargetBounds {
+ func matches(_ other: WindowTargetBounds, tolerance: Double) -> Bool {
+ abs(x - other.x) <= tolerance
+ && abs(y - other.y) <= tolerance
+ && abs(width - other.width) <= tolerance
+ && abs(height - other.height) <= tolerance
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift b/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift
index 39c45b1c..89a5830e 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift
@@ -15,6 +15,7 @@ struct MacWindowProviderWindow: Equatable, Sendable {
var appName: String?
var bundleIdentifier: String?
var title: String?
+ var knownApplication: MacKnownApplicationIdentity?
var bounds: WindowTargetBounds
var alpha: Double
var layer: Int
@@ -26,6 +27,7 @@ struct MacWindowProviderWindow: Equatable, Sendable {
appName: String? = nil,
bundleIdentifier: String? = nil,
title: String? = nil,
+ knownApplication: MacKnownApplicationIdentity? = nil,
bounds: WindowTargetBounds,
alpha: Double = 1,
layer: Int = 0,
@@ -36,6 +38,7 @@ struct MacWindowProviderWindow: Equatable, Sendable {
self.appName = appName
self.bundleIdentifier = bundleIdentifier
self.title = title
+ self.knownApplication = knownApplication
self.bounds = bounds
self.alpha = alpha
self.layer = layer
@@ -43,6 +46,29 @@ struct MacWindowProviderWindow: Equatable, Sendable {
}
}
+struct MacKnownApplicationIdentity: Equatable, Sendable {
+ var processID: Int32
+ var bundleIdentifier: String?
+ var localizedName: String?
+ var executableName: String?
+
+ init(
+ processID: Int32,
+ bundleIdentifier: String? = nil,
+ localizedName: String? = nil,
+ executableName: String? = nil
+ ) {
+ self.processID = processID
+ self.bundleIdentifier = bundleIdentifier
+ self.localizedName = localizedName
+ self.executableName = executableName
+ }
+}
+
+protocol MacKnownApplicationIdentityProviding {
+ func identitiesByProcessIdentifier() -> [Int32: MacKnownApplicationIdentity]
+}
+
protocol MacWindowMetadataProviding {
func windows() -> [MacWindowProviderWindow]
func frontmostProcessIdentifier() -> Int32?
@@ -225,13 +251,19 @@ public final class MacWindowResolver: @unchecked Sendable {
normalizedOptional(window.appName) == nil
&& normalizedOptional(window.bundleIdentifier) == nil
&& normalizedOptional(window.title) == nil
+ && normalizedOptional(window.knownApplication?.bundleIdentifier) == nil
+ && normalizedOptional(window.knownApplication?.localizedName) == nil
+ && normalizedOptional(window.knownApplication?.executableName) == nil
}
private static func searchableText(for window: MacWindowProviderWindow) -> String {
[
window.appName,
window.bundleIdentifier,
- window.title
+ window.title,
+ window.knownApplication?.bundleIdentifier,
+ window.knownApplication?.localizedName,
+ window.knownApplication?.executableName
]
.compactMap(normalizedOptional)
.joined(separator: " ")
@@ -250,6 +282,14 @@ public final class MacWindowResolver: @unchecked Sendable {
}
private struct CoreGraphicsMacWindowMetadataProvider: MacWindowMetadataProviding {
+ var applicationIdentityProvider: any MacKnownApplicationIdentityProviding
+
+ init(
+ applicationIdentityProvider: any MacKnownApplicationIdentityProviding = NSWorkspaceMacKnownApplicationIdentityProvider()
+ ) {
+ self.applicationIdentityProvider = applicationIdentityProvider
+ }
+
func windows() -> [MacWindowProviderWindow] {
guard let rawWindows = CGWindowListCopyWindowInfo(
[.optionOnScreenOnly, .excludeDesktopElements],
@@ -258,6 +298,7 @@ private struct CoreGraphicsMacWindowMetadataProvider: MacWindowMetadataProviding
return []
}
+ let knownApplications = applicationIdentityProvider.identitiesByProcessIdentifier()
return rawWindows.compactMap { rawWindow in
guard let windowID = rawWindow.uint32Value(for: kCGWindowNumber),
let processID = rawWindow.int32Value(for: kCGWindowOwnerPID),
@@ -266,16 +307,17 @@ private struct CoreGraphicsMacWindowMetadataProvider: MacWindowMetadataProviding
return nil
}
- let bundleIdentifier = NSRunningApplication(
- processIdentifier: processID
- )?.bundleIdentifier
+ let knownApplication = knownApplications[processID]
return MacWindowProviderWindow(
windowID: windowID,
processID: processID,
- appName: rawWindow.stringValue(for: kCGWindowOwnerName),
- bundleIdentifier: bundleIdentifier,
+ appName: rawWindow.stringValue(for: kCGWindowOwnerName)
+ ?? knownApplication?.localizedName
+ ?? knownApplication?.executableName,
+ bundleIdentifier: knownApplication?.bundleIdentifier,
title: rawWindow.stringValue(for: kCGWindowName),
+ knownApplication: knownApplication,
bounds: bounds,
alpha: rawWindow.doubleValue(for: kCGWindowAlpha) ?? 1,
layer: rawWindow.intValue(for: kCGWindowLayer) ?? 0,
@@ -293,6 +335,25 @@ private struct CoreGraphicsMacWindowMetadataProvider: MacWindowMetadataProviding
}
}
+private struct NSWorkspaceMacKnownApplicationIdentityProvider: MacKnownApplicationIdentityProviding {
+ func identitiesByProcessIdentifier() -> [Int32: MacKnownApplicationIdentity] {
+ var identities: [Int32: MacKnownApplicationIdentity] = [:]
+ for application in NSWorkspace.shared.runningApplications {
+ let processID = application.processIdentifier
+ let executableName = application.executableURL?
+ .deletingPathExtension()
+ .lastPathComponent
+ identities[processID] = MacKnownApplicationIdentity(
+ processID: processID,
+ bundleIdentifier: application.bundleIdentifier,
+ localizedName: application.localizedName,
+ executableName: executableName
+ )
+ }
+ return identities
+ }
+}
+
private extension Dictionary where Key == String, Value == Any {
func stringValue(for key: CFString) -> String? {
self[key as String] as? String
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift b/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift
index c997ab27..aa3777f6 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift
@@ -11,6 +11,7 @@ public enum ManualCaptureDebugCommand: Equatable, Sendable {
case installLocalRuntime(LocalRuntimeInstallDebugOptions)
case repairLocalRuntime(LocalModelRuntimeID)
case removeLocalRuntime(LocalModelRuntimeID)
+ case localAppTask(LocalAppTaskDebugOptions)
}
public struct ManualCaptureDebugCaptureOptions: Equatable, Sendable {
@@ -52,6 +53,14 @@ public struct LocalRuntimeInstallDebugOptions: Equatable, Sendable {
}
}
+public struct LocalAppTaskDebugOptions: Equatable, Sendable {
+ public var command: String
+
+ public init(command: String) {
+ self.command = command
+ }
+}
+
public enum ManualCaptureDebugCommandParseError: Error, Equatable, Sendable, CustomStringConvertible {
case conflictingCommands
case missingCommand
@@ -66,7 +75,7 @@ public enum ManualCaptureDebugCommandParseError: Error, Equatable, Sendable, Cus
public var description: String {
switch self {
case .conflictingCommands:
- return "Use only one debug command: --list-window-candidates or --manual-capture."
+ return "Use only one Donkey debug command."
case .missingCommand:
return "Use --list-window-candidates or --manual-capture before capture options."
case .missingValue(let option):
@@ -99,6 +108,8 @@ public enum ManualCaptureDebugCommandParser {
|| argument == "--install-local-runtime"
|| argument == "--repair-local-runtime"
|| argument == "--remove-local-runtime"
+ || argument == "--local-app-task"
+ || argument == "--command"
|| argument == "--window-id"
|| argument == "--run-id"
|| argument == "--trace-id"
@@ -125,6 +136,7 @@ public enum ManualCaptureDebugCommandParser {
var benchmarkMode = ReflexReplayBenchmarkMode.endToEndDryRun
var runtimeID: LocalModelRuntimeID?
var runtimeSource: URL?
+ var localAppTaskCommand: String?
var index = 0
while index < arguments.count {
@@ -157,6 +169,12 @@ public enum ManualCaptureDebugCommandParser {
case "--remove-local-runtime":
try setMode(.removeLocalRuntime, current: &mode)
index += 1
+ case "--local-app-task":
+ try setMode(.localAppTask, current: &mode)
+ index += 1
+ case "--command":
+ localAppTaskCommand = try value(after: argument, in: arguments, at: index)
+ index += 2
case "--window-id":
let value = try value(after: argument, in: arguments, at: index)
guard let parsed = UInt32(value) else {
@@ -210,14 +228,16 @@ public enum ManualCaptureDebugCommandParser {
switch mode {
case .listWindowCandidates:
- guard windowID == nil, runID == nil, traceID == nil, frameCount == 30, benchmarkMode == .endToEndDryRun else {
+ guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
+ benchmarkMode == .endToEndDryRun, localAppTaskCommand == nil
+ else {
throw ManualCaptureDebugCommandParseError.unsupportedOption(
"options are not supported with --list-window-candidates"
)
}
return .listWindowCandidates
case .manualCapture:
- guard frameCount == 30, benchmarkMode == .endToEndDryRun else {
+ guard frameCount == 30, benchmarkMode == .endToEndDryRun, localAppTaskCommand == nil else {
throw ManualCaptureDebugCommandParseError.unsupportedOption(
"benchmark options require --dry-run-latency-report"
)
@@ -230,7 +250,7 @@ public enum ManualCaptureDebugCommandParser {
)
)
case .dryRunLatencyReport:
- guard windowID == nil, runID == nil, traceID == nil else {
+ guard windowID == nil, runID == nil, traceID == nil, localAppTaskCommand == nil else {
throw ManualCaptureDebugCommandParseError.unsupportedOption(
"capture options require --manual-capture"
)
@@ -243,7 +263,8 @@ public enum ManualCaptureDebugCommandParser {
)
case .localRuntimeStatus:
guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil
+ benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil,
+ localAppTaskCommand == nil
else {
throw ManualCaptureDebugCommandParseError.unsupportedOption(
"runtime install options require --install-local-runtime"
@@ -252,7 +273,8 @@ public enum ManualCaptureDebugCommandParser {
return .localRuntimeStatus
case .localRuntimeSupport:
guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil
+ benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil,
+ localAppTaskCommand == nil
else {
throw ManualCaptureDebugCommandParseError.unsupportedOption(
"runtime install options require a runtime lifecycle command"
@@ -261,7 +283,8 @@ public enum ManualCaptureDebugCommandParser {
return .localRuntimeSupport
case .localRuntimeInstructions:
guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil
+ benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil,
+ localAppTaskCommand == nil
else {
throw ManualCaptureDebugCommandParseError.unsupportedOption(
"runtime install options require --install-local-runtime"
@@ -270,7 +293,7 @@ public enum ManualCaptureDebugCommandParser {
return .localRuntimeInstructions
case .installLocalRuntime:
guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun
+ benchmarkMode == .endToEndDryRun, localAppTaskCommand == nil
else {
throw ManualCaptureDebugCommandParseError.unsupportedOption(
"capture or benchmark options are not supported with --install-local-runtime"
@@ -290,7 +313,7 @@ public enum ManualCaptureDebugCommandParser {
)
case .repairLocalRuntime:
guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, runtimeSource == nil
+ benchmarkMode == .endToEndDryRun, runtimeSource == nil, localAppTaskCommand == nil
else {
throw ManualCaptureDebugCommandParseError.unsupportedOption(
"capture, benchmark, or source options are not supported with --repair-local-runtime"
@@ -302,7 +325,7 @@ public enum ManualCaptureDebugCommandParser {
return .repairLocalRuntime(runtimeID)
case .removeLocalRuntime:
guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
- benchmarkMode == .endToEndDryRun, runtimeSource == nil
+ benchmarkMode == .endToEndDryRun, runtimeSource == nil, localAppTaskCommand == nil
else {
throw ManualCaptureDebugCommandParseError.unsupportedOption(
"capture, benchmark, or source options are not supported with --remove-local-runtime"
@@ -312,6 +335,20 @@ public enum ManualCaptureDebugCommandParser {
throw ManualCaptureDebugCommandParseError.missingValue("--runtime-id")
}
return .removeLocalRuntime(runtimeID)
+ case .localAppTask:
+ guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
+ benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil
+ else {
+ throw ManualCaptureDebugCommandParseError.unsupportedOption(
+ "runtime, capture, or benchmark options are not supported with --local-app-task"
+ )
+ }
+ guard let localAppTaskCommand,
+ !localAppTaskCommand.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ else {
+ throw ManualCaptureDebugCommandParseError.missingValue("--command")
+ }
+ return .localAppTask(LocalAppTaskDebugOptions(command: localAppTaskCommand))
}
}
@@ -505,6 +542,24 @@ public enum ManualCaptureDebugCommandFormatter {
]
}
+ public static func lines(
+ status: String,
+ summary: String,
+ traceID: String,
+ metadata: [String: String]
+ ) -> [String] {
+ var lines = [
+ "local app task completed",
+ "status=\(status)",
+ "summary=\(summary)",
+ "traceID=\(traceID)"
+ ]
+ for key in metadata.keys.sorted() {
+ lines.append("\(key)=\(metadata[key] ?? "")")
+ }
+ return lines
+ }
+
public static func errorLine(for error: Error) -> String {
if let parseError = error as? ManualCaptureDebugCommandParseError {
return "manual capture debug error: \(parseError.description)"
@@ -535,4 +590,5 @@ private enum ManualCaptureDebugCommandMode {
case installLocalRuntime
case repairLocalRuntime
case removeLocalRuntime
+ case localAppTask
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift b/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift
index 59ff4354..ed48edc8 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift
@@ -14,7 +14,8 @@ public struct RunContextAssembler: Equatable, Sendable {
transcriptSummary: String = "",
activeHints: [RunPlannerHint] = [],
recentFailures: [RunFailureSummary] = [],
- memorySnapshot: RunMemorySnapshot? = nil
+ memorySnapshot: RunMemorySnapshot? = nil,
+ semanticMemoryResults: [RunMemorySemanticResult] = []
) -> RunContextPackage {
let boundedTranscript = bounded(transcriptSummary)
let validHints = activeHints.filter(\.isValid)
@@ -29,7 +30,8 @@ public struct RunContextAssembler: Equatable, Sendable {
droppedTranscriptCharacterCount: boundedTranscript.droppedCount,
activeHints: validHints,
recentFailures: recentFailures,
- memorySnapshot: boundedMemorySnapshot(memorySnapshot, fallbackHints: validHints, fallbackFailures: recentFailures)
+ memorySnapshot: boundedMemorySnapshot(memorySnapshot, fallbackHints: validHints, fallbackFailures: recentFailures),
+ semanticMemoryResults: boundedSemanticMemoryResults(semanticMemoryResults)
)
}
@@ -65,4 +67,18 @@ public struct RunContextAssembler: Equatable, Sendable {
return snapshot
}
+
+ private func boundedSemanticMemoryResults(
+ _ results: [RunMemorySemanticResult]
+ ) -> [RunMemorySemanticResult] {
+ var promptCharacters = 0
+ var bounded: [RunMemorySemanticResult] = []
+ for result in results.prefix(6) {
+ let nextCharacters = promptCharacters + result.record.value.count
+ guard nextCharacters <= 2_000 else { break }
+ promptCharacters = nextCharacters
+ bounded.append(result)
+ }
+ return bounded
+ }
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
index 1afc0186..684a9d13 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
@@ -186,7 +186,8 @@ public actor RunCoordinator {
transcriptSummary: String = "",
activeHints: [RunPlannerHint] = [],
recentFailures: [RunFailureSummary] = [],
- memorySnapshot: RunMemorySnapshot? = nil
+ memorySnapshot: RunMemorySnapshot? = nil,
+ semanticMemoryResults: [RunMemorySemanticResult] = []
) -> RunContextPackage? {
guard let currentSession else { return nil }
@@ -196,7 +197,8 @@ public actor RunCoordinator {
transcriptSummary: transcriptSummary,
activeHints: activeHints,
recentFailures: recentFailures,
- memorySnapshot: memorySnapshot
+ memorySnapshot: memorySnapshot,
+ semanticMemoryResults: semanticMemoryResults
)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift b/apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift
index ad270008..59aea961 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift
@@ -285,6 +285,8 @@ public actor DryRunSlowPlannerSidecar {
private let unsafeActions: Set<HotLoopActionKind>
private let screenshotReferences: [SlowPlannerScreenshotReference]
private let maxTraceSummaries: Int
+ private let memoryRetriever: SemanticRunMemoryRetriever
+ private let semanticMemoryBudget: RunMemoryRetrievalBudget
private var previousSceneSignature: String?
private var consecutiveFailureCount = 0
@@ -300,7 +302,9 @@ public actor DryRunSlowPlannerSidecar {
triggerPolicy: SlowPlannerTriggerPolicy = SlowPlannerTriggerPolicy(),
unsafeActions: Set<HotLoopActionKind> = [],
screenshotReferences: [SlowPlannerScreenshotReference] = [],
- maxTraceSummaries: Int = 5
+ maxTraceSummaries: Int = 5,
+ memoryRetriever: SemanticRunMemoryRetriever = SemanticRunMemoryRetriever(),
+ semanticMemoryBudget: RunMemoryRetrievalBudget = RunMemoryRetrievalBudget(maxRecords: 4, maxPromptCharacters: 1_200)
) {
self.coordinator = coordinator
self.memory = memory
@@ -310,6 +314,8 @@ public actor DryRunSlowPlannerSidecar {
self.unsafeActions = unsafeActions
self.screenshotReferences = screenshotReferences
self.maxTraceSummaries = max(1, maxTraceSummaries)
+ self.memoryRetriever = memoryRetriever
+ self.semanticMemoryBudget = semanticMemoryBudget
}
public func observe(
@@ -339,12 +345,17 @@ public actor DryRunSlowPlannerSidecar {
let activeHints = await hintBus.summaryHints(now: now)
let summary = Self.worldStateSummary(for: worldState)
await memory?.rememberState(summary)
+ let semanticMemoryResults = await retrieveSemanticMemory(
+ goal: userInstruction ?? summary.summary,
+ memorySnapshot: memorySnapshot
+ )
guard let context = await coordinator.buildContext(
latestWorldState: summary,
activeHints: activeHints,
recentFailures: recentFailures,
- memorySnapshot: memorySnapshot
+ memorySnapshot: memorySnapshot,
+ semanticMemoryResults: semanticMemoryResults
) else {
return
}
@@ -407,6 +418,26 @@ public actor DryRunSlowPlannerSidecar {
}
}
+ private func retrieveSemanticMemory(
+ goal: String,
+ memorySnapshot: RunMemorySnapshot?
+ ) async -> [RunMemorySemanticResult] {
+ guard let records = memorySnapshot?.targetRecords,
+ !records.isEmpty
+ else {
+ return []
+ }
+
+ return await memoryRetriever.retrieve(
+ query: RunMemorySemanticQuery(
+ text: goal,
+ scope: .target,
+ budget: semanticMemoryBudget
+ ),
+ records: records
+ )
+ }
+
private static func worldStateSummary(for state: HotLoopWorldState) -> RunWorldStateSummary {
let signalSummary = state.signalSummaries
.map { "\($0.kind):\($0.observationCount)" }
diff --git a/apps/Donkey/Sources/DonkeyRuntime/TargetWindowContentCalibration.swift b/apps/Donkey/Sources/DonkeyRuntime/TargetWindowContentCalibration.swift
new file mode 100644
index 00000000..e31892aa
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/TargetWindowContentCalibration.swift
@@ -0,0 +1,111 @@
+import DonkeyContracts
+import Foundation
+
+public enum TargetWindowContentCalibrationMode: Equatable, Sendable {
+ case fullWindow
+ case centeredAspectFit(aspectRatioWidthOverHeight: Double)
+}
+
+public struct TargetWindowContentCalibrationRequest: Equatable, Sendable {
+ public var mode: TargetWindowContentCalibrationMode
+ public var minimumInset: Double
+
+ public init(
+ mode: TargetWindowContentCalibrationMode,
+ minimumInset: Double = 0
+ ) {
+ self.mode = mode
+ self.minimumInset = max(0, minimumInset)
+ }
+
+ public static let iPhonePortrait = TargetWindowContentCalibrationRequest(
+ mode: .centeredAspectFit(aspectRatioWidthOverHeight: 9.0 / 19.5)
+ )
+}
+
+public struct TargetWindowContentCalibrationResult: Equatable, Sendable {
+ public var crop: HotLoopCrop
+ public var metadata: [String: String]
+
+ public init(crop: HotLoopCrop, metadata: [String: String]) {
+ self.crop = crop
+ self.metadata = metadata
+ }
+}
+
+public struct TargetWindowContentCalibrator: Sendable {
+ public init() {}
+
+ public func calibrate(
+ target: MacWindowTargetCandidate,
+ capturedImageSize: HotLoopSize,
+ request: TargetWindowContentCalibrationRequest
+ ) -> TargetWindowContentCalibrationResult? {
+ guard capturedImageSize.hasPositiveArea else { return nil }
+
+ let availableWidth = max(0, capturedImageSize.width - request.minimumInset * 2)
+ let availableHeight = max(0, capturedImageSize.height - request.minimumInset * 2)
+ guard availableWidth > 0, availableHeight > 0 else { return nil }
+
+ let bounds: HotLoopRect
+ var metadata = [
+ "contentCalibration.enabled": "true",
+ "contentCalibration.minimumInset": String(request.minimumInset),
+ "contentCalibration.target.isIPhoneMirroring": String(target.isIPhoneMirroring)
+ ]
+
+ switch request.mode {
+ case .fullWindow:
+ bounds = HotLoopRect(
+ x: 0,
+ y: 0,
+ width: capturedImageSize.width,
+ height: capturedImageSize.height,
+ space: .window
+ )
+ metadata["contentCalibration.mode"] = "fullWindow"
+
+ case .centeredAspectFit(let aspectRatio):
+ guard aspectRatio > 0 else { return nil }
+
+ let availableRatio = availableWidth / availableHeight
+ let contentWidth: Double
+ let contentHeight: Double
+ if availableRatio > aspectRatio {
+ contentHeight = availableHeight
+ contentWidth = availableHeight * aspectRatio
+ } else {
+ contentWidth = availableWidth
+ contentHeight = availableWidth / aspectRatio
+ }
+
+ bounds = HotLoopRect(
+ x: request.minimumInset + (availableWidth - contentWidth) / 2,
+ y: request.minimumInset + (availableHeight - contentHeight) / 2,
+ width: contentWidth,
+ height: contentHeight,
+ space: .window
+ )
+ metadata["contentCalibration.mode"] = "centeredAspectFit"
+ metadata["contentCalibration.aspectRatioWidthOverHeight"] = String(aspectRatio)
+ }
+
+ metadata["contentCalibration.bounds.x"] = String(bounds.origin.x)
+ metadata["contentCalibration.bounds.y"] = String(bounds.origin.y)
+ metadata["contentCalibration.bounds.width"] = String(bounds.size.width)
+ metadata["contentCalibration.bounds.height"] = String(bounds.size.height)
+
+ return TargetWindowContentCalibrationResult(
+ crop: HotLoopCrop(
+ id: "target-window-content",
+ bounds: bounds,
+ outputSize: HotLoopSize(
+ width: bounds.size.width,
+ height: bounds.size.height,
+ space: .crop
+ )
+ ),
+ metadata: metadata
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift b/apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift
index 7e53e891..80991405 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/TargetWindowFrameSource.swift
@@ -10,6 +10,7 @@ public struct TargetWindowFrameCaptureRequest: Equatable, Sendable {
public var frameIDPrefix: String
public var maxFrameCount: Int
public var cropBoundsInWindow: HotLoopRect?
+ public var contentCalibration: TargetWindowContentCalibrationRequest?
public var plannerHintID: String?
public init(
@@ -19,6 +20,7 @@ public struct TargetWindowFrameCaptureRequest: Equatable, Sendable {
frameIDPrefix: String = "target-frame",
maxFrameCount: Int,
cropBoundsInWindow: HotLoopRect? = nil,
+ contentCalibration: TargetWindowContentCalibrationRequest? = nil,
plannerHintID: String? = nil
) {
self.selection = selection
@@ -27,6 +29,7 @@ public struct TargetWindowFrameCaptureRequest: Equatable, Sendable {
self.frameIDPrefix = frameIDPrefix
self.maxFrameCount = maxFrameCount
self.cropBoundsInWindow = cropBoundsInWindow
+ self.contentCalibration = contentCalibration
self.plannerHintID = plannerHintID
}
}
@@ -163,6 +166,16 @@ public final class TargetWindowFrameCaptureService: @unchecked Sendable {
let captureEnd = timestampProvider.now()
let copyStart = timestampProvider.now()
+ let pixelSize = HotLoopSize(
+ width: Double(captured.imageWidth),
+ height: Double(captured.imageHeight),
+ space: .window
+ )
+ let calibratedContent = calibratedContent(
+ request: request,
+ target: target,
+ capturedImageSize: pixelSize
+ )
let frame = HotLoopFrame(
id: "\(request.frameIDPrefix)-\(frameIndex + 1)",
traceID: request.traceID,
@@ -176,20 +189,13 @@ public final class TargetWindowFrameCaptureService: @unchecked Sendable {
height: target.bounds.height,
space: .screen
),
- crop: crop(
- request.cropBoundsInWindow,
- fallbackWidth: captured.imageWidth,
- fallbackHeight: captured.imageHeight
- ),
- pixelSize: HotLoopSize(
- width: Double(captured.imageWidth),
- height: Double(captured.imageHeight),
- space: .window
- ),
+ crop: calibratedContent?.crop,
+ pixelSize: pixelSize,
plannerHintID: request.plannerHintID,
metadata: metadata(
target: target,
captured: captured,
+ contentCalibrationMetadata: calibratedContent?.metadata ?? [:],
captureStart: captureStart,
captureEnd: captureEnd,
copyStart: copyStart,
@@ -200,6 +206,32 @@ public final class TargetWindowFrameCaptureService: @unchecked Sendable {
return frame
}
+ private func calibratedContent(
+ request: TargetWindowFrameCaptureRequest,
+ target: MacWindowTargetCandidate,
+ capturedImageSize: HotLoopSize
+ ) -> TargetWindowContentCalibrationResult? {
+ if let cropBoundsInWindow = request.cropBoundsInWindow {
+ return TargetWindowContentCalibrationResult(
+ crop: crop(cropBoundsInWindow),
+ metadata: [
+ "contentCalibration.enabled": "false",
+ "contentCalibration.mode": "explicitCrop"
+ ]
+ )
+ }
+
+ let calibration = request.contentCalibration
+ ?? (target.isIPhoneMirroring ? .iPhonePortrait : nil)
+ guard let calibration else { return nil }
+
+ return TargetWindowContentCalibrator().calibrate(
+ target: target,
+ capturedImageSize: capturedImageSize,
+ request: calibration
+ )
+ }
+
private func selectTarget(
_ selection: MacWindowSelectionRequest,
from candidates: [MacWindowTargetCandidate]
@@ -254,19 +286,13 @@ public final class TargetWindowFrameCaptureService: @unchecked Sendable {
return .clear
}
- private func crop(
- _ cropBoundsInWindow: HotLoopRect?,
- fallbackWidth: Int,
- fallbackHeight: Int
- ) -> HotLoopCrop? {
- guard let cropBoundsInWindow else { return nil }
-
+ private func crop(_ cropBoundsInWindow: HotLoopRect) -> HotLoopCrop {
return HotLoopCrop(
id: "target-window-crop",
bounds: cropBoundsInWindow,
outputSize: HotLoopSize(
- width: min(Double(fallbackWidth), cropBoundsInWindow.size.width),
- height: min(Double(fallbackHeight), cropBoundsInWindow.size.height),
+ width: cropBoundsInWindow.size.width,
+ height: cropBoundsInWindow.size.height,
space: .crop
)
)
@@ -275,6 +301,7 @@ public final class TargetWindowFrameCaptureService: @unchecked Sendable {
private func metadata(
target: MacWindowTargetCandidate,
captured: CapturedTargetWindowFrame,
+ contentCalibrationMetadata: [String: String],
captureStart: RunTraceTimestamp,
captureEnd: RunTraceTimestamp,
copyStart: RunTraceTimestamp,
@@ -298,6 +325,7 @@ public final class TargetWindowFrameCaptureService: @unchecked Sendable {
"capture.encoded": "false",
"capture.artifactWritten": "false"
]
+ metadata.merge(contentCalibrationMetadata) { current, _ in current }
if let appName = target.appName {
metadata["target.appName"] = appName
@@ -336,6 +364,71 @@ public struct TargetWindowFrameSource: DryRunFrameSource {
}
}
+public struct ContinuousTargetWindowFrameSource: DryRunStreamingFrameSource {
+ public let service: TargetWindowFrameCaptureService
+ public let request: TargetWindowFrameCaptureRequest
+ public let minimumFrameIntervalNanoseconds: UInt64
+ public let maximumFrameCount: Int?
+
+ public init(
+ service: TargetWindowFrameCaptureService = TargetWindowFrameCaptureService(),
+ request: TargetWindowFrameCaptureRequest,
+ minimumFrameIntervalNanoseconds: UInt64 = 33_000_000,
+ maximumFrameCount: Int? = nil
+ ) {
+ self.service = service
+ self.request = request
+ self.minimumFrameIntervalNanoseconds = minimumFrameIntervalNanoseconds
+ self.maximumFrameCount = maximumFrameCount
+ }
+
+ public func frameBatches() async -> [[HotLoopFrame]] {
+ guard let maximumFrameCount else { return [] }
+
+ var batches: [[HotLoopFrame]] = []
+ batches.reserveCapacity(maximumFrameCount)
+ for await batch in frameBatchStream() {
+ batches.append(batch)
+ if batches.count >= maximumFrameCount {
+ break
+ }
+ }
+ return batches
+ }
+
+ public func frameBatchStream() -> AsyncStream<[HotLoopFrame]> {
+ AsyncStream { continuation in
+ Task {
+ var emittedFrameCount = 0
+ while !Task.isCancelled {
+ if let maximumFrameCount, emittedFrameCount >= maximumFrameCount {
+ break
+ }
+
+ var frameRequest = request
+ frameRequest.maxFrameCount = 1
+ frameRequest.frameIDPrefix = "\(request.frameIDPrefix)-stream-\(emittedFrameCount + 1)"
+
+ do {
+ let result = try await service.captureFrames(request: frameRequest)
+ for frame in result.frames {
+ continuation.yield([frame])
+ emittedFrameCount += 1
+ }
+ } catch {
+ break
+ }
+
+ if minimumFrameIntervalNanoseconds > 0 {
+ try? await Task.sleep(nanoseconds: minimumFrameIntervalNanoseconds)
+ }
+ }
+ continuation.finish()
+ }
+ }
+ }
+}
+
private final class ScreenCaptureKitTargetWindowFrameCapturer: TargetWindowFrameCapturing {
var captureMethod: WindowScreenshotCaptureMethod {
.screenCaptureKitDesktopIndependentWindow
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index 60941595..70f2c9d6 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -159,6 +159,40 @@ struct AIHarnessAdapterTests {
#expect(result.trace.metadata["localOnly"] == "true")
}
+ @Test
+ func localVoiceTranscriptionAdapterConvertsPCMToParakeetCompatibleWAV() async {
+ let runtime = RecordingVoiceRuntime(
+ transcript: LocalVoiceTranscript(text: "show weather", confidence: 0.9)
+ )
+ let adapter = LocalVoiceTranscriptionAdapter(
+ runtime: runtime,
+ now: fixedClock([10, 20])
+ )
+ let result = await adapter.transcribe(
+ LocalVoiceTranscriptionRequest(
+ audio: LocalVoiceAudioBuffer(
+ id: "audio-pcm",
+ format: "pcm_f32le",
+ sampleRateHz: 48_000,
+ channelCount: 1,
+ durationMS: 4,
+ data: float32LittleEndianData([0, 0.25, -0.25, 0.5, -0.5, 0.1])
+ ),
+ sourceTraceID: "trace-voice-pcm"
+ )
+ )
+ let prepared = await runtime.lastAudio
+
+ #expect(result.trace.status == .completed)
+ #expect(prepared?.format == "wav")
+ #expect(prepared?.sampleRateHz == 16_000)
+ #expect(prepared?.channelCount == 1)
+ #expect(prepared?.metadata["audio.normalization.status"] == "converted")
+ #expect(prepared?.data.prefix(4) == Data("RIFF".utf8))
+ #expect(result.trace.metadata["audio.normalization.status"] == "converted")
+ #expect(result.trace.metadata["audio.prepared.format"] == "wav")
+ }
+
@Test
func processBackedParakeetRuntimeDecodesSidecarTranscript() async throws {
let runtime = ProcessBackedParakeetTranscriptionRuntime(
@@ -435,6 +469,109 @@ struct AIHarnessAdapterTests {
#expect(formatContainer["type"] as? String == "json_schema")
}
+ @Test
+ func openAIAdapterIncludesSelectedSemanticMemoryInPrompt() async throws {
+ let httpClient = FakeAIHTTPClient(
+ data: responseData(
+ outputText: """
+ {"id":"hint-semantic","goal":"avoid hazards","policyName":"planner-policy","priorities":["center lane"],"preferredActions":["wait"],"avoidActions":[],"confidence":0.82,"expiryMilliseconds":5000}
+ """
+ ),
+ statusCode: 200
+ )
+ let adapter = OpenAIPlannerHintAdapter(
+ router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "planner", modelID: "gpt-5.2")])),
+ httpClient: httpClient,
+ environment: ["OPENAI_API_KEY": "test-key"],
+ targetMemoryStore: nil
+ )
+ var request = adapterRequest()
+ request.context.semanticMemoryResults = [
+ RunMemorySemanticResult(
+ record: memoryRecord(
+ id: "memory-weather",
+ value: "Weather app search accepts city names.",
+ targetID: "target-1"
+ ),
+ relevance: 0.91,
+ embeddingModelID: "test-embedding"
+ )
+ ]
+
+ _ = await adapter.generatePlannerHint(request)
+
+ let body = try #require(httpClient.requests.first?.httpBodyJSONObject)
+ let input = try #require(body["input"] as? [[String: Any]])
+ let firstInput = try #require(input.first)
+ let content = try #require(firstInput["content"] as? [[String: Any]])
+ let prompt = try #require(content.first?["text"] as? String)
+ #expect(prompt.contains("semantic_memory: memory-weather(0.91): Weather app search accepts city names."))
+ }
+
+ @Test
+ func openAIAdapterPersistsProviderMemoryProposalsWithValidatedHint() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let store = try TargetMemoryJSONLStore(baseDirectory: root)
+ let httpClient = FakeAIHTTPClient(
+ data: responseData(
+ outputText: providerOutput(
+ hintID: "hint-memory",
+ memoryWriteProposals: [
+ providerMemoryProposalJSON(
+ proposalID: "proposal-1",
+ recordID: "memory-1",
+ targetID: "target-1"
+ )
+ ]
+ )
+ ),
+ statusCode: 200
+ )
+ let adapter = OpenAIPlannerHintAdapter(
+ router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "planner", modelID: "gpt-5.2")])),
+ httpClient: httpClient,
+ environment: ["OPENAI_API_KEY": "test-key"],
+ targetMemoryStore: store
+ )
+
+ let result = await adapter.generatePlannerHint(adapterRequest())
+ let records = try await store.records(targetID: "target-1")
+
+ #expect(result.hint?.id == "hint-memory")
+ #expect(result.trace.status == .completed)
+ #expect(result.memoryWriteDecisions.count == 1)
+ #expect(result.memoryWriteDecisions.first?.approval.approved == true)
+ #expect(records.map(\.id) == ["memory-1"])
+ #expect(result.trace.metadata["memoryProposal.count"] == "1")
+ #expect(result.trace.metadata["memoryProposal.persistedCount"] == "1")
+ }
+
+ @Test
+ func openAIAdapterKeepsHintWhenMemoryProposalPayloadIsMalformed() async {
+ let httpClient = FakeAIHTTPClient(
+ data: responseData(
+ outputText: """
+ {"hint":{"id":"hint-only","goal":"recover","policyName":"planner-policy","priorities":["observe"],"preferredActions":["wait"],"avoidActions":[],"confidence":0.82,"expiryMilliseconds":5000},"memoryWriteProposals":[{}]}
+ """
+ ),
+ statusCode: 200
+ )
+ let adapter = OpenAIPlannerHintAdapter(
+ router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "planner", modelID: "gpt-5.2")])),
+ httpClient: httpClient,
+ environment: ["OPENAI_API_KEY": "test-key"],
+ targetMemoryStore: nil
+ )
+
+ let result = await adapter.generatePlannerHint(adapterRequest())
+
+ #expect(result.hint?.id == "hint-only")
+ #expect(result.trace.status == .completed)
+ #expect(result.memoryWriteDecisions.isEmpty)
+ #expect(result.trace.metadata["memoryProposal.decodeStatus"] == "invalid")
+ }
+
@Test
func openAIAdapterHandlesMissingCredentialsRateLimitAndInvalidOutput() async {
let adapter = OpenAIPlannerHintAdapter(
@@ -696,6 +833,25 @@ struct AIHarnessAdapterTests {
return Data("{\"model\":\"qwen3:8b\",\"response\":\"\(escaped)\",\"done\":true}".utf8)
}
+ private func providerOutput(
+ hintID: String,
+ memoryWriteProposals: [String]
+ ) -> String {
+ """
+ {"hint":{"id":"\(hintID)","goal":"avoid hazards","policyName":"planner-policy","priorities":["center lane"],"preferredActions":["wait"],"avoidActions":[],"confidence":0.82,"expiryMilliseconds":5000},"memoryWriteProposals":[\(memoryWriteProposals.joined(separator: ","))]}
+ """
+ }
+
+ private func providerMemoryProposalJSON(
+ proposalID: String,
+ recordID: String,
+ targetID: String
+ ) -> String {
+ """
+ {"id":"\(proposalID)","proposedBy":"model","record":{"id":"\(recordID)","scope":"target","kind":"targetFact","targetID":"\(targetID)","value":"Weather app search accepts city names.","createdAt":{"wallClock":0.01,"monotonicUptimeNanoseconds":10000000},"expiresAt":{"wallClock":1.0,"monotonicUptimeNanoseconds":1000000000},"durable":false,"source":{"traceID":"trace-1","summary":"provider proposal test"},"metadata":{}},"rationale":"provider decoded"}
+ """
+ }
+
private func slowPlannerSnapshot() -> SlowPlannerSnapshot {
let observedAt = timestamp(10)
let context = RunContextPackage(
@@ -795,6 +951,22 @@ struct AIHarnessAdapterTests {
metadata: metadata
)
}
+
+ private func float32LittleEndianData(_ samples: [Float]) -> Data {
+ var data = Data(capacity: samples.count * MemoryLayout<UInt32>.size)
+ for sample in samples {
+ var bits = sample.bitPattern.littleEndian
+ data.append(Data(bytes: &bits, count: MemoryLayout<UInt32>.size))
+ }
+ return data
+ }
+
+ private func temporaryDirectory() -> URL {
+ FileManager.default.temporaryDirectory.appendingPathComponent(
+ "DonkeyAIHarnessAdapterTests-\(UUID().uuidString)",
+ isDirectory: true
+ )
+ }
}
private final class FixedTraceClock: @unchecked Sendable {
@@ -826,6 +998,23 @@ private struct FakeVoiceRuntime: LocalVoiceTranscriptionRuntime {
}
}
+private actor RecordingVoiceRuntime: LocalVoiceTranscriptionRuntime {
+ var transcript: LocalVoiceTranscript
+ private(set) var lastAudio: LocalVoiceAudioBuffer?
+
+ init(transcript: LocalVoiceTranscript) {
+ self.transcript = transcript
+ }
+
+ func transcribe(
+ audio: LocalVoiceAudioBuffer,
+ model: AIModelRegistryEntry
+ ) async throws -> LocalVoiceTranscript {
+ lastAudio = audio
+ return transcript
+ }
+}
+
private struct FakeSidecarRunner: LocalJSONSidecarRunning {
var result: LocalJSONSidecarResult
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
index d39eae33..85a86f9a 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
@@ -97,6 +97,7 @@ struct LocalAppTaskTests {
.focusControl,
.enterText,
.submit,
+ .submit,
.verifyResult
])
#expect(plan.steps.last?.status == .blocked)
@@ -109,8 +110,8 @@ struct LocalAppTaskTests {
for: intent,
issuedAt: timestamp(100)
)
- #expect(commands.map(\.kind) == [.key, .key, .key])
- #expect(commands.map(\.key) == ["Command+F", "San Francisco", "Return"])
+ #expect(commands.map(\.kind) == [.key, .key, .key, .key])
+ #expect(commands.map(\.key) == ["Command+F", "San Francisco", "Return", "Return"])
#expect(commands[1].metadata["workflowStepRole"] == "enterText")
#expect(commands[1].metadata["text"] == "San Francisco")
#expect(commands[1].metadata["bundleIdentifier"] == "com.apple.weather")
@@ -422,13 +423,140 @@ struct LocalAppTaskTests {
#expect(result.status == .completed)
#expect(result.finalPlan?.terminalState == .completed)
- #expect(result.actionTraces.count == 3)
+ #expect(result.actionTraces.count == 4)
#expect(result.actionTraces.allSatisfy { $0.executed })
- #expect(await backend.executedKeys() == ["Command+F", "San Francisco", "Return"])
+ #expect(await backend.executedKeys() == ["Command+F", "San Francisco", "Return", "Return"])
#expect(controller.launchCount == 1)
#expect(controller.observeCount == 1)
}
+ @Test @MainActor
+ func liveRunnerPublishesCoordinatorEventsForGuardedRun() async throws {
+ let backend = RecordingLocalAppTaskInputBackend()
+ let controller = FakeLocalAppTaskAppController(
+ launchObservation: LocalAppTaskObservation(
+ appIsRunning: true,
+ appIsFocused: true,
+ availableControls: ["search": true],
+ confidence: 0.5
+ ),
+ finalObservation: LocalAppTaskObservation(
+ appIsRunning: true,
+ appIsFocused: true,
+ availableControls: ["search": true],
+ visibleText: ["city": "San Francisco, CA"],
+ confidence: 0.92
+ )
+ )
+ let coordinator = RunCoordinator()
+ let catalog = LocalAppTaskCatalog(
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])
+ )
+ let runner = LocalAppTaskLiveRunner(
+ catalog: catalog,
+ appController: controller,
+ actionEngineFactory: { _ in
+ ActionEngineGuardrail(
+ configuration: ActionEngineConfiguration(liveInputEnabled: true),
+ inputBackend: backend
+ )
+ },
+ permissionPolicy: ToolCallPolicy(deniedCapabilities: []),
+ coordinator: coordinator
+ )
+
+ let result = await runner.run(command: "show me the weather for SF", traceID: "trace-live-task-events")
+ let events = await coordinator.events()
+
+ #expect(result.status == .completed)
+ #expect(events.contains { $0.stream == .lifecycle })
+ #expect(events.contains { $0.stream == .tool && $0.summary == "Launching or focusing local app" })
+ #expect(events.contains { $0.stream == .tool && $0.summary == "Executing guarded keyboard command" })
+ #expect(events.last?.summary == "Run completed")
+ }
+
+ @Test
+ func screenshotUnderstandingIsOnlyUsedWhenAccessibilityIsInsufficient() {
+ let definition = BuiltInLocalAppTaskDefinitions.weatherLookup
+
+ #expect(LocalAppTaskObservationFallbackPolicy.shouldUseScreenshotUnderstanding(
+ definition: definition,
+ accessibilityObservation: LocalAppTaskObservation(
+ appIsRunning: true,
+ appIsFocused: true,
+ availableControls: ["search": true],
+ visibleText: ["city": "San Francisco"],
+ confidence: 0.9
+ ),
+ verificationKey: "city"
+ ) == false)
+
+ #expect(LocalAppTaskObservationFallbackPolicy.shouldUseScreenshotUnderstanding(
+ definition: definition,
+ accessibilityObservation: LocalAppTaskObservation(
+ appIsRunning: true,
+ appIsFocused: true,
+ availableControls: [:],
+ visibleText: [:],
+ confidence: 0.4
+ ),
+ verificationKey: "city"
+ ) == true)
+ }
+
+ @Test @MainActor
+ func documentApprovalRunnerExecutesOnlyApprovedFields() async throws {
+ let backend = RecordingLocalAppTaskInputBackend()
+ let controller = FakeLocalAppTaskAppController(
+ launchObservation: LocalAppTaskObservation(appIsRunning: true, appIsFocused: true),
+ finalObservation: LocalAppTaskObservation(appIsRunning: true, appIsFocused: true)
+ )
+ let plan = DocumentFormFillPlan(
+ status: .readyForReview,
+ proposals: [
+ DocumentFormFillProposal(
+ fieldID: "ax-1.1",
+ fieldLabel: "Name",
+ proposedValue: "Ada Lovelace",
+ sourceKey: "Name",
+ confidence: 0.94
+ ),
+ DocumentFormFillProposal(
+ fieldID: "ax-1.2",
+ fieldLabel: "Address",
+ proposedValue: "12 Algorithm Ave",
+ sourceKey: "Address",
+ confidence: 0.94
+ )
+ ]
+ )
+ let coordinator = RunCoordinator()
+ let runner = DocumentFormFillApprovalLiveRunner(
+ appController: controller,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Preview"]),
+ coordinator: coordinator,
+ actionEngineFactory: { _ in
+ ActionEngineGuardrail(
+ configuration: ActionEngineConfiguration(liveInputEnabled: true),
+ inputBackend: backend
+ )
+ }
+ )
+
+ let result = await runner.run(
+ plan: plan,
+ definition: BuiltInLocalAppTaskDefinitions.documentFormFill,
+ traceID: "trace-document-approval",
+ approvedFieldIDs: ["ax-1.1"]
+ )
+
+ #expect(result.status == .completed)
+ #expect(result.approval.approvedProposals.map(\.fieldID) == ["ax-1.1"])
+ #expect(await backend.executedKeys() == ["Ada Lovelace"])
+ #expect(controller.launchCount == 1)
+ }
+
private func parser() -> LocalAppTaskIntentParser {
LocalAppTaskIntentParser(taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults)
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MacAccessibilitySnapshotCaptureServiceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MacAccessibilitySnapshotCaptureServiceTests.swift
index 09a35a0c..714ecb27 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/MacAccessibilitySnapshotCaptureServiceTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MacAccessibilitySnapshotCaptureServiceTests.swift
@@ -351,12 +351,108 @@ struct MacAccessibilitySnapshotCaptureServiceTests {
#expect(capturer.capturedWindowIDs == [10])
}
+ @Test
+ func captureTimeoutFailsWithoutWaitingForBlockedAccessibilityRead() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ _ = try await store.prepareRun(
+ session: RunSession(id: "run-ax-timeout", userGoal: "capture", targetID: "target-1"),
+ traceID: "trace-ax-timeout"
+ )
+ let capturer = FakeMacAccessibilitySnapshotCapturer(delayNanoseconds: 75_000_000)
+ let service = makeService(
+ store: store,
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Notes")
+ ],
+ frontmostProcessID: 100,
+ capturer: capturer,
+ captureTimeoutNanoseconds: 1_000_000
+ )
+ let started = ProcessInfo.processInfo.systemUptime
+
+ do {
+ _ = try await service.captureSnapshot(
+ runID: "run-ax-timeout",
+ artifactID: "accessibility-timeout"
+ )
+ Issue.record("Expected capture timeout")
+ } catch MacAccessibilitySnapshotCaptureError.captureTimedOut(let windowID, let timeoutNanoseconds) {
+ #expect(windowID == 10)
+ #expect(timeoutNanoseconds == 1_000_000)
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+
+ #expect(ProcessInfo.processInfo.systemUptime - started < 0.05)
+ let summary = try await store.summary(runID: "run-ax-timeout")
+ #expect(summary.artifacts.isEmpty)
+ }
+
+ @Test
+ func nativeDialogInAccessibilityTreeFailsAsSafetyStop() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ _ = try await store.prepareRun(
+ session: RunSession(id: "run-ax-dialog", userGoal: "capture", targetID: "target-1"),
+ traceID: "trace-ax-dialog"
+ )
+ let tree = MacAccessibilitySnapshotTreeBuilder.build(
+ root: RawMacAccessibilitySnapshotNode(
+ role: "AXWindow",
+ title: "Game",
+ children: [
+ RawMacAccessibilitySnapshotNode(
+ role: "AXSheet",
+ title: "Screen Recording Permission",
+ children: [
+ RawMacAccessibilitySnapshotNode(role: "AXButton", title: "Allow"),
+ RawMacAccessibilitySnapshotNode(role: "AXButton", title: "Deny")
+ ]
+ )
+ ]
+ ),
+ limits: MacAccessibilitySnapshotLimits(maxDepth: 3)
+ )
+ let capturer = FakeMacAccessibilitySnapshotCapturer(tree: tree)
+ let service = makeService(
+ store: store,
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Game")
+ ],
+ frontmostProcessID: 100,
+ capturer: capturer
+ )
+
+ do {
+ _ = try await service.captureSnapshot(
+ runID: "run-ax-dialog",
+ artifactID: "accessibility-dialog"
+ )
+ Issue.record("Expected native dialog to be refused")
+ } catch MacAccessibilitySnapshotCaptureError.unsafeTarget(let windowID, let status) {
+ #expect(windowID == 10)
+ #expect(status == .blocked)
+ } catch {
+ Issue.record("Unexpected error: \(error)")
+ }
+
+ let summary = try await store.summary(runID: "run-ax-dialog")
+ #expect(summary.artifacts.isEmpty)
+ #expect(capturer.capturedWindowIDs == [10])
+ }
+
private func makeService(
store: LocalRunArtifactStore,
windows: [MacWindowProviderWindow],
frontmostProcessID: Int32? = nil,
focusedWindowID: UInt32? = nil,
- capturer: FakeMacAccessibilitySnapshotCapturer
+ capturer: FakeMacAccessibilitySnapshotCapturer,
+ captureTimeoutNanoseconds: UInt64 = 250_000_000
) -> MacAccessibilitySnapshotCaptureService {
MacAccessibilitySnapshotCaptureService(
artifactStore: store,
@@ -367,7 +463,8 @@ struct MacAccessibilitySnapshotCaptureServiceTests {
focusedWindowID: focusedWindowID
)
),
- capturer: capturer
+ capturer: capturer,
+ captureTimeoutNanoseconds: captureTimeoutNanoseconds
)
}
@@ -446,10 +543,11 @@ struct MacAccessibilitySnapshotCaptureServiceTests {
}
}
-private final class FakeMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {
+private final class FakeMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing, @unchecked Sendable {
var trust: MacAccessibilityTrustStatus
var tree: MacAccessibilitySnapshotTree
var error: Error?
+ var delayNanoseconds: UInt64
var capturedWindowIDs: [UInt32] = []
init(
@@ -458,11 +556,13 @@ private final class FakeMacAccessibilitySnapshotCapturer: MacAccessibilitySnapsh
root: RawMacAccessibilitySnapshotNode(role: "AXWindow", title: "Window"),
limits: .default
),
- error: Error? = nil
+ error: Error? = nil,
+ delayNanoseconds: UInt64 = 0
) {
self.trust = trustStatus
self.tree = tree
self.error = error
+ self.delayNanoseconds = delayNanoseconds
}
func trustStatus() -> MacAccessibilityTrustStatus {
@@ -474,6 +574,9 @@ private final class FakeMacAccessibilitySnapshotCapturer: MacAccessibilitySnapsh
limits: MacAccessibilitySnapshotLimits
) throws -> MacAccessibilitySnapshotTree {
capturedWindowIDs.append(target.windowID)
+ if delayNanoseconds > 0 {
+ Thread.sleep(forTimeInterval: Double(delayNanoseconds) / 1_000_000_000)
+ }
if let error {
throw error
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MacWindowResolverTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MacWindowResolverTests.swift
index 7feebf8c..2a6f32c4 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/MacWindowResolverTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MacWindowResolverTests.swift
@@ -222,6 +222,117 @@ struct MacWindowResolverTests {
#expect(candidates.first?.safetyAssessment.status == .allowed)
}
+ @Test
+ func iPhoneMirroringHintCanComeFromRuntimeAppIdentity() {
+ let resolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(
+ windowID: 8,
+ processID: 800,
+ appName: nil,
+ bundleIdentifier: nil,
+ title: nil,
+ knownApplication: MacKnownApplicationIdentity(
+ processID: 800,
+ bundleIdentifier: "com.apple.ScreenContinuity",
+ localizedName: "iPhone Mirroring",
+ executableName: "ScreenContinuity"
+ )
+ )
+ ],
+ frontmostProcessID: 800
+ )
+ )
+
+ let candidate = resolver.enumerateCandidates().first
+
+ #expect(candidate?.windowID == 8)
+ #expect(candidate?.isIPhoneMirroring == true)
+ #expect(candidate?.safetyAssessment.status == .allowed)
+ }
+
+ @Test
+ func targetWindowFocusGuardAllowsOnlySameFocusedSafeWindow() async {
+ let resolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(
+ windowID: 44,
+ processID: 440,
+ appName: "iPhone Mirroring",
+ bundleIdentifier: "com.apple.ScreenContinuity",
+ bounds: WindowTargetBounds(x: 10, y: 20, width: 300, height: 600)
+ )
+ ],
+ frontmostProcessID: 440,
+ focusedWindowID: 44
+ )
+ )
+ let guardrail = MacTargetWindowFocusGuard(
+ targetID: "target-iphone",
+ windowID: 44,
+ processID: 440,
+ expectedBundleIdentifier: "com.apple.ScreenContinuity",
+ expectedBounds: WindowTargetBounds(x: 10, y: 20, width: 300, height: 600),
+ windowResolver: resolver
+ )
+
+ #expect(await guardrail.targetIsSafeForInput(targetID: "target-iphone"))
+ #expect(!(await guardrail.targetIsSafeForInput(targetID: "other-target")))
+ }
+
+ @Test
+ func targetWindowFocusGuardRejectsFocusLossAndMovedWindow() async {
+ let unfocusedResolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(
+ windowID: 44,
+ processID: 440,
+ appName: "iPhone Mirroring",
+ bundleIdentifier: "com.apple.ScreenContinuity",
+ bounds: WindowTargetBounds(x: 10, y: 20, width: 300, height: 600)
+ )
+ ],
+ frontmostProcessID: nil,
+ focusedWindowID: nil
+ )
+ )
+ let movedResolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(
+ windowID: 44,
+ processID: 440,
+ appName: "iPhone Mirroring",
+ bundleIdentifier: "com.apple.ScreenContinuity",
+ bounds: WindowTargetBounds(x: 60, y: 20, width: 300, height: 600)
+ )
+ ],
+ frontmostProcessID: 440,
+ focusedWindowID: 44
+ )
+ )
+
+ #expect(!(await MacTargetWindowFocusGuard(
+ targetID: "target-iphone",
+ windowID: 44,
+ processID: 440,
+ expectedBundleIdentifier: "com.apple.ScreenContinuity",
+ expectedBounds: WindowTargetBounds(x: 10, y: 20, width: 300, height: 600),
+ windowResolver: unfocusedResolver
+ ).targetIsSafeForInput(targetID: "target-iphone")))
+ #expect(!(await MacTargetWindowFocusGuard(
+ targetID: "target-iphone",
+ windowID: 44,
+ processID: 440,
+ expectedBundleIdentifier: "com.apple.ScreenContinuity",
+ expectedBounds: WindowTargetBounds(x: 10, y: 20, width: 300, height: 600),
+ windowResolver: movedResolver
+ ).targetIsSafeForInput(targetID: "target-iphone")))
+ }
+
@Test
func safetyClassificationMarksSensitiveAndUnknownSurfaces() {
let resolver = MacWindowResolver(
@@ -307,6 +418,7 @@ struct MacWindowResolverTests {
appName: String? = nil,
bundleIdentifier: String? = nil,
title: String? = nil,
+ knownApplication: MacKnownApplicationIdentity? = nil,
bounds: WindowTargetBounds = WindowTargetBounds(
x: 0,
y: 0,
@@ -323,6 +435,7 @@ struct MacWindowResolverTests {
appName: appName,
bundleIdentifier: bundleIdentifier,
title: title,
+ knownApplication: knownApplication,
bounds: bounds,
alpha: alpha,
layer: layer,
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift
index e3e37b11..3d565c03 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift
@@ -96,6 +96,22 @@ struct ManualCaptureDebugCommandTests {
) == .removeLocalRuntime(.yoloSegmenter))
}
+ @Test
+ func localAppTaskCommandParsesSubmittedCommand() throws {
+ let command = try ManualCaptureDebugCommandParser.parse(
+ arguments: [
+ "Donkey",
+ "--local-app-task",
+ "--command",
+ "show me the weather for SF"
+ ]
+ )
+
+ #expect(command == .localAppTask(
+ LocalAppTaskDebugOptions(command: "show me the weather for SF")
+ ))
+ }
+
@Test
func invalidLocalRuntimeIDReturnsCommandError() throws {
#expect(throws: ManualCaptureDebugCommandParseError.invalidRuntimeID("weather")) {
@@ -340,7 +356,7 @@ private final class FakeWindowScreenshotCapturer: WindowScreenshotCapturing {
}
}
-private final class FakeMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {
+private final class FakeMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing, @unchecked Sendable {
var trust: MacAccessibilityTrustStatus
var tree: MacAccessibilitySnapshotTree
var capturedWindowIDs: [UInt32] = []
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualTargetContextCaptureServiceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualTargetContextCaptureServiceTests.swift
index 57b20c0b..5a113379 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualTargetContextCaptureServiceTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualTargetContextCaptureServiceTests.swift
@@ -500,7 +500,7 @@ private final class FakeWindowScreenshotCapturer: WindowScreenshotCapturing {
}
}
-private final class FakeMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {
+private final class FakeMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing, @unchecked Sendable {
var trust: MacAccessibilityTrustStatus
var tree: MacAccessibilitySnapshotTree
var error: Error?
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/RunMemoryStoreTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/RunMemoryStoreTests.swift
index 049ba05f..d5add0de 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/RunMemoryStoreTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/RunMemoryStoreTests.swift
@@ -28,6 +28,30 @@ struct RunMemoryStoreTests {
#expect(approval.issues == [.missingRetention, .missingSourceLink])
}
+ @Test
+ func deterministicApproverRejectsSensitiveMemoryContent() {
+ let proposal = RunMemoryWriteProposal(
+ id: "proposal-sensitive",
+ proposedBy: .model,
+ record: RunMemoryRecord(
+ id: "memory-sensitive",
+ scope: .target,
+ kind: .targetFact,
+ targetID: "target-1",
+ value: "user email [email protected]",
+ createdAt: timestamp(10),
+ expiresAt: timestamp(1_000),
+ source: RunMemorySource(traceID: "trace-1", summary: "sensitive fixture")
+ ),
+ rationale: "bad provider proposal"
+ )
+
+ let approval = RunMemoryApprover.evaluate(proposal, decidedAt: timestamp(20))
+
+ #expect(approval.approved == false)
+ #expect(approval.issues == [.sensitiveContent])
+ }
+
@Test
func targetMemoryJsonlStoresListsAndDeletesApprovedRecords() async throws {
let root = temporaryDirectory()
@@ -136,6 +160,28 @@ struct RunMemoryStoreTests {
#expect(context.memorySnapshot?.targetRecords.map(\.id) == ["memory-1"])
}
+ @Test
+ func contextAssemblerCarriesBoundedSemanticMemoryResults() {
+ let assembler = RunContextAssembler()
+ let session = RunSession(id: "run-1", userGoal: "avoid hazards", targetID: "target-1")
+ let results = [
+ RunMemorySemanticResult(
+ record: targetRecord(id: "memory-1", runID: "run-1", userID: "user-1"),
+ relevance: 0.9,
+ embeddingModelID: "test-embedding"
+ )
+ ]
+
+ let context = assembler.build(
+ session: session,
+ transcriptSummary: "",
+ semanticMemoryResults: results
+ )
+
+ #expect(context.semanticMemoryResults.map(\.record.id) == ["memory-1"])
+ #expect(context.semanticMemoryResults.first?.embeddingModelID == "test-embedding")
+ }
+
private func targetRecord(id: String, runID: String, userID: String) -> RunMemoryRecord {
RunMemoryRecord(
id: id,
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/TargetWindowFrameSourceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/TargetWindowFrameSourceTests.swift
index 67f872d6..c698c6ec 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/TargetWindowFrameSourceTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/TargetWindowFrameSourceTests.swift
@@ -87,6 +87,43 @@ struct TargetWindowFrameSourceTests {
#expect(result.frames.first?.metadata["capture.artifactWritten"] == "false")
}
+ @Test
+ func iPhoneMirroringFramesDefaultToCenteredPhoneContentCrop() async throws {
+ let service = makeService(
+ windows: [
+ fixtureWindow(
+ windowID: 33,
+ processID: 300,
+ appName: "iPhone Mirroring",
+ bundleIdentifier: "com.apple.ScreenContinuity"
+ )
+ ],
+ frontmostProcessID: 300,
+ capturer: FakeTargetWindowFrameCapturer(
+ imageWidth: 500,
+ imageHeight: 1_000
+ )
+ )
+
+ let result = try await service.captureFrames(
+ request: TargetWindowFrameCaptureRequest(
+ selection: MacWindowSelectionRequest(windowID: 33),
+ targetID: "target-iphone",
+ traceID: "trace-iphone",
+ maxFrameCount: 1
+ )
+ )
+
+ let crop = try #require(result.frames.first?.crop)
+ #expect(crop.id == "target-window-content")
+ #expect(abs(crop.bounds.origin.x - 19.230_769) < 0.001)
+ #expect(crop.bounds.origin.y == 0)
+ #expect(abs(crop.bounds.size.width - 461.538_461) < 0.001)
+ #expect(crop.bounds.size.height == 1_000)
+ #expect(result.frames.first?.metadata["contentCalibration.mode"] == "centeredAspectFit")
+ #expect(result.frames.first?.metadata["contentCalibration.target.isIPhoneMirroring"] == "true")
+ }
+
@Test
func unsafeTargetRefusesBeforeCapturingFrames() async throws {
let capturer = FakeTargetWindowFrameCapturer()
@@ -190,6 +227,43 @@ struct TargetWindowFrameSourceTests {
#expect(batches.flatMap { $0 }.map(\.id) == ["source-frame-1", "source-frame-2"])
}
+ @Test
+ func continuousTargetWindowFrameSourceStreamsLatestFrameBatches() async {
+ let capturer = FakeTargetWindowFrameCapturer()
+ let service = makeService(
+ windows: [
+ fixtureWindow(windowID: 31, processID: 301, appName: "Game")
+ ],
+ frontmostProcessID: 301,
+ capturer: capturer
+ )
+ let source = ContinuousTargetWindowFrameSource(
+ service: service,
+ request: TargetWindowFrameCaptureRequest(
+ selection: MacWindowSelectionRequest(windowID: 31),
+ targetID: "target-game",
+ traceID: "trace-stream",
+ frameIDPrefix: "stream-frame",
+ maxFrameCount: 1
+ ),
+ minimumFrameIntervalNanoseconds: 0,
+ maximumFrameCount: 3
+ )
+
+ var frames: [HotLoopFrame] = []
+ for await batch in source.frameBatchStream() {
+ frames.append(contentsOf: batch)
+ }
+
+ #expect(frames.count == 3)
+ #expect(frames.map(\.id) == [
+ "stream-frame-stream-1-1",
+ "stream-frame-stream-2-1",
+ "stream-frame-stream-3-1"
+ ])
+ #expect(capturer.capturedWindowIDs == [31, 31, 31])
+ }
+
private func makeService(
windows: [MacWindowProviderWindow],
frontmostProcessID: Int32? = nil,