Skip to content

Open source CapCut alternative.

TypeScript

Add local runtime installer and sidecar setup

David Lef3ab204848dd
diff --git a/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift b/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift
index fa1216ac..58f68e2f 100644
--- a/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift
+++ b/apps/Donkey/Sources/Donkey/ManualCaptureDebugLaunchHandler.swift
@@ -54,6 +54,36 @@ struct ManualCaptureDebugLaunchHandler {
.run()
printLines(ReflexLatencyReportFormatter.lines(for: report))
return 0
+ case .localRuntimeStatus:
+ let manager = try LocalModelRuntimeSetupManager()
+ printLines(
+ ManualCaptureDebugCommandFormatter.lines(
+ for: try manager.statuses()
+ )
+ )
+ return 0
+ case .localRuntimeInstructions:
+ let manager = try LocalModelRuntimeSetupManager()
+ printLines(
+ ManualCaptureDebugCommandFormatter.lines(
+ for: manager.instructions()
+ )
+ )
+ return 0
+ case .installLocalRuntime(let options):
+ let manager = try LocalModelRuntimeSetupManager()
+ let installation = try manager.registerDownloadedRuntime(
+ runtimeID: options.runtimeID,
+ downloadedDirectory: options.sourceDirectory
+ )
+ let spec = try manager.status(for: options.runtimeID).spec
+ printLines(
+ ManualCaptureDebugCommandFormatter.lines(
+ for: installation,
+ spec: spec
+ )
+ )
+ return 0
}
} catch {
printError(ManualCaptureDebugCommandFormatter.errorLine(for: error))
diff --git a/apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swift b/apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swift
new file mode 100644
index 00000000..5af7cd18
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swift
@@ -0,0 +1,167 @@
+import DonkeyContracts
+import Foundation
+
+public enum AIHarnessRedactionSurface: String, Codable, Equatable, Sendable {
+ case screenshotSummary
+ case domSummary
+ case modelContext
+}
+
+public struct AIHarnessRedactionResult: Codable, Equatable, Sendable {
+ public var surface: AIHarnessRedactionSurface
+ public var redactedText: String
+ public var redactionCount: Int
+ public var metadata: [String: String]
+
+ public init(
+ surface: AIHarnessRedactionSurface,
+ redactedText: String,
+ redactionCount: Int,
+ metadata: [String: String] = [:]
+ ) {
+ self.surface = surface
+ self.redactedText = redactedText
+ self.redactionCount = redactionCount
+ self.metadata = metadata
+ }
+}
+
+public struct AIHarnessRedactor: Sendable {
+ public init() {}
+
+ public func redact(
+ _ text: String,
+ surface: AIHarnessRedactionSurface
+ ) -> AIHarnessRedactionResult {
+ var redacted = text
+ var count = 0
+ let patterns = [
+ #"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}"#: "[redacted-email]",
+ #"\b(?:\d[ -]*?){13,16}\b"#: "[redacted-number]",
+ #"(?i)(password|token|api[_ -]?key)\s*[:=]\s*\S+"#: "$1=[redacted-secret]"
+ ]
+
+ for (pattern, replacement) in patterns {
+ let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
+ let range = NSRange(redacted.startIndex..<redacted.endIndex, in: redacted)
+ let matches = regex?.numberOfMatches(in: redacted, range: range) ?? 0
+ guard matches > 0 else { continue }
+ redacted = regex?.stringByReplacingMatches(
+ in: redacted,
+ range: range,
+ withTemplate: replacement
+ ) ?? redacted
+ count += matches
+ }
+
+ return AIHarnessRedactionResult(
+ surface: surface,
+ redactedText: redacted,
+ redactionCount: count,
+ metadata: [
+ "redactor": "ai-harness-redactor-v1",
+ "remoteBoundSafe": String(count > 0)
+ ]
+ )
+ }
+}
+
+public struct AIModelObservabilityReport: Codable, Equatable, Sendable {
+ public var callCount: Int
+ public var statusCounts: [String: Int]
+ public var providerCounts: [String: Int]
+ public var validationStatusCounts: [String: Int]
+ public var acceptedCount: Int
+ public var recoverySuccessCount: Int
+ public var totalEstimatedCostUSD: Double
+ public var latencyMS: AIModelLatencyPercentiles
+ public var metadata: [String: String]
+
+ public init(
+ callCount: Int,
+ statusCounts: [String: Int],
+ providerCounts: [String: Int],
+ validationStatusCounts: [String: Int],
+ acceptedCount: Int,
+ recoverySuccessCount: Int,
+ totalEstimatedCostUSD: Double,
+ latencyMS: AIModelLatencyPercentiles,
+ metadata: [String: String] = [:]
+ ) {
+ self.callCount = callCount
+ self.statusCounts = statusCounts
+ self.providerCounts = providerCounts
+ self.validationStatusCounts = validationStatusCounts
+ self.acceptedCount = acceptedCount
+ self.recoverySuccessCount = recoverySuccessCount
+ self.totalEstimatedCostUSD = totalEstimatedCostUSD
+ self.latencyMS = latencyMS
+ self.metadata = metadata
+ }
+}
+
+public struct AIModelLatencyPercentiles: Codable, Equatable, Sendable {
+ public var p50: Double?
+ public var p95: Double?
+
+ public init(p50: Double? = nil, p95: Double? = nil) {
+ self.p50 = p50
+ self.p95 = p95
+ }
+}
+
+public enum AIModelObservabilityReportBuilder {
+ public static func build(from traces: [AIModelCallTrace]) -> AIModelObservabilityReport {
+ AIModelObservabilityReport(
+ callCount: traces.count,
+ statusCounts: countBy(traces.map { $0.status.rawValue }),
+ providerCounts: countBy(traces.map { $0.provider.rawValue }),
+ validationStatusCounts: countBy(traces.map(\.validationStatus)),
+ acceptedCount: traces.filter { $0.status == .completed && $0.validationStatus != "invalid" }.count,
+ recoverySuccessCount: traces.filter { $0.metadata["recovery.success"] == "true" }.count,
+ totalEstimatedCostUSD: traces.reduce(0) { total, trace in
+ total + (Double(trace.metadata["cost.estimatedUSD"] ?? "") ?? 0)
+ },
+ latencyMS: percentiles(traces.compactMap(\.latencyMS)),
+ metadata: ["report": "ai-model-observability-v1"]
+ )
+ }
+
+ private static func countBy(_ values: [String]) -> [String: Int] {
+ values.reduce(into: [:]) { result, value in
+ result[value, default: 0] += 1
+ }
+ }
+
+ private static func percentiles(_ values: [Double]) -> AIModelLatencyPercentiles {
+ guard !values.isEmpty else { return AIModelLatencyPercentiles() }
+ let sorted = values.sorted()
+ return AIModelLatencyPercentiles(
+ p50: percentile(sorted, fraction: 0.50),
+ p95: percentile(sorted, fraction: 0.95)
+ )
+ }
+
+ private static func percentile(_ sortedValues: [Double], fraction: Double) -> Double? {
+ let index = min(sortedValues.count - 1, Int(Double(sortedValues.count - 1) * fraction))
+ return sortedValues[index]
+ }
+}
+
+public enum ProviderDecodedMemoryProposalHandler {
+ public static func decisions(
+ from data: Data,
+ decidedAt: RunTraceTimestamp,
+ decoder: JSONDecoder = JSONDecoder()
+ ) throws -> [RunMemoryWriteDecision] {
+ let proposals = try decoder.decode([RunMemoryWriteProposal].self, from: data)
+ return proposals.map { proposal in
+ let approval = RunMemoryApprover.evaluate(proposal, decidedAt: decidedAt)
+ return RunMemoryWriteDecision(
+ proposal: proposal,
+ approval: approval,
+ storedRecord: approval.approved ? proposal.record : nil
+ )
+ }
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
index 420e4254..b7a11dca 100644
--- a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
@@ -131,7 +131,7 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {
promptVersion: "voice-transcription-v1",
evalStatus: .candidate,
docsURL: URL(string: "https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3")!,
- rollbackID: "local-voice-transcription-whisper-large-v3-turbo",
+ rollbackID: nil,
metadata: [
"local": "true",
"runtime": "nvidia-nemo",
@@ -143,28 +143,7 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {
"selectedReason": "current Parakeet TDT 0.6B default for local ASR with punctuation, timestamps, and multilingual support",
"lastVerifiedAt": "2026-05-17",
"docsSource": "official NVIDIA Hugging Face model card",
- "fallbackModelID": "openai/whisper-large-v3-turbo"
- ]
- ),
- AIModelRegistryEntry(
- id: "local-voice-transcription-whisper-large-v3-turbo",
- role: .voiceTranscription,
- provider: .localRuntime,
- modelID: "openai/whisper-large-v3-turbo",
- endpoint: URL(string: "local://openai/whisper-large-v3-turbo")!,
- capabilities: [.audioInput],
- timeoutMS: 4_000,
- promptVersion: "voice-transcription-v1",
- evalStatus: .candidate,
- docsURL: URL(string: "https://huggingface.co/openai/whisper-large-v3-turbo")!,
- rollbackID: nil,
- metadata: [
- "local": "true",
- "runtime": "transformers-or-whispercpp",
- "language": "multilingual",
- "selectedReason": "fallback local ASR when Parakeet runtime is unavailable or non-supported language quality wins",
- "lastVerifiedAt": "2026-05-17",
- "docsSource": "official OpenAI Hugging Face model card"
+ "fallbackPolicy": "none"
]
),
AIModelRegistryEntry(
diff --git a/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
index 1f8481fa..67ccc436 100644
--- a/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
@@ -1,4 +1,5 @@
import DonkeyContracts
+import DonkeyRuntime
import Foundation
public struct LocalVoiceAudioBuffer: Equatable, Sendable {
@@ -102,6 +103,102 @@ public struct UnavailableLocalVoiceTranscriptionRuntime: LocalVoiceTranscription
public enum LocalVoiceTranscriptionRuntimeError: Error, Equatable, Sendable {
case runtimeUnavailable(String)
case emptyTranscript
+ case invalidOutput(String)
+}
+
+public struct ProcessBackedParakeetTranscriptionRuntime: LocalVoiceTranscriptionRuntime {
+ public var sidecarRunner: any LocalJSONSidecarRunning
+ public var encoder: JSONEncoder
+ public var decoder: JSONDecoder
+
+ public init(
+ sidecarRunner: any LocalJSONSidecarRunning = ProcessBackedLocalJSONSidecarRunner(),
+ encoder: JSONEncoder = JSONEncoder(),
+ decoder: JSONDecoder = JSONDecoder()
+ ) {
+ self.sidecarRunner = sidecarRunner
+ self.encoder = encoder
+ self.decoder = decoder
+ }
+
+ public func transcribe(
+ audio: LocalVoiceAudioBuffer,
+ model: AIModelRegistryEntry
+ ) async throws -> LocalVoiceTranscript {
+ let request = ParakeetSidecarRequest(
+ audioID: audio.id,
+ format: audio.format,
+ sampleRateHz: audio.sampleRateHz,
+ channelCount: audio.channelCount,
+ durationMS: audio.durationMS,
+ audioBase64: audio.data.base64EncodedString(),
+ modelID: model.modelID,
+ metadata: audio.metadata
+ )
+ let inputData = try encoder.encode(request)
+ let result = await sidecarRunner.run(
+ LocalJSONSidecarRequest(
+ environmentVariableName: "DONKEY_PARAKEET_TRANSCRIBER",
+ inputData: inputData,
+ timeoutMS: model.timeoutMS,
+ metadata: [
+ "sidecar.role": "voiceTranscription",
+ "modelID": model.modelID
+ ]
+ )
+ )
+ guard result.status == .completed else {
+ throw LocalVoiceTranscriptionRuntimeError.runtimeUnavailable(
+ result.metadata["sidecar.reason"] ?? result.status.rawValue
+ )
+ }
+
+ do {
+ let response = try decoder.decode(ParakeetSidecarResponse.self, from: result.outputData)
+ return LocalVoiceTranscript(
+ text: response.text,
+ language: response.language,
+ confidence: response.confidence,
+ segments: response.segments,
+ metadata: result.metadata.merging(response.metadata) { current, _ in current }
+ )
+ } catch {
+ throw LocalVoiceTranscriptionRuntimeError.invalidOutput(String(describing: error))
+ }
+ }
+}
+
+private struct ParakeetSidecarRequest: Codable, Equatable, Sendable {
+ var audioID: String
+ var format: String
+ var sampleRateHz: Int
+ var channelCount: Int
+ var durationMS: Double
+ var audioBase64: String
+ var modelID: String
+ var metadata: [String: String]
+}
+
+private struct ParakeetSidecarResponse: Codable, Equatable, Sendable {
+ var text: String
+ var language: String?
+ var confidence: Double
+ var segments: [String]
+ var metadata: [String: String]
+
+ init(
+ text: String,
+ language: String? = nil,
+ confidence: Double = 0,
+ segments: [String] = [],
+ metadata: [String: String] = [:]
+ ) {
+ self.text = text
+ self.language = language
+ self.confidence = confidence
+ self.segments = segments
+ self.metadata = metadata
+ }
}
public struct LocalVoiceTranscriptionAdapter: Sendable {
diff --git a/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift b/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift
index eec35dca..b5f228e8 100644
--- a/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift
@@ -210,6 +210,63 @@ public struct RunMemorySnapshot: Codable, Equatable, Sendable {
}
}
+public struct RunMemoryRetrievalBudget: Codable, Equatable, Sendable {
+ public var maxRecords: Int
+ public var maxPromptCharacters: Int
+ public var minRelevance: Double
+
+ public init(
+ maxRecords: Int = 6,
+ maxPromptCharacters: Int = 2_000,
+ minRelevance: Double = 0.2
+ ) {
+ self.maxRecords = max(0, maxRecords)
+ self.maxPromptCharacters = max(0, maxPromptCharacters)
+ self.minRelevance = min(max(minRelevance, 0), 1)
+ }
+}
+
+public struct RunMemorySemanticQuery: Codable, Equatable, Sendable {
+ public var text: String
+ public var targetID: String?
+ public var scope: RunMemoryScope?
+ public var budget: RunMemoryRetrievalBudget
+ public var metadata: [String: String]
+
+ public init(
+ text: String,
+ targetID: String? = nil,
+ scope: RunMemoryScope? = nil,
+ budget: RunMemoryRetrievalBudget = RunMemoryRetrievalBudget(),
+ metadata: [String: String] = [:]
+ ) {
+ self.text = text
+ self.targetID = targetID
+ self.scope = scope
+ self.budget = budget
+ self.metadata = metadata
+ }
+}
+
+public struct RunMemorySemanticResult: Codable, Equatable, Sendable {
+ public var record: RunMemoryRecord
+ public var relevance: Double
+ public var embeddingModelID: String?
+ public var metadata: [String: String]
+
+ public init(
+ record: RunMemoryRecord,
+ relevance: Double,
+ embeddingModelID: String? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.record = record
+ self.relevance = min(max(relevance, 0), 1)
+ self.embeddingModelID = embeddingModelID
+ self.metadata = metadata
+ }
+}
+
public enum RunMemoryApprover {
public static func evaluate(
_ proposal: RunMemoryWriteProposal,
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalJSONSidecarRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalJSONSidecarRunner.swift
new file mode 100644
index 00000000..29f7532c
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalJSONSidecarRunner.swift
@@ -0,0 +1,203 @@
+import Foundation
+
+public enum LocalJSONSidecarStatus: String, Codable, Equatable, Sendable {
+ case completed
+ case unavailable
+ case failed
+ case timedOut
+ case invalidOutput
+}
+
+public struct LocalJSONSidecarRequest: Equatable, Sendable {
+ public var environmentVariableName: String
+ public var inputData: Data
+ public var timeoutMS: Int
+ public var metadata: [String: String]
+
+ public init(
+ environmentVariableName: String,
+ inputData: Data,
+ timeoutMS: Int,
+ metadata: [String: String] = [:]
+ ) {
+ self.environmentVariableName = environmentVariableName
+ self.inputData = inputData
+ self.timeoutMS = max(1, timeoutMS)
+ self.metadata = metadata
+ }
+}
+
+public struct LocalJSONSidecarResult: Equatable, Sendable {
+ public var status: LocalJSONSidecarStatus
+ public var outputData: Data
+ public var exitCode: Int32?
+ public var stderrText: String
+ public var latencyMS: Double?
+ public var metadata: [String: String]
+
+ public init(
+ status: LocalJSONSidecarStatus,
+ outputData: Data = Data(),
+ exitCode: Int32? = nil,
+ stderrText: String = "",
+ latencyMS: Double? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.status = status
+ self.outputData = outputData
+ self.exitCode = exitCode
+ self.stderrText = stderrText
+ self.latencyMS = latencyMS
+ self.metadata = metadata
+ }
+}
+
+public protocol LocalJSONSidecarRunning: Sendable {
+ func run(_ request: LocalJSONSidecarRequest) async -> LocalJSONSidecarResult
+}
+
+public struct ProcessBackedLocalJSONSidecarRunner: LocalJSONSidecarRunning {
+ public var environment: [String: String]
+ public var executableResolver: @Sendable (String, [String: String]) -> String?
+ public var isExecutableFile: @Sendable (String) -> Bool
+ public var now: @Sendable () -> Date
+
+ public init(
+ environment: [String: String] = ProcessInfo.processInfo.environment,
+ executableResolver: @escaping @Sendable (String, [String: String]) -> String? = Self.defaultExecutablePath,
+ isExecutableFile: @escaping @Sendable (String) -> Bool = { FileManager.default.isExecutableFile(atPath: $0) },
+ now: @escaping @Sendable () -> Date = Date.init
+ ) {
+ self.environment = environment
+ self.executableResolver = executableResolver
+ self.isExecutableFile = isExecutableFile
+ self.now = now
+ }
+
+ public func run(_ request: LocalJSONSidecarRequest) async -> LocalJSONSidecarResult {
+ guard let executablePath = executableResolver(request.environmentVariableName, environment),
+ !executablePath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ else {
+ return LocalJSONSidecarResult(
+ status: .unavailable,
+ metadata: metadata(
+ request: request,
+ executablePath: nil,
+ reason: "missingEnvironmentVariable"
+ )
+ )
+ }
+
+ guard isExecutableFile(executablePath) else {
+ return LocalJSONSidecarResult(
+ status: .unavailable,
+ metadata: metadata(
+ request: request,
+ executablePath: executablePath,
+ reason: "executableMissingOrNotExecutable"
+ )
+ )
+ }
+
+ let startedAt = now()
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: executablePath)
+ let stdin = Pipe()
+ let stdout = Pipe()
+ let stderr = Pipe()
+ let termination = DispatchSemaphore(value: 0)
+ process.standardInput = stdin
+ process.standardOutput = stdout
+ process.standardError = stderr
+ process.terminationHandler = { _ in
+ termination.signal()
+ }
+
+ do {
+ try process.run()
+ try stdin.fileHandleForWriting.write(contentsOf: request.inputData)
+ try stdin.fileHandleForWriting.close()
+ } catch {
+ return LocalJSONSidecarResult(
+ status: .failed,
+ stderrText: String(describing: error),
+ latencyMS: startedAt.distance(to: now()) * 1_000,
+ metadata: metadata(
+ request: request,
+ executablePath: executablePath,
+ reason: "processLaunchFailed"
+ )
+ )
+ }
+
+ let timeout = DispatchTime.now() + .milliseconds(request.timeoutMS)
+ if Self.waitForTermination(termination, timeout: timeout) == .timedOut {
+ process.terminate()
+ _ = Self.waitForTermination(termination, timeout: .now() + .seconds(1))
+ let stderrData = stderr.fileHandleForReading.readDataToEndOfFile()
+ return LocalJSONSidecarResult(
+ status: .timedOut,
+ exitCode: process.isRunning ? nil : process.terminationStatus,
+ stderrText: String(decoding: stderrData, as: UTF8.self),
+ latencyMS: startedAt.distance(to: now()) * 1_000,
+ metadata: metadata(
+ request: request,
+ executablePath: executablePath,
+ reason: "timeout"
+ )
+ )
+ }
+
+ let outputData = stdout.fileHandleForReading.readDataToEndOfFile()
+ let stderrData = stderr.fileHandleForReading.readDataToEndOfFile()
+ let stderrText = String(decoding: stderrData, as: UTF8.self)
+ let status: LocalJSONSidecarStatus = process.terminationStatus == 0 ? .completed : .failed
+
+ return LocalJSONSidecarResult(
+ status: status,
+ outputData: outputData,
+ exitCode: process.terminationStatus,
+ stderrText: stderrText,
+ latencyMS: startedAt.distance(to: now()) * 1_000,
+ metadata: metadata(
+ request: request,
+ executablePath: executablePath,
+ reason: status == .completed ? "completed" : "nonZeroExit"
+ )
+ )
+ }
+
+ private func metadata(
+ request: LocalJSONSidecarRequest,
+ executablePath: String?,
+ reason: String
+ ) -> [String: String] {
+ var values = request.metadata
+ values["sidecar.environmentVariable"] = request.environmentVariableName
+ values["sidecar.executablePath"] = executablePath ?? ""
+ values["sidecar.reason"] = reason
+ values["sidecar.timeoutMS"] = String(request.timeoutMS)
+ return values
+ }
+
+ private static func waitForTermination(
+ _ semaphore: DispatchSemaphore,
+ timeout: DispatchTime
+ ) -> DispatchTimeoutResult {
+ semaphore.wait(timeout: timeout)
+ }
+
+ public static func defaultExecutablePath(
+ environmentVariableName: String,
+ environment: [String: String]
+ ) -> String? {
+ if let path = environment[environmentVariableName],
+ !path.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ return path
+ }
+
+ return LocalModelRuntimeExecutableResolver().executablePath(
+ environmentVariableName: environmentVariableName
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift
new file mode 100644
index 00000000..d52aef1a
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift
@@ -0,0 +1,352 @@
+import Foundation
+
+public enum LocalModelRuntimeID: String, Codable, CaseIterable, Equatable, Sendable {
+ case parakeetTranscriber = "parakeet-transcriber"
+ case yoloSegmenter = "yolo-segmenter"
+ case uiUnderstander = "ui-understander"
+}
+
+public enum LocalModelRuntimeInstallState: String, Codable, Equatable, Sendable {
+ case installed
+ case notInstalled
+ case invalidExecutable
+}
+
+public enum LocalModelRuntimeSetupError: Error, Equatable, Sendable {
+ case unknownRuntime(String)
+ case missingDownloadedExecutable(runtimeID: LocalModelRuntimeID, expectedRelativePath: String)
+ case downloadedExecutableNotExecutable(runtimeID: LocalModelRuntimeID, path: String)
+}
+
+public struct LocalModelRuntimeSpec: Codable, Equatable, Sendable {
+ public var id: LocalModelRuntimeID
+ public var displayName: String
+ public var environmentVariableName: String
+ public var expectedExecutableRelativePath: String
+ public var modelName: String
+ public var downloadPageURL: URL?
+ public var installSteps: [String]
+ public var metadata: [String: String]
+
+ public init(
+ id: LocalModelRuntimeID,
+ displayName: String,
+ environmentVariableName: String,
+ expectedExecutableRelativePath: String,
+ modelName: String,
+ downloadPageURL: URL? = nil,
+ installSteps: [String],
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.displayName = displayName
+ self.environmentVariableName = environmentVariableName
+ self.expectedExecutableRelativePath = expectedExecutableRelativePath
+ self.modelName = modelName
+ self.downloadPageURL = downloadPageURL
+ self.installSteps = installSteps
+ self.metadata = metadata
+ }
+}
+
+public struct LocalModelRuntimeInstallation: Codable, Equatable, Sendable {
+ public var runtimeID: LocalModelRuntimeID
+ public var executablePath: String
+ public var downloadedDirectoryPath: String
+ public var installedAt: Date
+ public var metadata: [String: String]
+
+ public init(
+ runtimeID: LocalModelRuntimeID,
+ executablePath: String,
+ downloadedDirectoryPath: String,
+ installedAt: Date,
+ metadata: [String: String] = [:]
+ ) {
+ self.runtimeID = runtimeID
+ self.executablePath = executablePath
+ self.downloadedDirectoryPath = downloadedDirectoryPath
+ self.installedAt = installedAt
+ self.metadata = metadata
+ }
+}
+
+public struct LocalModelRuntimeStatus: Codable, Equatable, Sendable {
+ public var spec: LocalModelRuntimeSpec
+ public var state: LocalModelRuntimeInstallState
+ public var installation: LocalModelRuntimeInstallation?
+ public var metadata: [String: String]
+
+ public init(
+ spec: LocalModelRuntimeSpec,
+ state: LocalModelRuntimeInstallState,
+ installation: LocalModelRuntimeInstallation? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.spec = spec
+ self.state = state
+ self.installation = installation
+ self.metadata = metadata
+ }
+}
+
+public struct LocalModelRuntimeInstallInstruction: Codable, Equatable, Sendable {
+ public var spec: LocalModelRuntimeSpec
+ public var setupDirectory: URL
+
+ public init(spec: LocalModelRuntimeSpec, setupDirectory: URL) {
+ self.spec = spec
+ self.setupDirectory = setupDirectory
+ }
+}
+
+public struct LocalModelRuntimeRegistry: Codable, Equatable, Sendable {
+ public var installations: [String: LocalModelRuntimeInstallation]
+
+ public init(installations: [String: LocalModelRuntimeInstallation] = [:]) {
+ self.installations = installations
+ }
+}
+
+public struct LocalModelRuntimeSetupManager: Sendable {
+ public var baseDirectory: URL
+ public var specs: [LocalModelRuntimeSpec]
+ public var isExecutableFile: @Sendable (String) -> Bool
+ public var now: @Sendable () -> Date
+
+ public init(
+ baseDirectory: URL? = nil,
+ specs: [LocalModelRuntimeSpec] = Self.defaultSpecs,
+ isExecutableFile: @escaping @Sendable (String) -> Bool = { FileManager.default.isExecutableFile(atPath: $0) },
+ now: @escaping @Sendable () -> Date = Date.init
+ ) throws {
+ self.baseDirectory = try baseDirectory ?? Self.defaultBaseDirectory()
+ self.specs = specs
+ self.isExecutableFile = isExecutableFile
+ self.now = now
+ }
+
+ public static let defaultSpecs: [LocalModelRuntimeSpec] = [
+ LocalModelRuntimeSpec(
+ id: .parakeetTranscriber,
+ displayName: "Parakeet voice transcription",
+ environmentVariableName: "DONKEY_PARAKEET_TRANSCRIBER",
+ expectedExecutableRelativePath: "bin/donkey-parakeet-transcriber",
+ modelName: "nvidia/parakeet-tdt-0.6b-v3",
+ downloadPageURL: URL(string: "https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3"),
+ installSteps: [
+ "Download the Donkey-compatible Parakeet runtime package after installing Donkey.",
+ "Choose that downloaded runtime folder in Donkey setup.",
+ "Donkey validates bin/donkey-parakeet-transcriber and records the path in Application Support."
+ ],
+ metadata: ["sidecar.role": "voiceTranscription"]
+ ),
+ LocalModelRuntimeSpec(
+ id: .yoloSegmenter,
+ displayName: "YOLO26 screenshot segmentation",
+ environmentVariableName: "DONKEY_YOLO_SEGMENTER",
+ expectedExecutableRelativePath: "bin/donkey-yolo-segmenter",
+ modelName: "ultralytics/yolo26n-seg",
+ downloadPageURL: URL(string: "https://docs.ultralytics.com/models/yolo26/"),
+ installSteps: [
+ "Download the Donkey-compatible YOLO26 segmentation runtime package after installing Donkey.",
+ "Choose that downloaded runtime folder in Donkey setup.",
+ "Donkey validates bin/donkey-yolo-segmenter and records the path in Application Support."
+ ],
+ metadata: ["sidecar.role": "screenshotSegmentation"]
+ ),
+ LocalModelRuntimeSpec(
+ id: .uiUnderstander,
+ displayName: "Local UI understanding",
+ environmentVariableName: "DONKEY_UI_UNDERSTANDER",
+ expectedExecutableRelativePath: "bin/donkey-ui-understander",
+ modelName: "local-ui-understander",
+ downloadPageURL: nil,
+ installSteps: [
+ "Download the Donkey-compatible local UI-understanding runtime package after installing Donkey.",
+ "Choose that downloaded runtime folder in Donkey setup.",
+ "Donkey validates bin/donkey-ui-understander and records the path in Application Support."
+ ],
+ metadata: ["sidecar.role": "uiUnderstanding"]
+ )
+ ]
+
+ public static func defaultBaseDirectory() throws -> URL {
+ try FileManager.default
+ .url(
+ for: .applicationSupportDirectory,
+ in: .userDomainMask,
+ appropriateFor: nil,
+ create: true
+ )
+ .appendingPathComponent("Donkey", isDirectory: true)
+ .appendingPathComponent("LocalModelRuntimes", isDirectory: true)
+ }
+
+ public func instructions() -> [LocalModelRuntimeInstallInstruction] {
+ specs.map { spec in
+ LocalModelRuntimeInstallInstruction(
+ spec: spec,
+ setupDirectory: baseDirectory.appendingPathComponent(spec.id.rawValue, isDirectory: true)
+ )
+ }
+ }
+
+ public func statuses() throws -> [LocalModelRuntimeStatus] {
+ try specs.map { spec in
+ try status(for: spec.id)
+ }
+ }
+
+ public func status(for runtimeID: LocalModelRuntimeID) throws -> LocalModelRuntimeStatus {
+ let spec = try spec(for: runtimeID)
+ let registry = try loadRegistry()
+ guard let installation = registry.installations[runtimeID.rawValue] else {
+ return LocalModelRuntimeStatus(
+ spec: spec,
+ state: .notInstalled,
+ metadata: ["reason": "noRegisteredRuntime"]
+ )
+ }
+
+ let state: LocalModelRuntimeInstallState = isExecutableFile(installation.executablePath)
+ ? .installed
+ : .invalidExecutable
+ return LocalModelRuntimeStatus(
+ spec: spec,
+ state: state,
+ installation: installation,
+ metadata: [
+ "reason": state == .installed ? "installed" : "executableMissingOrNotExecutable"
+ ]
+ )
+ }
+
+ @discardableResult
+ public func registerDownloadedRuntime(
+ runtimeID: LocalModelRuntimeID,
+ downloadedDirectory: URL
+ ) throws -> LocalModelRuntimeInstallation {
+ let spec = try spec(for: runtimeID)
+ let executableURL = downloadedDirectory.appendingPathComponent(
+ spec.expectedExecutableRelativePath,
+ isDirectory: false
+ )
+ guard FileManager.default.fileExists(atPath: executableURL.path) else {
+ throw LocalModelRuntimeSetupError.missingDownloadedExecutable(
+ runtimeID: runtimeID,
+ expectedRelativePath: spec.expectedExecutableRelativePath
+ )
+ }
+
+ return try registerExecutable(
+ runtimeID: runtimeID,
+ executableURL: executableURL,
+ downloadedDirectory: downloadedDirectory
+ )
+ }
+
+ @discardableResult
+ public func registerExecutable(
+ runtimeID: LocalModelRuntimeID,
+ executableURL: URL,
+ downloadedDirectory: URL
+ ) throws -> LocalModelRuntimeInstallation {
+ guard isExecutableFile(executableURL.path) else {
+ throw LocalModelRuntimeSetupError.downloadedExecutableNotExecutable(
+ runtimeID: runtimeID,
+ path: executableURL.path
+ )
+ }
+
+ try FileManager.default.createDirectory(
+ at: baseDirectory,
+ withIntermediateDirectories: true
+ )
+ var registry = try loadRegistry()
+ let installation = LocalModelRuntimeInstallation(
+ runtimeID: runtimeID,
+ executablePath: executableURL.path,
+ downloadedDirectoryPath: downloadedDirectory.path,
+ installedAt: now(),
+ metadata: ["installedBy": "donkey-local-runtime-setup"]
+ )
+ registry.installations[runtimeID.rawValue] = installation
+ try saveRegistry(registry)
+ return installation
+ }
+
+ public func configuredEnvironment() throws -> [String: String] {
+ let registry = try loadRegistry()
+ return specs.reduce(into: [:]) { result, spec in
+ guard let installation = registry.installations[spec.id.rawValue],
+ isExecutableFile(installation.executablePath)
+ else {
+ return
+ }
+ result[spec.environmentVariableName] = installation.executablePath
+ }
+ }
+
+ public func executablePath(environmentVariableName: String) throws -> String? {
+ try configuredEnvironment()[environmentVariableName]
+ }
+
+ private func spec(for runtimeID: LocalModelRuntimeID) throws -> LocalModelRuntimeSpec {
+ guard let spec = specs.first(where: { $0.id == runtimeID }) else {
+ throw LocalModelRuntimeSetupError.unknownRuntime(runtimeID.rawValue)
+ }
+ return spec
+ }
+
+ private func loadRegistry() throws -> LocalModelRuntimeRegistry {
+ let url = registryURL()
+ guard FileManager.default.fileExists(atPath: url.path) else {
+ return LocalModelRuntimeRegistry()
+ }
+ let data = try Data(contentsOf: url)
+ return try Self.decoder().decode(LocalModelRuntimeRegistry.self, from: data)
+ }
+
+ private func saveRegistry(_ registry: LocalModelRuntimeRegistry) throws {
+ try FileManager.default.createDirectory(
+ at: baseDirectory,
+ withIntermediateDirectories: true
+ )
+ let data = try Self.encoder().encode(registry)
+ try data.write(to: registryURL(), options: .atomic)
+ }
+
+ private func registryURL() -> URL {
+ baseDirectory.appendingPathComponent("runtime-installations.json", isDirectory: false)
+ }
+
+ private static func encoder() -> JSONEncoder {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ encoder.dateEncodingStrategy = .iso8601
+ return encoder
+ }
+
+ private static func decoder() -> JSONDecoder {
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ return decoder
+ }
+}
+
+public struct LocalModelRuntimeExecutableResolver: Sendable {
+ public var setupManagerFactory: @Sendable () throws -> LocalModelRuntimeSetupManager
+
+ public init(
+ setupManagerFactory: @escaping @Sendable () throws -> LocalModelRuntimeSetupManager = {
+ try LocalModelRuntimeSetupManager()
+ }
+ ) {
+ self.setupManagerFactory = setupManagerFactory
+ }
+
+ public func executablePath(environmentVariableName: String) -> String? {
+ try? setupManagerFactory().executablePath(environmentVariableName: environmentVariableName)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift
new file mode 100644
index 00000000..8b81d381
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift
@@ -0,0 +1,183 @@
+import DonkeyContracts
+import Foundation
+
+public enum LocalUIUnderstandingError: Error, Equatable, Sendable {
+ case unavailable(String)
+ case invalidOutput(String)
+}
+
+public struct LocalUIUnderstandingRequest: Equatable, Sendable {
+ public var traceID: String
+ public var targetID: String
+ public var appIsRunning: Bool
+ public var appIsFocused: Bool
+ public var imageFileURL: URL?
+ public var artifactURL: URL?
+ public var cropBounds: HotLoopRect?
+ public var pixelSize: HotLoopSize?
+ public var metadata: [String: String]
+
+ public init(
+ traceID: String,
+ targetID: String,
+ appIsRunning: Bool = true,
+ appIsFocused: Bool = true,
+ imageFileURL: URL? = nil,
+ artifactURL: URL? = nil,
+ cropBounds: HotLoopRect? = nil,
+ pixelSize: HotLoopSize? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.traceID = traceID
+ self.targetID = targetID
+ self.appIsRunning = appIsRunning
+ self.appIsFocused = appIsFocused
+ self.imageFileURL = imageFileURL
+ self.artifactURL = artifactURL
+ self.cropBounds = cropBounds
+ self.pixelSize = pixelSize
+ self.metadata = metadata
+ }
+}
+
+public struct LocalUIUnderstandingControl: Codable, Equatable, Sendable {
+ public var id: String
+ public var label: String
+ public var kind: LocalAppControlKind
+ public var frame: HotLoopRect?
+ public var confidence: Double
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ label: String,
+ kind: LocalAppControlKind,
+ frame: HotLoopRect? = nil,
+ confidence: Double,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.label = label
+ self.kind = kind
+ self.frame = frame
+ self.confidence = min(max(confidence, 0), 1)
+ self.metadata = metadata
+ }
+}
+
+public struct LocalUIUnderstandingResult: Codable, Equatable, Sendable {
+ public var visibleText: [String: String]
+ public var controls: [LocalUIUnderstandingControl]
+ public var formFields: [LocalDocumentFormField]
+ public var confidence: Double
+ public var metadata: [String: String]
+
+ public init(
+ visibleText: [String: String] = [:],
+ controls: [LocalUIUnderstandingControl] = [],
+ formFields: [LocalDocumentFormField] = [],
+ confidence: Double,
+ metadata: [String: String] = [:]
+ ) {
+ self.visibleText = visibleText
+ self.controls = controls
+ self.formFields = formFields
+ self.confidence = min(max(confidence, 0), 1)
+ self.metadata = metadata
+ }
+
+ public func observation(for request: LocalUIUnderstandingRequest) -> LocalAppTaskObservation {
+ LocalAppTaskObservation(
+ appIsRunning: request.appIsRunning,
+ appIsFocused: request.appIsFocused,
+ availableControls: Dictionary(uniqueKeysWithValues: controls.map { control in
+ (control.metadata["controlID"] ?? control.id, true)
+ }),
+ visibleText: visibleText,
+ confidence: confidence,
+ metadata: metadata.merging([
+ "observer": "local-ui-understanding",
+ "traceID": request.traceID,
+ "targetID": request.targetID,
+ "controlCount": String(controls.count),
+ "formFieldCount": String(formFields.count),
+ "directInputActionsAllowed": "false"
+ ]) { current, _ in current }
+ )
+ }
+}
+
+public protocol LocalUIUnderstandingRunning: Sendable {
+ func understand(_ request: LocalUIUnderstandingRequest) async throws -> LocalUIUnderstandingResult
+}
+
+public struct ProcessBackedLocalUIUnderstandingAdapter: LocalUIUnderstandingRunning {
+ public var sidecarRunner: any LocalJSONSidecarRunning
+ public var encoder: JSONEncoder
+ public var decoder: JSONDecoder
+ public var timeoutMS: Int
+
+ public init(
+ sidecarRunner: any LocalJSONSidecarRunning = ProcessBackedLocalJSONSidecarRunner(),
+ encoder: JSONEncoder = JSONEncoder(),
+ decoder: JSONDecoder = JSONDecoder(),
+ timeoutMS: Int = 4_000
+ ) {
+ self.sidecarRunner = sidecarRunner
+ self.encoder = encoder
+ self.decoder = decoder
+ self.timeoutMS = max(1, timeoutMS)
+ }
+
+ public func understand(_ request: LocalUIUnderstandingRequest) async throws -> LocalUIUnderstandingResult {
+ let input = LocalUIUnderstandingSidecarRequest(
+ traceID: request.traceID,
+ targetID: request.targetID,
+ imagePath: request.imageFileURL?.path,
+ artifactURL: request.artifactURL?.absoluteString,
+ cropBounds: request.cropBounds,
+ pixelSize: request.pixelSize,
+ metadata: request.metadata
+ )
+ let result = await sidecarRunner.run(
+ LocalJSONSidecarRequest(
+ environmentVariableName: "DONKEY_UI_UNDERSTANDER",
+ inputData: try encoder.encode(input),
+ timeoutMS: timeoutMS,
+ metadata: [
+ "sidecar.role": "uiUnderstanding",
+ "targetID": request.targetID
+ ]
+ )
+ )
+
+ guard result.status == .completed else {
+ throw LocalUIUnderstandingError.unavailable(
+ result.metadata["sidecar.reason"] ?? result.status.rawValue
+ )
+ }
+
+ do {
+ let output = try decoder.decode(LocalUIUnderstandingResult.self, from: result.outputData)
+ return LocalUIUnderstandingResult(
+ visibleText: output.visibleText,
+ controls: output.controls,
+ formFields: output.formFields,
+ confidence: output.confidence,
+ metadata: result.metadata.merging(output.metadata) { current, _ in current }
+ )
+ } catch {
+ throw LocalUIUnderstandingError.invalidOutput(String(describing: error))
+ }
+ }
+}
+
+private struct LocalUIUnderstandingSidecarRequest: Codable, Equatable, Sendable {
+ var traceID: String
+ var targetID: String
+ var imagePath: String?
+ var artifactURL: String?
+ var cropBounds: HotLoopRect?
+ var pixelSize: HotLoopSize?
+ var metadata: [String: String]
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift b/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift
index 595e5828..a873f388 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ManualCaptureDebugCommand.swift
@@ -5,6 +5,9 @@ public enum ManualCaptureDebugCommand: Equatable, Sendable {
case listWindowCandidates
case manualCapture(ManualCaptureDebugCaptureOptions)
case dryRunLatencyReport(DryRunLatencyReportDebugOptions)
+ case localRuntimeStatus
+ case localRuntimeInstructions
+ case installLocalRuntime(LocalRuntimeInstallDebugOptions)
}
public struct ManualCaptureDebugCaptureOptions: Equatable, Sendable {
@@ -36,6 +39,16 @@ public struct DryRunLatencyReportDebugOptions: Equatable, Sendable {
}
}
+public struct LocalRuntimeInstallDebugOptions: Equatable, Sendable {
+ public var runtimeID: LocalModelRuntimeID
+ public var sourceDirectory: URL
+
+ public init(runtimeID: LocalModelRuntimeID, sourceDirectory: URL) {
+ self.runtimeID = runtimeID
+ self.sourceDirectory = sourceDirectory
+ }
+}
+
public enum ManualCaptureDebugCommandParseError: Error, Equatable, Sendable, CustomStringConvertible {
case conflictingCommands
case missingCommand
@@ -43,6 +56,7 @@ public enum ManualCaptureDebugCommandParseError: Error, Equatable, Sendable, Cus
case invalidWindowID(String)
case invalidFrameCount(String)
case invalidBenchmarkMode(String)
+ case invalidRuntimeID(String)
case invalidIdentifier(option: String, value: String)
case unsupportedOption(String)
@@ -60,6 +74,8 @@ public enum ManualCaptureDebugCommandParseError: Error, Equatable, Sendable, Cus
return "Invalid --frame-count value: \(value)."
case .invalidBenchmarkMode(let value):
return "Invalid --benchmark-mode value: \(value)."
+ case .invalidRuntimeID(let value):
+ return "Invalid --runtime-id value: \(value)."
case .invalidIdentifier(let option, let value):
return "Invalid \(option) value: \(value). Use letters, numbers, '.', '_', or '-'."
case .unsupportedOption(let option):
@@ -74,11 +90,16 @@ public enum ManualCaptureDebugCommandParser {
argument == "--list-window-candidates"
|| argument == "--manual-capture"
|| argument == "--dry-run-latency-report"
+ || argument == "--local-runtime-status"
+ || argument == "--local-runtime-instructions"
+ || argument == "--install-local-runtime"
|| argument == "--window-id"
|| argument == "--run-id"
|| argument == "--trace-id"
|| argument == "--frame-count"
|| argument == "--benchmark-mode"
+ || argument == "--runtime-id"
+ || argument == "--runtime-source"
}
}
@@ -96,6 +117,8 @@ public enum ManualCaptureDebugCommandParser {
var traceID: String?
var frameCount = 30
var benchmarkMode = ReflexReplayBenchmarkMode.endToEndDryRun
+ var runtimeID: LocalModelRuntimeID?
+ var runtimeSource: URL?
var index = 0
while index < arguments.count {
@@ -110,6 +133,15 @@ public enum ManualCaptureDebugCommandParser {
case "--dry-run-latency-report":
try setMode(.dryRunLatencyReport, current: &mode)
index += 1
+ case "--local-runtime-status":
+ try setMode(.localRuntimeStatus, current: &mode)
+ index += 1
+ case "--local-runtime-instructions":
+ try setMode(.localRuntimeInstructions, current: &mode)
+ index += 1
+ case "--install-local-runtime":
+ try setMode(.installLocalRuntime, current: &mode)
+ index += 1
case "--window-id":
let value = try value(after: argument, in: arguments, at: index)
guard let parsed = UInt32(value) else {
@@ -141,6 +173,17 @@ public enum ManualCaptureDebugCommandParser {
}
benchmarkMode = parsed
index += 2
+ case "--runtime-id":
+ let value = try value(after: argument, in: arguments, at: index)
+ guard let parsed = LocalModelRuntimeID(rawValue: value) else {
+ throw ManualCaptureDebugCommandParseError.invalidRuntimeID(value)
+ }
+ runtimeID = parsed
+ index += 2
+ case "--runtime-source":
+ let value = try value(after: argument, in: arguments, at: index)
+ runtimeSource = URL(fileURLWithPath: value)
+ index += 2
default:
throw ManualCaptureDebugCommandParseError.unsupportedOption(argument)
}
@@ -183,6 +226,44 @@ public enum ManualCaptureDebugCommandParser {
mode: benchmarkMode
)
)
+ case .localRuntimeStatus:
+ guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
+ benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil
+ else {
+ throw ManualCaptureDebugCommandParseError.unsupportedOption(
+ "runtime install options require --install-local-runtime"
+ )
+ }
+ return .localRuntimeStatus
+ case .localRuntimeInstructions:
+ guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
+ benchmarkMode == .endToEndDryRun, runtimeID == nil, runtimeSource == nil
+ else {
+ throw ManualCaptureDebugCommandParseError.unsupportedOption(
+ "runtime install options require --install-local-runtime"
+ )
+ }
+ return .localRuntimeInstructions
+ case .installLocalRuntime:
+ guard windowID == nil, runID == nil, traceID == nil, frameCount == 30,
+ benchmarkMode == .endToEndDryRun
+ else {
+ throw ManualCaptureDebugCommandParseError.unsupportedOption(
+ "capture or benchmark options are not supported with --install-local-runtime"
+ )
+ }
+ guard let runtimeID else {
+ throw ManualCaptureDebugCommandParseError.missingValue("--runtime-id")
+ }
+ guard let runtimeSource else {
+ throw ManualCaptureDebugCommandParseError.missingValue("--runtime-source")
+ }
+ return .installLocalRuntime(
+ LocalRuntimeInstallDebugOptions(
+ runtimeID: runtimeID,
+ sourceDirectory: runtimeSource
+ )
+ )
}
}
@@ -299,6 +380,60 @@ public enum ManualCaptureDebugCommandFormatter {
return lines
}
+ public static func lines(
+ for instructions: [LocalModelRuntimeInstallInstruction]
+ ) -> [String] {
+ var lines = ["local runtime setup instructions"]
+ for instruction in instructions {
+ lines.append("runtime=\(instruction.spec.id.rawValue)")
+ lines.append("name=\(instruction.spec.displayName)")
+ lines.append("model=\(instruction.spec.modelName)")
+ lines.append("env=\(instruction.spec.environmentVariableName)")
+ lines.append("expectedExecutable=\(instruction.spec.expectedExecutableRelativePath)")
+ lines.append("setupDirectory=\(instruction.setupDirectory.path)")
+ if let downloadPageURL = instruction.spec.downloadPageURL {
+ lines.append("downloadPage=\(downloadPageURL.absoluteString)")
+ }
+ for (index, step) in instruction.spec.installSteps.enumerated() {
+ lines.append("step\(index + 1)=\(step)")
+ }
+ }
+ return lines
+ }
+
+ public static func lines(
+ for statuses: [LocalModelRuntimeStatus]
+ ) -> [String] {
+ var lines = ["local runtime status"]
+ for status in statuses {
+ lines.append(
+ [
+ "runtime=\(status.spec.id.rawValue)",
+ "state=\(status.state.rawValue)",
+ "env=\(status.spec.environmentVariableName)",
+ "executable=\(status.installation?.executablePath ?? "-")",
+ "reason=\(status.metadata["reason"] ?? "-")"
+ ]
+ .joined(separator: " | ")
+ )
+ }
+ return lines
+ }
+
+ public static func lines(
+ for installation: LocalModelRuntimeInstallation,
+ spec: LocalModelRuntimeSpec
+ ) -> [String] {
+ [
+ "local runtime installed",
+ "runtime=\(installation.runtimeID.rawValue)",
+ "name=\(spec.displayName)",
+ "env=\(spec.environmentVariableName)",
+ "executable=\(installation.executablePath)",
+ "downloadedDirectory=\(installation.downloadedDirectoryPath)"
+ ]
+ }
+
public static func errorLine(for error: Error) -> String {
if let parseError = error as? ManualCaptureDebugCommandParseError {
return "manual capture debug error: \(parseError.description)"
@@ -323,4 +458,7 @@ private enum ManualCaptureDebugCommandMode {
case listWindowCandidates
case manualCapture
case dryRunLatencyReport
+ case localRuntimeStatus
+ case localRuntimeInstructions
+ case installLocalRuntime
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift b/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift
index 2f73fa61..70f10597 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift
@@ -43,6 +43,7 @@ public struct ReflexLatencyReport: Codable, Equatable, Sendable {
public var decisionMS: ReflexLatencyPercentiles
public var actionProjectionMS: ReflexLatencyPercentiles
public var inputMS: ReflexLatencyPercentiles
+ public var componentLatencyMS: [String: ReflexLatencyPercentiles]
public var captureFPS: Double?
public var perceptionFPS: Double?
public var controllerTickRate: Double?
@@ -63,6 +64,7 @@ public struct ReflexLatencyReport: Codable, Equatable, Sendable {
decisionMS: ReflexLatencyPercentiles,
actionProjectionMS: ReflexLatencyPercentiles = ReflexLatencyPercentiles(),
inputMS: ReflexLatencyPercentiles,
+ componentLatencyMS: [String: ReflexLatencyPercentiles] = [:],
captureFPS: Double? = nil,
perceptionFPS: Double? = nil,
controllerTickRate: Double? = nil,
@@ -82,6 +84,7 @@ public struct ReflexLatencyReport: Codable, Equatable, Sendable {
self.decisionMS = decisionMS
self.actionProjectionMS = actionProjectionMS
self.inputMS = inputMS
+ self.componentLatencyMS = componentLatencyMS
self.captureFPS = captureFPS
self.perceptionFPS = perceptionFPS
self.controllerTickRate = controllerTickRate
@@ -127,6 +130,7 @@ public enum ReflexLatencyReportBuilder {
decisionMS: percentiles(traces.compactMap(\.latencyBreakdown.decisionMS)),
actionProjectionMS: percentiles(traces.compactMap(\.latencyBreakdown.actionProjectionMS)),
inputMS: percentiles(traces.compactMap(\.latencyBreakdown.inputMS)),
+ componentLatencyMS: componentLatencyPercentiles(from: traces),
captureFPS: rate(
count: traces.count,
first: traces.compactMap(\.timestamps.captureEnd).first,
@@ -212,11 +216,33 @@ public enum ReflexLatencyReportBuilder {
)
}
}
+
+ private static func componentLatencyPercentiles(
+ from traces: [ReflexTraceRecord]
+ ) -> [String: ReflexLatencyPercentiles] {
+ let components = [
+ "commandParse": "latency.commandParseMS",
+ "launchFocus": "latency.launchFocusMS",
+ "observation": "latency.observationMS",
+ "accessibilityAction": "latency.accessibilityActionMS",
+ "keyboardAction": "latency.keyboardActionMS",
+ "verification": "latency.verificationMS",
+ "yoloSegmentation": "latency.yoloSegmentationMS",
+ "uiUnderstanding": "latency.uiUnderstandingMS",
+ "parakeetTranscription": "latency.parakeetTranscriptionMS"
+ ]
+
+ return components.reduce(into: [:]) { result, item in
+ let values = traces.compactMap { Double($0.metadata[item.value] ?? "") }
+ guard !values.isEmpty else { return }
+ result[item.key] = percentiles(values)
+ }
+ }
}
public enum ReflexLatencyReportFormatter {
public static func lines(for report: ReflexLatencyReport) -> [String] {
- [
+ var lines = [
"reflex latency report",
"mode=\(report.mode.rawValue)",
"traceCount=\(report.traceCount)",
@@ -236,6 +262,17 @@ public enum ReflexLatencyReportFormatter {
"staleActionCount=\(report.staleActionCount)",
"worstTraces=\(report.worstTraces.map { "\($0.traceID):\($0.frameID):\(format($0.softwareLoopMS))" }.joined(separator: ","))"
]
+ lines.insert(
+ contentsOf: componentLines(for: report.componentLatencyMS),
+ at: 13
+ )
+ return lines
+ }
+
+ private static func componentLines(for components: [String: ReflexLatencyPercentiles]) -> [String] {
+ components.keys.sorted().map { key in
+ "componentLatency.\(key)MS=\(format(components[key] ?? ReflexLatencyPercentiles()))"
+ }
}
private static func format(_ percentiles: ReflexLatencyPercentiles) -> String {
diff --git a/apps/Donkey/Sources/DonkeyRuntime/SemanticRunMemoryRetriever.swift b/apps/Donkey/Sources/DonkeyRuntime/SemanticRunMemoryRetriever.swift
new file mode 100644
index 00000000..965577de
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/SemanticRunMemoryRetriever.swift
@@ -0,0 +1,99 @@
+import DonkeyContracts
+import Foundation
+
+public protocol RunMemoryEmbeddingProviding: Sendable {
+ func embedding(for text: String) async -> [Double]
+}
+
+public struct LexicalRunMemoryEmbeddingProvider: RunMemoryEmbeddingProviding {
+ public init() {}
+
+ public func embedding(for text: String) async -> [Double] {
+ let tokens = Set(Self.tokens(in: text))
+ return Self.vocabulary.map { tokens.contains($0) ? 1 : 0 }
+ }
+
+ private static let vocabulary = [
+ "app", "button", "field", "form", "media", "music", "pdf", "play", "search", "weather"
+ ]
+
+ fileprivate static func tokens(in text: String) -> [String] {
+ text
+ .lowercased()
+ .split { !$0.isLetter && !$0.isNumber }
+ .map(String.init)
+ }
+}
+
+public struct SemanticRunMemoryRetriever: Sendable {
+ public var embeddingProvider: any RunMemoryEmbeddingProviding
+ public var embeddingModelID: String
+
+ public init(
+ embeddingProvider: any RunMemoryEmbeddingProviding = LexicalRunMemoryEmbeddingProvider(),
+ embeddingModelID: String = "local-semantic-memory-embedding-contract-v1"
+ ) {
+ self.embeddingProvider = embeddingProvider
+ self.embeddingModelID = embeddingModelID
+ }
+
+ public func retrieve(
+ query: RunMemorySemanticQuery,
+ records: [RunMemoryRecord]
+ ) async -> [RunMemorySemanticResult] {
+ let filtered = records.filter { record in
+ if let scope = query.scope, record.scope != scope { return false }
+ if let targetID = query.targetID, record.targetID != targetID { return false }
+ return true
+ }
+ let queryEmbedding = await embeddingProvider.embedding(for: query.text)
+ let scored: [RunMemorySemanticResult] = await filtered.asyncMap { record in
+ let recordEmbedding = await embeddingProvider.embedding(for: record.value)
+ let relevance = cosineSimilarity(queryEmbedding, recordEmbedding)
+ return RunMemorySemanticResult(
+ record: record,
+ relevance: relevance,
+ embeddingModelID: embeddingModelID,
+ metadata: [
+ "retriever": "semantic-run-memory",
+ "budget.maxRecords": String(query.budget.maxRecords),
+ "budget.maxPromptCharacters": String(query.budget.maxPromptCharacters)
+ ]
+ )
+ }
+
+ var promptCharacters = 0
+ var results: [RunMemorySemanticResult] = []
+ for result in scored
+ .filter({ $0.relevance >= query.budget.minRelevance })
+ .sorted(by: { $0.relevance > $1.relevance })
+ {
+ guard results.count < query.budget.maxRecords else { break }
+ let nextCharacters = promptCharacters + result.record.value.count
+ guard nextCharacters <= query.budget.maxPromptCharacters else { break }
+ promptCharacters = nextCharacters
+ results.append(result)
+ }
+ return results
+ }
+
+ private func cosineSimilarity(_ lhs: [Double], _ rhs: [Double]) -> Double {
+ guard lhs.count == rhs.count, !lhs.isEmpty else { return 0 }
+ let dot = zip(lhs, rhs).reduce(0) { $0 + $1.0 * $1.1 }
+ let lhsMagnitude = sqrt(lhs.reduce(0) { $0 + $1 * $1 })
+ let rhsMagnitude = sqrt(rhs.reduce(0) { $0 + $1 * $1 })
+ guard lhsMagnitude > 0, rhsMagnitude > 0 else { return 0 }
+ return dot / (lhsMagnitude * rhsMagnitude)
+ }
+}
+
+private extension Array {
+ func asyncMap<T>(_ transform: (Element) async -> T) async -> [T] {
+ var values: [T] = []
+ values.reserveCapacity(count)
+ for element in self {
+ values.append(await transform(element))
+ }
+ return values
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift
index c1cf432b..f96dc681 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift
@@ -6,6 +6,8 @@ public struct ScreenshotSegmentationRequest: Equatable, Sendable {
public var frameID: String
public var targetID: String
public var cropID: String
+ public var cropImageFileURL: URL?
+ public var artifactURL: URL?
public var cropBounds: HotLoopRect
public var pixelSize: HotLoopSize
public var metadata: [String: String]
@@ -15,6 +17,8 @@ public struct ScreenshotSegmentationRequest: Equatable, Sendable {
frameID: String,
targetID: String,
cropID: String,
+ cropImageFileURL: URL? = nil,
+ artifactURL: URL? = nil,
cropBounds: HotLoopRect,
pixelSize: HotLoopSize,
metadata: [String: String] = [:]
@@ -23,6 +27,8 @@ public struct ScreenshotSegmentationRequest: Equatable, Sendable {
self.frameID = frameID
self.targetID = targetID
self.cropID = cropID
+ self.cropImageFileURL = cropImageFileURL
+ self.artifactURL = artifactURL
self.cropBounds = cropBounds
self.pixelSize = pixelSize
self.metadata = metadata
@@ -102,6 +108,7 @@ public protocol ScreenshotSegmentationBackend: Sendable {
public enum ScreenshotSegmentationRunnerError: Error, Equatable, Sendable {
case noModelCandidate
case backendUnavailable(String)
+ case invalidOutput(String)
}
public struct UnavailableScreenshotSegmentationBackend: ScreenshotSegmentationBackend {
@@ -115,6 +122,104 @@ public struct UnavailableScreenshotSegmentationBackend: ScreenshotSegmentationBa
}
}
+public struct ProcessBackedScreenshotSegmentationBackend: ScreenshotSegmentationBackend {
+ public var sidecarRunner: any LocalJSONSidecarRunning
+ public var encoder: JSONEncoder
+ public var decoder: JSONDecoder
+
+ public init(
+ sidecarRunner: any LocalJSONSidecarRunning = ProcessBackedLocalJSONSidecarRunner(),
+ encoder: JSONEncoder = JSONEncoder(),
+ decoder: JSONDecoder = JSONDecoder()
+ ) {
+ self.sidecarRunner = sidecarRunner
+ self.encoder = encoder
+ self.decoder = decoder
+ }
+
+ public func segment(
+ request: ScreenshotSegmentationRequest,
+ model: OffTheShelfVisionModelCandidate
+ ) async throws -> ScreenshotSegmentationBackendResult {
+ let input = YOLOSidecarRequest(
+ traceID: request.traceID,
+ frameID: request.frameID,
+ targetID: request.targetID,
+ cropID: request.cropID,
+ cropImagePath: request.cropImageFileURL?.path,
+ artifactURL: request.artifactURL?.absoluteString,
+ cropBounds: request.cropBounds,
+ pixelSize: request.pixelSize,
+ modelID: model.id,
+ modelName: model.modelName,
+ metadata: request.metadata
+ )
+ let result = await sidecarRunner.run(
+ LocalJSONSidecarRequest(
+ environmentVariableName: "DONKEY_YOLO_SEGMENTER",
+ inputData: try encoder.encode(input),
+ timeoutMS: Int(model.metadata["timeoutMS"] ?? "4000") ?? 4_000,
+ metadata: [
+ "sidecar.role": "screenshotSegmentation",
+ "modelID": model.id,
+ "modelName": model.modelName
+ ]
+ )
+ )
+
+ guard result.status == .completed else {
+ throw ScreenshotSegmentationRunnerError.backendUnavailable(
+ result.metadata["sidecar.reason"] ?? result.status.rawValue
+ )
+ }
+
+ do {
+ let response = try decoder.decode(YOLOSidecarResponse.self, from: result.outputData)
+ return ScreenshotSegmentationBackendResult(
+ masks: response.masks,
+ preprocessMS: response.preprocessMS,
+ modelInferenceMS: response.modelInferenceMS,
+ metadata: result.metadata.merging(response.metadata) { current, _ in current }
+ )
+ } catch {
+ throw ScreenshotSegmentationRunnerError.invalidOutput(String(describing: error))
+ }
+ }
+}
+
+private struct YOLOSidecarRequest: Codable, Equatable, Sendable {
+ var traceID: String
+ var frameID: String
+ var targetID: String
+ var cropID: String
+ var cropImagePath: String?
+ var artifactURL: String?
+ var cropBounds: HotLoopRect
+ var pixelSize: HotLoopSize
+ var modelID: String
+ var modelName: String
+ var metadata: [String: String]
+}
+
+private struct YOLOSidecarResponse: Codable, Equatable, Sendable {
+ var masks: [ScreenshotSegmentationMask]
+ var preprocessMS: Double
+ var modelInferenceMS: Double
+ var metadata: [String: String]
+
+ init(
+ masks: [ScreenshotSegmentationMask] = [],
+ preprocessMS: Double = 0,
+ modelInferenceMS: Double = 0,
+ metadata: [String: String] = [:]
+ ) {
+ self.masks = masks
+ self.preprocessMS = preprocessMS
+ self.modelInferenceMS = modelInferenceMS
+ self.metadata = metadata
+ }
+}
+
public struct YOLOScreenshotSegmentationRunner: Sendable {
public var model: OffTheShelfVisionModelCandidate
public var backend: any ScreenshotSegmentationBackend
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index c06592d9..caba69cd 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -103,28 +103,27 @@ struct AIHarnessAdapterTests {
#expect(selected.endpoint.absoluteString == "local://nvidia/parakeet-tdt-0.6b-v3")
#expect(selected.docsURL.absoluteString == "https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3")
#expect(selected.capabilities == [.audioInput])
- #expect(selected.rollbackID == "local-voice-transcription-whisper-large-v3-turbo")
+ #expect(selected.rollbackID == nil)
#expect(selected.metadata["runtime"] == "nvidia-nemo")
#expect(selected.metadata["local"] == "true")
- #expect(selected.metadata["fallbackModelID"] == "openai/whisper-large-v3-turbo")
+ #expect(selected.metadata["fallbackPolicy"] == "none")
+ #expect(selected.metadata["fallbackModelID"] == nil)
}
@Test
- func voiceTranscriptionRouteFallsBackToWhisperWhenParakeetFailed() throws {
+ func voiceTranscriptionRouteHasNoWhisperFallbackWhenParakeetFailed() throws {
let router = AIModelRouter(registry: .defaultHybridPlanner)
- let selected = try router.route(
- AIModelRouteRequest(
- jobType: .voiceTranscription,
- privacyMode: .privacySensitive,
- failedModelEntryIDs: ["local-voice-transcription-parakeet-tdt-0.6b-v3"],
- requiredCapabilities: [.audioInput]
+ #expect(throws: AIModelRouteError.noMatchingModel) {
+ _ = try router.route(
+ AIModelRouteRequest(
+ jobType: .voiceTranscription,
+ privacyMode: .privacySensitive,
+ failedModelEntryIDs: ["local-voice-transcription-parakeet-tdt-0.6b-v3"],
+ requiredCapabilities: [.audioInput]
+ )
)
- )
-
- #expect(selected.id == "local-voice-transcription-whisper-large-v3-turbo")
- #expect(selected.provider == .localRuntime)
- #expect(selected.modelID == "openai/whisper-large-v3-turbo")
+ }
}
@Test
@@ -160,6 +159,91 @@ struct AIHarnessAdapterTests {
#expect(result.trace.metadata["localOnly"] == "true")
}
+ @Test
+ func processBackedParakeetRuntimeDecodesSidecarTranscript() async throws {
+ let runtime = ProcessBackedParakeetTranscriptionRuntime(
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: Data("""
+ {"text":"play Coldplay","language":"en","confidence":0.94,"segments":["play Coldplay"],"metadata":{"decoder":"fake-parakeet"}}
+ """.utf8),
+ metadata: ["sidecar.reason": "completed"]
+ )
+ )
+ )
+ let transcript = try await runtime.transcribe(
+ audio: LocalVoiceAudioBuffer(
+ id: "audio-sidecar",
+ durationMS: 800,
+ data: Data([1, 2, 3])
+ ),
+ model: try AIModelRouter(registry: .defaultHybridPlanner).route(
+ AIModelRouteRequest(
+ jobType: .voiceTranscription,
+ requiredCapabilities: [.audioInput],
+ allowedProviders: [.localRuntime]
+ )
+ )
+ )
+
+ #expect(transcript.text == "play Coldplay")
+ #expect(transcript.language == "en")
+ #expect(transcript.metadata["decoder"] == "fake-parakeet")
+ }
+
+ @Test
+ func processBackedParakeetRuntimeFailsClearlyWhenUnavailable() async throws {
+ let runtime = ProcessBackedParakeetTranscriptionRuntime(
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .unavailable,
+ metadata: ["sidecar.reason": "missingEnvironmentVariable"]
+ )
+ )
+ )
+
+ await #expect(throws: LocalVoiceTranscriptionRuntimeError.runtimeUnavailable("missingEnvironmentVariable")) {
+ _ = try await runtime.transcribe(
+ audio: LocalVoiceAudioBuffer(id: "audio-missing", durationMS: 10, data: Data()),
+ model: try AIModelRouter(registry: .defaultHybridPlanner).route(
+ AIModelRouteRequest(
+ jobType: .voiceTranscription,
+ requiredCapabilities: [.audioInput],
+ allowedProviders: [.localRuntime]
+ )
+ )
+ )
+ }
+ }
+
+ @Test
+ func localJSONSidecarRunnerReportsMissingEnvAndNonzeroExit() async {
+ let missing = await ProcessBackedLocalJSONSidecarRunner(environment: [:]).run(
+ LocalJSONSidecarRequest(
+ environmentVariableName: "DONKEY_PARAKEET_TRANSCRIBER",
+ inputData: Data("{}".utf8),
+ timeoutMS: 100
+ )
+ )
+ #expect(missing.status == .unavailable)
+ #expect(missing.metadata["sidecar.reason"] == "missingEnvironmentVariable")
+
+ let failed = await ProcessBackedLocalJSONSidecarRunner(
+ environment: ["DONKEY_TEST_SIDECAR": "/bin/false"]
+ )
+ .run(
+ LocalJSONSidecarRequest(
+ environmentVariableName: "DONKEY_TEST_SIDECAR",
+ inputData: Data("{}".utf8),
+ timeoutMS: 100
+ )
+ )
+ #expect(failed.status == .failed)
+ #expect(failed.exitCode != 0)
+ #expect(failed.metadata["sidecar.reason"] == "nonZeroExit")
+ }
+
@Test
func ollamaTaskIntentAdapterBuildsLocalRequestAndDecodesValidatedIntent() async throws {
let httpClient = FakeAIHTTPClient(
@@ -416,6 +500,75 @@ struct AIHarnessAdapterTests {
#expect(result.metadata["selectedModelID"] == "gpt-5.2")
}
+ @Test
+ func semanticMemoryRetrievalUsesBudgetsAndTargetScope() async {
+ let records = [
+ memoryRecord(id: "weather", value: "Weather app search field accepts city names.", targetID: "weather-app"),
+ memoryRecord(id: "music", value: "Music app can play Coldplay from the search field.", targetID: "music-app")
+ ]
+ let retriever = SemanticRunMemoryRetriever()
+
+ let results = await retriever.retrieve(
+ query: RunMemorySemanticQuery(
+ text: "play music",
+ targetID: "music-app",
+ budget: RunMemoryRetrievalBudget(maxRecords: 1, maxPromptCharacters: 80, minRelevance: 0.1)
+ ),
+ records: records
+ )
+
+ #expect(results.map(\.record.id) == ["music"])
+ #expect(results.first?.embeddingModelID == "local-semantic-memory-embedding-contract-v1")
+ }
+
+ @Test
+ func redactorCoversRemoteBoundModelContext() {
+ let result = AIHarnessRedactor().redact(
+ "email [email protected] password: hunter2",
+ surface: .modelContext
+ )
+
+ #expect(result.redactedText.contains("[redacted-email]"))
+ #expect(result.redactedText.contains("[redacted-secret]"))
+ #expect(result.redactionCount == 2)
+ }
+
+ @Test
+ func modelObservabilityAggregatesLatencyValidityCostAndRecovery() {
+ let report = AIModelObservabilityReportBuilder.build(from: [
+ modelTrace(id: "call-1", status: .completed, validationStatus: "schemaDecoded", latencyMS: 20, metadata: ["cost.estimatedUSD": "0.01"]),
+ modelTrace(id: "call-2", status: .invalidOutput, validationStatus: "invalid", latencyMS: 40, metadata: ["recovery.success": "true"])
+ ])
+
+ #expect(report.callCount == 2)
+ #expect(report.statusCounts["completed"] == 1)
+ #expect(report.validationStatusCounts["invalid"] == 1)
+ #expect(report.acceptedCount == 1)
+ #expect(report.recoverySuccessCount == 1)
+ #expect(report.totalEstimatedCostUSD == 0.01)
+ #expect(report.latencyMS.p95 == 20)
+ }
+
+ @Test
+ func providerDecodedMemoryProposalsUseDeterministicApprover() throws {
+ let proposal = RunMemoryWriteProposal(
+ id: "proposal-1",
+ proposedBy: .model,
+ record: memoryRecord(id: "record-1", value: "Music app search works for artist names.", targetID: "music-app"),
+ rationale: "provider decoded"
+ )
+ let data = try JSONEncoder().encode([proposal])
+
+ let decisions = try ProviderDecodedMemoryProposalHandler.decisions(
+ from: data,
+ decidedAt: timestamp(20)
+ )
+
+ #expect(decisions.first?.approval.approved == true)
+ #expect(decisions.first?.storedRecord?.id == "record-1")
+ #expect(decisions.first?.approval.approver == "deterministic-memory-approver-v1")
+ }
+
private func adapterRequest() -> PlannerHintAdapterRequest {
PlannerHintAdapterRequest(
context: RunContextPackage(
@@ -546,6 +699,47 @@ struct AIHarnessAdapterTests {
clock.next()
}
}
+
+ private func memoryRecord(
+ id: String,
+ value: String,
+ targetID: String
+ ) -> RunMemoryRecord {
+ RunMemoryRecord(
+ id: id,
+ scope: .target,
+ kind: .targetFact,
+ targetID: targetID,
+ value: value,
+ createdAt: timestamp(10),
+ expiresAt: timestamp(1_000),
+ durable: false,
+ source: RunMemorySource(traceID: "trace-\(id)", summary: "test source")
+ )
+ }
+
+ private func modelTrace(
+ id: String,
+ status: AIModelCallStatus,
+ validationStatus: String,
+ latencyMS: Double,
+ metadata: [String: String] = [:]
+ ) -> AIModelCallTrace {
+ AIModelCallTrace(
+ id: id,
+ role: .plannerHint,
+ provider: .openAI,
+ modelID: "gpt-5.2",
+ promptVersion: "planner-hint-v1",
+ schemaID: "planner-hint-v1",
+ latencyMS: latencyMS,
+ timeoutMS: 8_000,
+ status: status,
+ validationStatus: validationStatus,
+ sourceTraceID: "trace-\(id)",
+ metadata: metadata
+ )
+ }
}
private final class FixedTraceClock: @unchecked Sendable {
@@ -577,6 +771,14 @@ private struct FakeVoiceRuntime: LocalVoiceTranscriptionRuntime {
}
}
+private struct FakeSidecarRunner: LocalJSONSidecarRunning {
+ var result: LocalJSONSidecarResult
+
+ func run(_ request: LocalJSONSidecarRequest) async -> LocalJSONSidecarResult {
+ result
+ }
+}
+
private final class FakeAIHTTPClient: AIHTTPClient, @unchecked Sendable {
var data: Data
var statusCode: Int
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift
new file mode 100644
index 00000000..6ca85a30
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift
@@ -0,0 +1,157 @@
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct LocalModelRuntimeSetupTests {
+ @Test
+ func setupInstructionsDescribeDownloadThenAppRegistration() throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let manager = try LocalModelRuntimeSetupManager(baseDirectory: root)
+ let instructions = manager.instructions()
+
+ #expect(instructions.count == 3)
+ #expect(instructions.map(\.spec.id).contains(.parakeetTranscriber))
+ #expect(instructions.first { $0.spec.id == .parakeetTranscriber }?.spec.environmentVariableName == "DONKEY_PARAKEET_TRANSCRIBER")
+ #expect(instructions.first { $0.spec.id == .yoloSegmenter }?.spec.environmentVariableName == "DONKEY_YOLO_SEGMENTER")
+ #expect(instructions.first { $0.spec.id == .uiUnderstander }?.spec.environmentVariableName == "DONKEY_UI_UNDERSTANDER")
+ #expect(instructions.first?.spec.installSteps.first?.contains("Download") == true)
+ }
+
+ @Test
+ func registerDownloadedRuntimeStoresExecutablePathInApplicationSupportRegistry() throws {
+ let root = temporaryDirectory()
+ let download = temporaryDirectory()
+ defer {
+ try? FileManager.default.removeItem(at: root)
+ try? FileManager.default.removeItem(at: download)
+ }
+ let executableURL = try makeExecutable(
+ root: download,
+ relativePath: "bin/donkey-yolo-segmenter"
+ )
+ let manager = try LocalModelRuntimeSetupManager(baseDirectory: root)
+
+ let installation = try manager.registerDownloadedRuntime(
+ runtimeID: .yoloSegmenter,
+ downloadedDirectory: download
+ )
+ let status = try manager.status(for: .yoloSegmenter)
+ let environment = try manager.configuredEnvironment()
+
+ #expect(installation.executablePath == executableURL.path)
+ #expect(status.state == .installed)
+ #expect(status.installation?.downloadedDirectoryPath == download.path)
+ #expect(environment["DONKEY_YOLO_SEGMENTER"] == executableURL.path)
+ }
+
+ @Test
+ func registerDownloadedRuntimeFailsWhenExecutableIsMissingOrNotExecutable() throws {
+ let root = temporaryDirectory()
+ let download = temporaryDirectory()
+ defer {
+ try? FileManager.default.removeItem(at: root)
+ try? FileManager.default.removeItem(at: download)
+ }
+ let manager = try LocalModelRuntimeSetupManager(baseDirectory: root)
+
+ #expect(throws: LocalModelRuntimeSetupError.missingDownloadedExecutable(
+ runtimeID: .parakeetTranscriber,
+ expectedRelativePath: "bin/donkey-parakeet-transcriber"
+ )) {
+ _ = try manager.registerDownloadedRuntime(
+ runtimeID: .parakeetTranscriber,
+ downloadedDirectory: download
+ )
+ }
+
+ let executableURL = try makeFile(
+ root: download,
+ relativePath: "bin/donkey-parakeet-transcriber",
+ permissions: 0o644
+ )
+ #expect(throws: LocalModelRuntimeSetupError.downloadedExecutableNotExecutable(
+ runtimeID: .parakeetTranscriber,
+ path: executableURL.path
+ )) {
+ _ = try manager.registerDownloadedRuntime(
+ runtimeID: .parakeetTranscriber,
+ downloadedDirectory: download
+ )
+ }
+ }
+
+ @Test
+ func processRunnerResolvesAppManagedRuntimeWhenShellEnvironmentIsMissing() async throws {
+ let root = temporaryDirectory()
+ let download = temporaryDirectory()
+ defer {
+ try? FileManager.default.removeItem(at: root)
+ try? FileManager.default.removeItem(at: download)
+ }
+ let executableURL = URL(fileURLWithPath: "/bin/cat")
+ let manager = try LocalModelRuntimeSetupManager(baseDirectory: root)
+ try manager.registerExecutable(
+ runtimeID: .parakeetTranscriber,
+ executableURL: executableURL,
+ downloadedDirectory: download
+ )
+ let resolver = LocalModelRuntimeExecutableResolver {
+ try LocalModelRuntimeSetupManager(baseDirectory: root)
+ }
+ let runner = ProcessBackedLocalJSONSidecarRunner(
+ environment: [:],
+ executableResolver: { environmentVariableName, _ in
+ resolver.executablePath(environmentVariableName: environmentVariableName)
+ }
+ )
+
+ let result = await runner.run(
+ LocalJSONSidecarRequest(
+ environmentVariableName: "DONKEY_PARAKEET_TRANSCRIBER",
+ inputData: Data("{\"ok\":true}".utf8),
+ timeoutMS: 1_000
+ )
+ )
+
+ #expect(result.status == .completed)
+ #expect(String(decoding: result.outputData, as: UTF8.self) == "{\"ok\":true}")
+ #expect(result.metadata["sidecar.executablePath"] == executableURL.path)
+ }
+
+ private func makeExecutable(
+ root: URL,
+ relativePath: String
+ ) throws -> URL {
+ try makeFile(root: root, relativePath: relativePath, permissions: 0o755)
+ }
+
+ private func makeFile(
+ root: URL,
+ relativePath: String,
+ permissions: Int
+ ) throws -> URL {
+ let url = relativePath
+ .split(separator: "/")
+ .reduce(root) { partialURL, component in
+ partialURL.appendingPathComponent(String(component), isDirectory: false)
+ }
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ try Data("#!/bin/sh\ncat\n".utf8).write(to: url)
+ try FileManager.default.setAttributes(
+ [.posixPermissions: permissions],
+ ofItemAtPath: url.path
+ )
+ return url
+ }
+
+ private func temporaryDirectory() -> URL {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-runtime-setup-tests-\(UUID().uuidString)", isDirectory: true)
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift
index 352968b1..b314f3f8 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ManualCaptureDebugCommandTests.swift
@@ -58,6 +58,49 @@ struct ManualCaptureDebugCommandTests {
}
}
+ @Test
+ func localRuntimeInstallCommandsParseStatusInstructionsAndInstall() throws {
+ #expect(try ManualCaptureDebugCommandParser.parse(
+ arguments: ["Donkey", "--local-runtime-status"]
+ ) == .localRuntimeStatus)
+ #expect(try ManualCaptureDebugCommandParser.parse(
+ arguments: ["Donkey", "--local-runtime-instructions"]
+ ) == .localRuntimeInstructions)
+
+ let command = try ManualCaptureDebugCommandParser.parse(
+ arguments: [
+ "Donkey",
+ "--install-local-runtime",
+ "--runtime-id",
+ "yolo-segmenter",
+ "--runtime-source",
+ "/tmp/yolo-runtime"
+ ]
+ )
+
+ #expect(command == .installLocalRuntime(
+ LocalRuntimeInstallDebugOptions(
+ runtimeID: .yoloSegmenter,
+ sourceDirectory: URL(fileURLWithPath: "/tmp/yolo-runtime")
+ )
+ ))
+ }
+
+ @Test
+ func invalidLocalRuntimeIDReturnsCommandError() throws {
+ #expect(throws: ManualCaptureDebugCommandParseError.invalidRuntimeID("weather")) {
+ _ = try ManualCaptureDebugCommandParser.parse(
+ arguments: [
+ "--install-local-runtime",
+ "--runtime-id",
+ "weather",
+ "--runtime-source",
+ "/tmp/runtime"
+ ]
+ )
+ }
+ }
+
@Test
func missingWindowIDValueReturnsCommandError() throws {
#expect(throws: ManualCaptureDebugCommandParseError.missingValue("--window-id")) {
@@ -124,6 +167,23 @@ struct ManualCaptureDebugCommandTests {
])
}
+ @Test
+ func runtimeSetupFormattersPrintInstructionsAndStatus() throws {
+ let manager = try LocalModelRuntimeSetupManager(baseDirectory: temporaryDirectory())
+ let instructionLines = ManualCaptureDebugCommandFormatter.lines(
+ for: manager.instructions()
+ )
+ let statusLines = ManualCaptureDebugCommandFormatter.lines(
+ for: try manager.statuses()
+ )
+
+ #expect(instructionLines.contains("local runtime setup instructions"))
+ #expect(instructionLines.contains("runtime=parakeet-transcriber"))
+ #expect(instructionLines.contains("expectedExecutable=bin/donkey-parakeet-transcriber"))
+ #expect(statusLines.contains("local runtime status"))
+ #expect(statusLines.contains("runtime=yolo-segmenter | state=notInstalled | env=DONKEY_YOLO_SEGMENTER | executable=- | reason=noRegisteredRuntime"))
+ }
+
@Test
func manualCaptureModeCanDriveExistingServiceWithExplicitWindowID() async throws {
let root = temporaryDirectory()
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift
index e5c78058..0f310a63 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift
@@ -127,6 +127,7 @@ struct OffTheShelfVisionPerceptionTests {
frameID: "frame-yolo",
targetID: "target-yolo",
cropID: "crop-search",
+ cropImageFileURL: URL(fileURLWithPath: "/tmp/crop-search.png"),
cropBounds: HotLoopRect(x: 0, y: 0, width: 320, height: 180, space: .window),
pixelSize: HotLoopSize(width: 320, height: 180, space: .crop)
)
@@ -145,6 +146,93 @@ struct OffTheShelfVisionPerceptionTests {
#expect(signal.metadata["requiresLocalBenchmark"] == "true")
}
+ @Test
+ func processBackedYOLORuntimeDecodesSidecarMasks() async throws {
+ let backend = ProcessBackedScreenshotSegmentationBackend(
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: Data("""
+ {"masks":[{"id":"mask-play","label":"play-button","bounds":{"x":0.2,"y":0.3,"width":0.4,"height":0.1,"space":"normalizedTarget"},"confidence":0.88,"pointCount":12,"metadata":{"source":"fake-yolo"}}],"preprocessMS":4,"modelInferenceMS":11,"metadata":{"backend":"fake-sidecar-yolo"}}
+ """.utf8),
+ metadata: ["sidecar.reason": "completed"]
+ )
+ )
+ )
+
+ let result = try await backend.segment(
+ request: ScreenshotSegmentationRequest(
+ traceID: "trace-sidecar-yolo",
+ frameID: "frame-sidecar-yolo",
+ targetID: "target-sidecar-yolo",
+ cropID: "crop-play",
+ artifactURL: URL(string: "donkey-artifact://crop-play"),
+ cropBounds: HotLoopRect(x: 0, y: 0, width: 100, height: 100, space: .window),
+ pixelSize: HotLoopSize(width: 100, height: 100, space: .crop)
+ ),
+ model: OffTheShelfVisionModelCatalog.yolo26NanoScreenshotSegmentation
+ )
+
+ #expect(result.masks.first?.label == "play-button")
+ #expect(result.preprocessMS == 4)
+ #expect(result.modelInferenceMS == 11)
+ #expect(result.metadata["backend"] == "fake-sidecar-yolo")
+ }
+
+ @Test
+ func processBackedYOLORuntimeFailsClearlyWhenUnavailable() async throws {
+ let backend = ProcessBackedScreenshotSegmentationBackend(
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .unavailable,
+ metadata: ["sidecar.reason": "missingEnvironmentVariable"]
+ )
+ )
+ )
+
+ await #expect(throws: ScreenshotSegmentationRunnerError.backendUnavailable("missingEnvironmentVariable")) {
+ _ = try await backend.segment(
+ request: ScreenshotSegmentationRequest(
+ traceID: "trace-missing-yolo",
+ frameID: "frame-missing-yolo",
+ targetID: "target-missing-yolo",
+ cropID: "crop-missing",
+ cropBounds: HotLoopRect(x: 0, y: 0, width: 100, height: 100, space: .window),
+ pixelSize: HotLoopSize(width: 100, height: 100, space: .crop)
+ ),
+ model: OffTheShelfVisionModelCatalog.yolo26NanoScreenshotSegmentation
+ )
+ }
+ }
+
+ @Test
+ func localUIUnderstandingSidecarFeedsObservationShape() async throws {
+ let adapter = ProcessBackedLocalUIUnderstandingAdapter(
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: Data("""
+ {"visibleText":{"title":"Music","result":"Coldplay"},"controls":[{"id":"search","label":"Search","kind":"searchField","frame":{"x":0.1,"y":0.1,"width":0.8,"height":0.08,"space":"normalizedTarget"},"confidence":0.86,"metadata":{"controlID":"search"}}],"formFields":[],"confidence":0.84,"metadata":{"understander":"fake-local-llm"}}
+ """.utf8),
+ metadata: ["sidecar.reason": "completed"]
+ )
+ )
+ )
+ let request = LocalUIUnderstandingRequest(
+ traceID: "trace-ui-understanding",
+ targetID: "music-app",
+ imageFileURL: URL(fileURLWithPath: "/tmp/music-crop.png")
+ )
+
+ let result = try await adapter.understand(request)
+ let observation = result.observation(for: request)
+
+ #expect(observation.availableControls["search"] == true)
+ #expect(observation.visibleText["result"] == "Coldplay")
+ #expect(observation.metadata["directInputActionsAllowed"] == "false")
+ #expect(observation.metadata["understander"] == "fake-local-llm")
+ }
+
private func recordedSignal(
kind: OffTheShelfVisionSignalKind,
id: String,
@@ -255,3 +343,11 @@ private struct FakeScreenshotSegmentationBackend: ScreenshotSegmentationBackend
)
}
}
+
+private struct FakeSidecarRunner: LocalJSONSidecarRunning {
+ var result: LocalJSONSidecarResult
+
+ func run(_ request: LocalJSONSidecarRequest) async -> LocalJSONSidecarResult {
+ result
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift
index 90364100..09684e6a 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ReflexLatencyReportTests.swift
@@ -45,7 +45,24 @@ struct ReflexLatencyReportTests {
@Test
func reportFormatterPrintsCliFriendlyLines() {
let report = ReflexLatencyReportBuilder.build(
- from: [trace(index: 1, softwareLoopMS: 10, fallbackReason: nil)],
+ from: [
+ trace(
+ index: 1,
+ softwareLoopMS: 10,
+ fallbackReason: nil,
+ metadata: [
+ "latency.commandParseMS": "4",
+ "latency.launchFocusMS": "11",
+ "latency.observationMS": "7",
+ "latency.accessibilityActionMS": "5",
+ "latency.keyboardActionMS": "6",
+ "latency.verificationMS": "9",
+ "latency.yoloSegmentationMS": "21",
+ "latency.uiUnderstandingMS": "16",
+ "latency.parakeetTranscriptionMS": "31"
+ ]
+ )
+ ],
mode: .captureOnly,
droppedFrameCount: 1
)
@@ -57,6 +74,9 @@ struct ReflexLatencyReportTests {
#expect(lines.contains("traceCount=1"))
#expect(lines.contains("droppedFrameCount=1"))
#expect(lines.contains("softwareLoopMS=p50=10.00,p95=10.00,p99=10.00"))
+ #expect(lines.contains("componentLatency.commandParseMS=p50=4.00,p95=4.00,p99=4.00"))
+ #expect(lines.contains("componentLatency.yoloSegmentationMS=p50=21.00,p95=21.00,p99=21.00"))
+ #expect(lines.contains("componentLatency.parakeetTranscriptionMS=p50=31.00,p95=31.00,p99=31.00"))
}
@Test
@@ -98,10 +118,11 @@ struct ReflexLatencyReportTests {
private func trace(
index: Int,
softwareLoopMS: UInt64,
- fallbackReason: String?
+ fallbackReason: String?,
+ metadata extraMetadata: [String: String] = [:]
) -> ReflexTraceRecord {
let baseMS = UInt64(index * 10)
- var metadata: [String: String] = [:]
+ var metadata = extraMetadata
if let fallbackReason {
metadata["action.fallback"] = "true"
metadata["fallbackReason"] = fallbackReason
diff --git a/docs/README.md b/docs/README.md
index 21589093..fd7f1653 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -4,7 +4,7 @@ This folder is the product and engineering source of truth for capabilities that
Plans describe what we might build. Guides describe what Donkey currently supports and how to maintain it.
-There is an active milestone plan in `plans/master-plan.md`. It tracks the unfinished work needed before the fast local navigation and AI-harness roadmap can be considered complete: generic local-app task knowledge, local JSON/JSONL task-definition loading, installed-app/task resolution, local-model command parsing with catalog validation, local task-context intake, Accessibility control discovery and action planning, review-first document form-fill planning, local voice-transcription model selection and adapter wiring, YOLO screenshot segmentation runner boundaries, local navigation, guarded input, result verification, latency reporting, and optional slow planner recovery. Weather lookup, media playback, and document form-fill are benchmark definitions for this generic system, not source-specific architectures.
+There is an active milestone plan in `plans/master-plan.md`. It tracks the unfinished work needed before the fast local navigation and AI-harness roadmap can be considered complete: generic local-app task knowledge, local JSON/JSONL task-definition loading, installed-app/task resolution, local-model command parsing with catalog validation, local task-context intake, Accessibility control discovery and action planning, review-first document form-fill planning, Parakeet-only local voice transcription, YOLO screenshot segmentation and local UI-understanding sidecar boundaries, post-install local runtime setup without bundled model weights, semantic memory/redaction/model-observability scaffolding, local navigation, guarded input, result verification, latency reporting, and optional slow planner recovery. Weather lookup, media playback, and document form-fill are benchmark definitions for this generic system, not source-specific architectures.
## Product Guides
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index 89ef276e..fb115985 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -26,15 +26,15 @@ Donkey also supports the first cheap perception and deterministic controller sli
Donkey also supports the first off-the-shelf local vision evidence boundary inside the dry-run reflex loop. `RecordedOffTheShelfVisionMetadataCodec` can carry recorded detector, template, OCR, or segmentation observations with crop ids, component ids, model ids, confidence, coordinate spaces, and measured preprocessing/model latency. `OffTheShelfVisionPerceptionAdapter` converts that local evidence into compact `HotLoopPerceptionSignal` values, and `OffTheShelfVisionWorldStateProjector` exposes only typed affordances to the deterministic controller. This is a local perception contract and replay path; it does not yet run a live Core ML, ONNX, OCR, or template matcher over captured pixels.
-Donkey also tracks the first screenshot segmentation model candidate for the off-the-shelf vision boundary. `OffTheShelfVisionModelCatalog` lists Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`) as the current screenshot/crop segmentation candidate, with official docs rechecked on May 17, 2026. The runner boundary can convert injected local backend masks into traceable segmentation evidence, but live screenshot segmentation still requires an installed backend, crop pipeline integration, export/runtime choice, and measured latency before it can enter a guarded live loop.
+Donkey also tracks the first screenshot segmentation model candidate for the off-the-shelf vision boundary. `OffTheShelfVisionModelCatalog` lists Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`) as the current screenshot/crop segmentation candidate, with official docs rechecked on May 17, 2026. `YOLOScreenshotSegmentationRunner` accepts bounded crop metadata plus a crop image or artifact URL, and `ProcessBackedScreenshotSegmentationBackend` calls a local JSON stdin/stdout sidecar from `DONKEY_YOLO_SEGMENTER`. Missing executable configuration, nonzero exits, and invalid output produce explicit unavailable or decoding failures. Decoded masks become the same recorded off-the-shelf segmentation evidence used by replay and dry-run perception.
Donkey also supports the first action-engine guardrail boundary. `ActionEngineGuardrail` accepts typed tap, swipe, key, mouse, controller, and `releaseAll` commands; checks input permission policy, focus guard status, command rate, and maximum hold duration; tracks held-input state; and records replayable command traces. Live input remains disabled by default and requires explicit configuration, an input-allowing policy, a passing focus guard, and an injected input backend. The local-app live runner injects a narrow macOS keyboard backend for guarded key/text commands; other action-engine use still records dry-run traces unless a caller opts into live input. Allowed non-live commands are projected as dry-run traces, live commands record backend execution evidence, denied commands include explicit denial reasons, and `releaseAll` clears held-input state.
-Donkey also supports reflex latency reports and a synthetic replay benchmark. `ReflexLatencyReportBuilder` summarizes reflex traces into p50/p95/p99 latency for software-loop, capture, preprocess/crop-normalize, model inference, perception, state update, controller decision, action projection, and input stages, plus capture/perception/controller rates, dropped frames, stale actions, and worst traces. `ReflexReplayBenchmark` can generate deterministic dry-run traces for capture-only, controller-only, or end-to-end dry-run report modes. The installed debug entrypoint can print a CLI-friendly dry-run latency report with `--dry-run-latency-report`.
+Donkey also supports reflex latency reports and a synthetic replay benchmark. `ReflexLatencyReportBuilder` summarizes reflex traces into p50/p95/p99 latency for software-loop, capture, preprocess/crop-normalize, model inference, perception, state update, controller decision, action projection, and input stages, plus component latency fields for command parse, launch/focus, observation, Accessibility action, keyboard action, verification, YOLO segmentation, UI understanding, and Parakeet transcription when traces include those metadata keys. Reports also include capture/perception/controller rates, dropped frames, stale actions, and worst traces. `ReflexReplayBenchmark` can generate deterministic dry-run traces for capture-only, controller-only, or end-to-end dry-run report modes. The installed debug entrypoint can print a CLI-friendly dry-run latency report with `--dry-run-latency-report`.
Donkey also supports the first fast local-navigation dry-run slice end to end through the dry-run reflex loop. `LocalNavigationMetadataFrameSource` can turn macOS window candidate metadata and optional browser-tab metadata supplied by callers into metadata-only hot-loop frames. `LocalNavigationDryRunPerceptionAdapter` and `LocalNavigationDryRunWorldStateProjector` keep the local-navigation path swappable while preserving the no-remote-model fallback. `LocalNavigationControllerPolicy` can choose traceable dry-run semantic actions such as `focusWindow`, `activateCandidate`, `switchTab`, `wait`, or `observe` from typed state. This slice is metadata-only and side-effect free by default; guarded live-action smoke requires an injected backend, and richer visual inference remains future work.
-Donkey also supports the first generic local-app task catalog, intent, live runner, and local task-definition loading boundary. `TaskIntent` can represent a parsed task, target app, normalized entities, parser source, confidence, and confirmation state. `LocalAppTaskDefinition` describes app-task knowledge as data: target app metadata, deterministic trigger terms, required entities and aliases, workflow steps, observation strategies, and verification rules. `LocalAppTaskDefinitionLoader` can load additional JSON or JSONL task definitions from `~/Library/Application Support/Donkey/TaskDefinitions/` and merge them with built-ins, so new use cases do not require Swift source changes. `LocalAppTaskCatalog` resolves validated intents against known task definitions, checks target-app availability through an injected provider, and exposes built-in definitions such as Weather lookup, Music playback, and PDF/document form-fill as data rather than source-specific adapters. `OllamaTaskIntentAdapter` is the supported primary command parser: it sends the user command and available task definitions to a local Ollama-compatible structured-output model, decodes a `TaskIntent`, and validates it against the catalog before execution can proceed. `LocalAppTaskIntentParser` remains a deterministic fallback and test scaffold for known commands, not the preferred command-understanding path. `LocalAppTaskAdapter` can build a target-app local-navigation metadata request, project dry-run workflow steps, emit guarded keyboard command templates, and verify observed visible text against the requested entity. `LocalAppAccessibilityControlDiscovery` can index controls and form fields from bounded Accessibility snapshots, and `MacAccessibilityActionEngineInputBackend` can execute guarded `AXPress` and `AXSetValue` commands when Accessibility is trusted, focus guard passes, and input policy allows it. `LocalAppTaskLiveRunner` can launch or focus the resolved app, prefer discovered Accessibility commands when available, fall back to guarded keyboard templates, observe visible Accessibility text when trusted, and return a final verification plan. Review-only tasks, such as document form-fill with external data, resolve into a local context snapshot and `DocumentFormFillPlanner` review plan; approved proposals can be converted to guarded Accessibility fill commands, but user-visible approval UI is still required before enabling default live form filling. Live local-model UI understanding remains unsupported.
+Donkey also supports the first generic local-app task catalog, intent, live runner, and local task-definition loading boundary. `TaskIntent` can represent a parsed task, target app, normalized entities, parser source, confidence, and confirmation state. `LocalAppTaskDefinition` describes app-task knowledge as data: target app metadata, deterministic trigger terms, required entities and aliases, workflow steps, observation strategies, and verification rules. `LocalAppTaskDefinitionLoader` can load additional JSON or JSONL task definitions from `~/Library/Application Support/Donkey/TaskDefinitions/` and merge them with built-ins, so new use cases do not require Swift source changes. `LocalAppTaskCatalog` resolves validated intents against known task definitions, checks target-app availability through an injected provider, and exposes built-in definitions such as Weather lookup, Music playback, and PDF/document form-fill as data rather than source-specific adapters. `OllamaTaskIntentAdapter` is the supported primary command parser: it sends the user command and available task definitions to a local Ollama-compatible structured-output model, decodes a `TaskIntent`, and validates it against the catalog before execution can proceed. `LocalAppTaskIntentParser` remains a deterministic fallback and test scaffold for known commands, not the preferred command-understanding path. `LocalAppTaskAdapter` can build a target-app local-navigation metadata request, project dry-run workflow steps, emit guarded keyboard command templates, and verify observed visible text against the requested entity. `LocalAppAccessibilityControlDiscovery` can index controls and form fields from bounded Accessibility snapshots, and `MacAccessibilityActionEngineInputBackend` can execute guarded `AXPress` and `AXSetValue` commands when Accessibility is trusted, focus guard passes, and input policy allows it. `ProcessBackedLocalUIUnderstandingAdapter` can call a local JSON sidecar from `DONKEY_UI_UNDERSTANDER` for bounded screenshot/crop context and return visible text, controls, form fields, and confidence as a `LocalAppTaskObservation`; those results feed observation only and never direct input actions. `LocalAppTaskLiveRunner` can launch or focus the resolved app, prefer discovered Accessibility commands when available, fall back to guarded keyboard templates, observe visible Accessibility text when trusted, and return a final verification plan. Review-only tasks, such as document form-fill with external data, resolve into a local context snapshot and `DocumentFormFillPlanner` review plan. A user-facing document approval UI is intentionally out of scope for this slice; live form filling remains review/planning code until a separate product decision enables it.
Donkey also supports a guarded live-action smoke boundary for local-navigation behavior. `GuardedLiveActionSmokeRunner` requires an end-to-end dry-run result, a latency report with p95 evidence, a non-fallback latest action, explicit input policy allowance, and a passing action-engine focus guard before mapping semantic local-navigation actions to typed action-engine commands. The smoke path records replayable action traces and can execute only through an injected backend.
@@ -42,17 +42,19 @@ Donkey also supports slow-path planner hint contracts. `StructuredPlannerHint` c
Donkey also supports the first slow-planner sidecar beside the dry-run reflex loop. `DryRunSlowPlannerSidecar` can trigger on scene changes, low confidence, repeated fallback/failure, already-complete local-navigation goals, or explicit user instruction. It builds compact planner snapshots from the latest world state, action, bounded trace summaries, optional screenshot artifact references, and run memory. Planner work is notified from the dry-run loop after reflex trace publication in a fire-and-forget task, so model latency is not included in reflex p95. `ValidatedPlannerHintBus` publishes only validated hints, and `PlannerHintAwareControllerPolicy` can expose the latest still-valid hint to a controller without letting planner output become direct input.
-Donkey also supports the first AI harness model registry and router boundary. `AIModelRegistry` stores model roles, providers, literal model ids, endpoints, capabilities, timeouts, prompt versions, eval status, docs URLs, and rollback ids as registry data. `AIModelRouter` routes slow-path jobs by job type, risk, privacy mode, latency tolerance, capabilities, failed-model history, and allowed providers. Privacy-sensitive planner routes prefer local Ollama-compatible entries when they are available. Privacy-sensitive voice-transcription routes prefer local runtime entries and currently select NVIDIA Parakeet TDT 0.6B v3, with Whisper large-v3-turbo as a local rollback candidate. `LocalVoiceTranscriptionAdapter` accepts bounded local audio buffers, routes to the selected local runtime model, returns transcript text plus timing/confidence trace metadata, and marks transcripts as inputs to the normal command parser rather than actions. The default transcription runtime is injectable and unavailable until a local NeMo/Whisper runtime is installed. Literal provider model ids should stay in registry entries, not planner/controller logic.
+Donkey also supports the first AI harness model registry and router boundary. `AIModelRegistry` stores model roles, providers, literal model ids, endpoints, capabilities, timeouts, prompt versions, eval status, docs URLs, and rollback ids as registry data. `AIModelRouter` routes slow-path jobs by job type, risk, privacy mode, latency tolerance, capabilities, failed-model history, and allowed providers. Privacy-sensitive planner routes prefer local Ollama-compatible entries when they are available. Privacy-sensitive voice-transcription routes prefer local runtime entries and select NVIDIA Parakeet TDT 0.6B v3 only; Whisper fallback has been removed. `ProcessBackedParakeetTranscriptionRuntime` calls a local JSON stdin/stdout sidecar from `DONKEY_PARAKEET_TRANSCRIBER`, and missing configuration or nonzero exits fail clearly instead of silently falling back. `LocalVoiceTranscriptionAdapter` accepts bounded local audio buffers, routes to the selected local runtime model, returns transcript text plus timing/confidence trace metadata, and marks transcripts as inputs to the normal command parser rather than actions. Literal provider model ids should stay in registry entries, not planner/controller logic.
-Donkey also supports the first measured screenshot segmentation runner boundary for the YOLO26 screenshot candidate. `YOLOScreenshotSegmentationRunner` accepts bounded crop requests, calls an injected local segmentation backend, converts masks into recorded off-the-shelf vision evidence, and preserves preprocessing/model/adapter latency in the same metadata codec used by the dry-run perception adapter. The default backend is unavailable; live segmentation requires an installed local runtime and target-specific benchmark evidence before it can affect live control.
+Donkey also supports a reusable local JSON sidecar runner for local model processes. `ProcessBackedLocalJSONSidecarRunner` reads executable paths from environment variables first, then from Donkey's app-managed local runtime registry, validates executability, sends request JSON on stdin, captures stdout/stderr, records exit status and latency metadata, and returns explicit unavailable or failed statuses. Current model sidecars use `DONKEY_YOLO_SEGMENTER`, `DONKEY_PARAKEET_TRANSCRIBER`, and `DONKEY_UI_UNDERSTANDER`.
+
+Donkey also supports the first post-install local runtime setup boundary. The app does not ship model weights or local model binaries. `LocalModelRuntimeSetupManager` describes the required Parakeet, YOLO26, and UI-understanding runtime packages, provides user-facing download/setup instructions, validates a user-downloaded runtime folder, and records the executable paths in `~/Library/Application Support/Donkey/LocalModelRuntimes/runtime-installations.json`. After registration, sidecar calls can resolve app-managed executables without shell environment variables. Developer launch arguments can print setup instructions, show install status, or register a downloaded runtime folder.
Donkey also supports the first provider-neutral planner-hint adapter boundary using OpenAI's Responses API. `OpenAIPlannerHintAdapter` reads `OPENAI_API_KEY` from the environment, routes through the model registry, sends a structured-output Responses request with `store: false`, decodes a strict planner-hint JSON response, and records a model-call trace with role, provider, model id, prompt version, schema id, latency, timeout, validation status, and source trace/state ids. Missing credentials, cancellation, timeout, rate limit, invalid output, and provider outage return traceable failures without stopping the reflex loop. Official OpenAI docs were rechecked on May 16, 2026 for the Responses API, `text.format` JSON schema structured outputs, `store: false`, and current model registry default guidance.
Donkey also supports an Ollama-compatible local planner-hint adapter and provider-backed slow planner generator. `OllamaPlannerHintAdapter` sends a local `/api/generate` request with `stream: false` and the same strict planner-hint JSON schema, decodes the local model response into `StructuredPlannerHint`, and records the same model-call trace shape as the OpenAI adapter. `ProviderBackedSlowPlannerHintGenerator` can try local planning first and fall back to the online adapter; either provider can publish only validated hints through the existing slow-planner sidecar and hint bus. Official Ollama docs were checked on May 16, 2026 for the `/api/generate` endpoint, JSON schema `format`, and non-streaming response shape.
-Donkey also supports the first memory boundary for slow-path context. Short-term run memory is in-process and bounded; it can retain the current goal, active valid hints, recent world states, recent failures, user instructions, safety stops, and target records for context assembly. Target memory is stored as scoped, source-linked JSONL records under Application Support by default, with tests and tools able to pass an explicit base directory. Model-proposed memory writes go through a deterministic approver before storage. Target and user scoped records require either an expiry timestamp or an explicit durable flag, and records can be listed or deleted by target, run, user, or record id.
+Donkey also supports the first memory boundary for slow-path context. Short-term run memory is in-process and bounded; it can retain the current goal, active valid hints, recent world states, recent failures, user instructions, safety stops, and target records for context assembly. Target memory is stored as scoped, source-linked JSONL records under Application Support by default, with tests and tools able to pass an explicit base directory. Semantic memory retrieval contracts include target/scope filters, max-record and prompt-character budgets, minimum relevance, and an embedding-provider protocol. Model-proposed or provider-decoded memory writes go through the deterministic approver before storage. Target and user scoped records require either an expiry timestamp or an explicit durable flag, and records can be listed or deleted by target, run, user, or record id.
-Donkey also supports a replay/eval scaffold for model and prompt changes. Planner-hint replay cases summarize recorded traces, decoded hints, validation issues, model-call latency, estimated cost, fallback count, recovery success, and memory-write decisions. `PlannerHintReplayEvaluator` aggregates schema validity, hint acceptance, memory write acceptance and rejection, latency, cost, fallbacks, and recovery success into a promotion report. `AIModelUpdateChecklist` records the model entry, prompt version, `last_verified_at`, docs URLs, eval suite id, rollback model id, and optional report id before model or prompt promotion.
+Donkey also supports a replay/eval scaffold for model and prompt changes. Planner-hint replay cases summarize recorded traces, decoded hints, validation issues, model-call latency, estimated cost, fallback count, recovery success, and memory-write decisions. `PlannerHintReplayEvaluator` aggregates schema validity, hint acceptance, memory write acceptance and rejection, latency, cost, fallbacks, and recovery success into a promotion report. `AIModelObservabilityReportBuilder` aggregates model-call latency, status, provider, schema validity, acceptance, estimated cost, and recovery success across arbitrary `AIModelCallTrace` samples. `AIHarnessRedactor` provides hooks for remote-bound screenshot summaries, DOM summaries, and model context before provider calls. `AIModelUpdateChecklist` records the model entry, prompt version, `last_verified_at`, docs URLs, eval suite id, rollback model id, and optional report id before model or prompt promotion.
Donkey also supports a local run artifact store for durable trace data. Installed app runs are stored under `~/Library/Application Support/Donkey/Runs/<run-id>/`; tests and development tools may pass an explicit base directory override. Each prepared run creates:
@@ -75,7 +77,7 @@ Donkey supports a runtime-level manual target context capture service that wires
The installed executable also supports a developer-only launch-argument entrypoint for manual verification. `--list-window-candidates` prints the current candidate-list labels and durable `windowID` values. `--manual-capture` runs one manual capture, optionally with `--window-id <id>`, `--run-id <safe-id>`, and `--trace-id <safe-id>`, then prints the run folder and artifact paths. These commands are non-interactive and exit before showing the pointer prompt overlay.
-This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, cheap metadata perception, recorded off-the-shelf local vision evidence, screenshot segmentation model-candidate catalog and runner boundary, deterministic controller, local-navigation dry-run, generic local-app task catalog/intent/live-runner boundary, local JSON/JSONL task-definition loading, local task-context intake, Accessibility control discovery/action execution boundary, document form-fill review and approval planning, sample task definitions across weather/media/document domains, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, local voice-transcription model selection and adapter boundary, OpenAI and Ollama-compatible planner adapters, memory, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not bundle live transcription or vision model runtimes, run OCR over captured pixels, provide the user-visible form-fill approval UI, provide a manual capture UI, persist high-volume reflex traces to disk, provide continuous streaming capture, or make model calls required for reflex ticks.
+This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, cheap metadata perception, recorded off-the-shelf local vision evidence, screenshot segmentation model-candidate catalog and sidecar runner boundary, local UI-understanding sidecar observation boundary, post-install local runtime setup/registration boundary, deterministic controller, local-navigation dry-run, generic local-app task catalog/intent/live-runner boundary, local JSON/JSONL task-definition loading, local task-context intake, Accessibility control discovery/action execution boundary, document form-fill review planning, sample task definitions across weather/media/document domains, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, Parakeet-only local voice-transcription sidecar boundary, OpenAI and Ollama-compatible planner adapters, semantic memory/redaction/model-observability scaffolding, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not bundle live transcription or vision model binaries, run OCR over captured pixels by default, provide a manual capture UI, persist high-volume reflex traces to disk, provide continuous streaming capture, or make model calls required for reflex ticks.
## Technical Guidelines
@@ -113,10 +115,15 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic
- Treat planner hints as validated, expiring advice. Controllers may use the latest valid hint, but planner output must never become direct input.
- Keep slow planner work beside the reflex loop. Trigger it from compact state, trace, memory, and artifact references; never await model calls from the hot tick before recording the reflex trace.
- Keep model selection in `AIModelRegistry` data. Do not scatter provider model ids through planner code.
-- Keep local voice transcription as a model-routed local runtime job. Transcription output is transcript text only and must enter the same validated command path as typed input before any task can run.
+- Keep local voice transcription as a Parakeet-only model-routed local runtime job. Transcription output is transcript text only and must enter the same validated command path as typed input before any task can run. If `DONKEY_PARAKEET_TRANSCRIBER` is missing or fails, the voice path fails clearly; it must not silently fall back to Whisper or any remote transcription provider.
+- Keep local model runtimes behind JSON sidecars. Use `DONKEY_YOLO_SEGMENTER`, `DONKEY_PARAKEET_TRANSCRIBER`, and `DONKEY_UI_UNDERSTANDER` for developer overrides, then Donkey's app-managed runtime registry for normal user installs. Return explicit unavailable results when executables are absent.
+- Do not bundle model weights in the app. Users download compatible runtime packages after app install; Donkey validates the selected folder and records executable paths under Application Support.
- Keep privacy-sensitive Responses API calls configured with `store: false` unless an explicit later policy changes that default.
- Treat provider failures as sidecar failures. Missing credentials, timeout, rate limit, invalid output, or outage should leave the controller running on local state and existing valid hints.
- Keep memory writes source-linked and scoped. Model-proposed memory writes must pass the deterministic approver before storage; target and user records require TTL or explicit durable retention.
+- Keep provider-decoded memory proposals on the same deterministic approval path as runtime-created proposals.
+- Keep semantic memory retrieval bounded by target/scope filters, max record count, prompt-character budget, and minimum relevance before adding it to model context.
+- Redact remote-bound screenshot summaries, DOM summaries, and model context before online provider calls.
- Keep target memory inspectable and deleteable by target, run, user, and record id. Do not use memory JSONL as an opaque cache.
- Promote model or prompt changes only after replay/eval records schema validity, hint acceptance, memory acceptance, latency, cost, fallback count, recovery success, docs URLs, and rollback model id.
- Keep reflex trace retention bounded. The current in-memory store is for recent status and tests, not high-volume replay persistence.
@@ -130,7 +137,7 @@ From `apps/Donkey/`:
swift test
```
-The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, recorded off-the-shelf vision evidence projection, screenshot segmentation model-candidate selection and runner evidence encoding, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, local-model task intent request shaping and validation, deterministic local-app task parsing fallback and alias expansion, local task-definition loading, local-app catalog resolution and app availability checks, local task-context intake, Accessibility control discovery, document form-fill review and approval planning, local-app navigation request construction, generic dry-run step projection, guarded keyboard and Accessibility command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, local voice-transcription model routing and adapter tracing, OpenAI Responses request shaping and failure handling, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.
+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, recorded off-the-shelf vision evidence projection, screenshot segmentation model-candidate selection, YOLO sidecar decoding and unavailable states, local UI-understanding observation decoding, local runtime setup instructions/status/registration, app-managed sidecar executable resolution, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, local-model task intent request shaping and validation, deterministic local-app task parsing fallback and alias expansion, local task-definition loading, local-app catalog resolution and app availability checks, local task-context intake, Accessibility control discovery, document form-fill review planning, local-app navigation request construction, generic dry-run step projection, guarded keyboard and Accessibility command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles, component latency fields, replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, Parakeet-only local voice-transcription routing, Parakeet sidecar decoding and unavailable states, local JSON sidecar missing-env/nonzero-exit states, OpenAI Responses request shaping and failure handling, semantic memory retrieval, remote-bound redaction, model-call observability, provider-decoded memory proposal approval, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.
Manual smoke commands:
@@ -138,6 +145,9 @@ Manual smoke commands:
swift run Donkey -- --list-window-candidates
swift run Donkey -- --manual-capture --window-id <id>
swift run Donkey -- --dry-run-latency-report --frame-count 30
+swift run Donkey -- --local-runtime-instructions
+swift run Donkey -- --install-local-runtime --runtime-id yolo-segmenter --runtime-source <downloaded-runtime-folder>
+swift run Donkey -- --local-runtime-status
```
Manual verification on May 16, 2026 confirmed that the list command enumerates current visible Mac windows and that manual capture against a normal Mac app window creates a run folder with 9 ordered coordinator events, one screenshot artifact, and one Accessibility artifact. The verified run targeted a non-frontmost, non-focused Fork window by durable `windowID`.
@@ -174,12 +184,17 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi
- Ollama-compatible local task-intent parsing lives in `apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift`.
- Local voice transcription adapter boundary lives in `apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift`.
- YOLO screenshot segmentation runner boundary lives in `apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift`.
+- Local JSON sidecar running lives in `apps/Donkey/Sources/DonkeyRuntime/LocalJSONSidecarRunner.swift`.
+- Local model runtime setup lives in `apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift`.
+- Local UI-understanding observation lives in `apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift`.
- Slow-planner sidecar triggers, snapshots, validated hint bus, and hint-aware controller wrapper live in `apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift`.
- AI model registry and routing live in `apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift`.
- The OpenAI Responses planner-hint adapter lives in `apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift`.
- The Ollama-compatible local planner-hint adapter and provider-backed slow-planner generator live in `apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift`.
- Memory contracts live in `apps/Donkey/Sources/DonkeyContracts/MemoryContracts.swift`.
- Short-term run memory and target-memory JSONL storage live in `apps/Donkey/Sources/DonkeyRuntime/RunMemoryStore.swift`.
+- Semantic memory retrieval lives in `apps/Donkey/Sources/DonkeyRuntime/SemanticRunMemoryRetriever.swift`.
+- AI redaction, model-call observability, and provider-decoded memory proposal handling live in `apps/Donkey/Sources/DonkeyAI/AIHarnessCompletion.swift`.
- Replay/eval scaffolding lives in `apps/Donkey/Sources/DonkeyAI/AIReplayEvaluation.swift`.
- Recent reflex trace retention lives in `apps/Donkey/Sources/DonkeyRuntime/InMemoryReflexTraceStore.swift`.
- macOS window resolution lives in `apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift`.
diff --git a/plans/master-plan.md b/plans/master-plan.md
index cf4d75ce..cc3058c8 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -55,10 +55,10 @@ The normal Weather benchmark path should work without a remote model call. A tin
## Supported Boundary
-- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, in-memory reflex trace retention, and stage-split latency reports are supported.
-- Fast navigation hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, recorded off-the-shelf detector/template/OCR/segmentation evidence projection, screenshot segmentation model-candidate catalog and runner boundary with Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`), swappable world-state projection, deterministic controller, loop-integrated metadata-only local-navigation dry-run action selection, optional caller-supplied browser-tab metadata, dry-run action projection, generic local-app task intent contracts, data-driven task definitions, local JSON/JSONL task-definition loading, Ollama-compatible local-model command parsing to validated `TaskIntent`, deterministic parsing as fallback/validator, catalog command resolution, target-app availability checks, local task-context intake, Accessibility control discovery, document form-fill review and approval planning, generic dry-run task adaptation, local-navigation request construction, step projection, guarded keyboard and Accessibility command templates, macOS app launch/focus, guarded macOS keyboard input, guarded `AXPress`/`AXSetValue` backend, pointer-prompt typed command submission, Accessibility visible-text observation when trusted, visible-text verification, and built-in task definitions for Weather lookup, media playback, and document form-fill are supported. This is not yet a complete live fast-navigation agent: there is no live local-model UI-understanding fallback, no bundled live YOLO runtime, no bundled live voice-transcription runtime, no user-visible document approval UI, and no manually verified live command-to-result Weather trace yet.
+- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, local model runtime setup/registration in Application Support, in-memory reflex trace retention, and stage-split latency reports are supported.
+- Fast navigation hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, recorded off-the-shelf detector/template/OCR/segmentation evidence projection, screenshot segmentation model-candidate catalog and runner boundary with Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`), process-backed YOLO sidecar decoding through `DONKEY_YOLO_SEGMENTER` or app-managed runtime registration, local UI-understanding sidecar decoding through `DONKEY_UI_UNDERSTANDER` or app-managed runtime registration, swappable world-state projection, deterministic controller, loop-integrated metadata-only local-navigation dry-run action selection, optional caller-supplied browser-tab metadata, dry-run action projection, generic local-app task intent contracts, data-driven task definitions, local JSON/JSONL task-definition loading, Ollama-compatible local-model command parsing to validated `TaskIntent`, deterministic parsing as fallback/validator, catalog command resolution, target-app availability checks, local task-context intake, Accessibility control discovery, document form-fill review planning, generic dry-run task adaptation, local-navigation request construction, step projection, guarded keyboard and Accessibility command templates, macOS app launch/focus, guarded macOS keyboard input, guarded `AXPress`/`AXSetValue` backend, pointer-prompt typed command submission, Accessibility visible-text observation when trusted, visible-text verification, component latency reporting, and built-in task definitions for Weather lookup, media playback, and document form-fill are supported. This is not yet a complete live fast-navigation agent: model binaries are user-downloaded after app install rather than bundled, UI-understanding is an adapter boundary rather than a default live observation path, and there is no manually verified live command-to-result Weather trace yet.
- Safety boundary: action-engine command contracts, permission/focus/rate/hold/release guardrails, guarded live-action smoke with injected backends, the narrow macOS keyboard backend for local-app tasks, the narrow macOS Accessibility backend for discovered nodes, and replayable command traces are supported.
-- Slow AI boundary: local-model task-intent parsing, local voice-transcription model routing and adapter tracing, structured planner hints, validation/expiry/latest-valid selection, loop-adjacent slow-planner trigger/snapshot sidecar, model registry/router, OpenAI Responses and Ollama-compatible planner adapters, provider-backed local/online planner fallback, source-linked memory, and replay/eval scaffolding are supported as optional sidecar pieces. NVIDIA Parakeet TDT 0.6B v3 is the selected local voice-transcription default, with Whisper large-v3-turbo as a local rollback candidate. This is not yet the complete AI harness because semantic retrieval, redaction, aggregate model observability, installed local microphone transcription runtime, live local visual UI understanding, and provider-decoded memory write proposals remain active.
+- Slow AI boundary: local-model task-intent parsing, Parakeet-only local voice-transcription model routing and process-backed sidecar tracing through `DONKEY_PARAKEET_TRANSCRIBER` or app-managed runtime registration, structured planner hints, validation/expiry/latest-valid selection, loop-adjacent slow-planner trigger/snapshot sidecar, model registry/router, OpenAI Responses and Ollama-compatible planner adapters, provider-backed local/online planner fallback, source-linked memory, bounded semantic memory retrieval contracts, remote-bound redaction hooks, aggregate model-call observability reports, provider-decoded memory proposal handling through the deterministic approver, and replay/eval scaffolding are supported as optional sidecar pieces. NVIDIA Parakeet TDT 0.6B v3 is the selected local voice-transcription default with no Whisper fallback. This is not yet the complete AI harness because the pointer-prompt microphone capture path still needs to feed the Parakeet runtime and live sidecar binaries still need machine-local installation/benchmark evidence.
- Source of truth: detailed supported behavior lives in `docs/guides/minimal-run-coordinator.md`; active unfinished work lives in this plan and its primary/supporting plans.
## Non-Negotiable Rules
@@ -84,16 +84,15 @@ Recent commits completed these pieces:
- current slice: generic local-app task catalog, local-model command parser, deterministic fallback parser, app availability check, and dry-run adapter boundary, with Weather lookup represented as built-in benchmark data.
- `d6e48c9`: archived plans, which was premature for this milestone.
-The code now includes the first generic local-app task catalog, local JSON/JSONL task-definition loader, local task context provider, Accessibility control discovery/action planning, document form-fill review and approval planner, Ollama-compatible local-model command parser, deterministic fallback parser, app availability check, dry-run adapter boundary, local-app live runner, macOS launch/focus, keyboard-input and Accessibility-input backends, pointer-prompt typed command wiring, sample app-task definitions across weather/media/document domains, YOLO26 screenshot segmentation model-candidate metadata and runner boundary, local voice-transcription model routing, and local voice-transcription adapter boundary. It does not yet include live local-model UI understanding over bounded screenshots/crops, bundled live YOLO screenshot segmentation inference, bundled live microphone transcription, semantic memory retrieval, remote-input redaction hooks, aggregate model observability, provider-decoded memory write proposals, or a user-visible approval UI for document fill proposals.
+The code now includes the first generic local-app task catalog, local JSON/JSONL task-definition loader, local task context provider, Accessibility control discovery/action planning, document form-fill review planner, Ollama-compatible local-model command parser, deterministic fallback parser, app availability check, dry-run adapter boundary, local-app live runner, macOS launch/focus, keyboard-input and Accessibility-input backends, pointer-prompt typed command wiring, sample app-task definitions across weather/media/document domains, YOLO26 screenshot segmentation model-candidate metadata and process-backed sidecar backend, local UI-understanding sidecar adapter, Parakeet-only local voice-transcription routing and sidecar runtime, shared JSON sidecar runner, post-install local runtime setup instructions/registration, semantic memory retrieval contracts, redaction hooks, aggregate model-call observability, provider-decoded memory proposal handling, and expanded latency reporting. It does not yet bundle model binaries, wire pointer-prompt microphone buffers into Parakeet, make local UI understanding the default live observation fallback, or include a manually verified live command-to-result Weather trace.
## What Should Be Done Next
-1. Add the user-visible document approval UI in the pointer prompt or a companion review surface, then route approved proposals through the existing guarded Accessibility fill-command path.
-2. Wire pointer-prompt voice capture buffers into `LocalVoiceTranscriptionAdapter`, including bounded audio file/buffer handoff, transcript display, and routing transcript text through the same validated command-intent path as typed input.
-3. Add installed local runtime adapters for Parakeet/Whisper and YOLO26 segmentation behind the injectable runtime protocols, with model availability checks and clear unavailable states.
-4. Add a local model UI-understanding fallback for bounded screenshot/crop context when Accessibility and metadata are insufficient. Prefer this before OCR-specific extraction; OCR can remain a measured optional adapter.
-5. Add benchmark/reporting evidence for command-to-result latency, local navigation/action latency, verification confidence, Accessibility action latency, visual fallback latency, voice transcription latency/accuracy, YOLO mask quality/latency, and comparison against manual/chat-style workflows.
-6. Keep the current dry-run/guarded-live safety boundary: local or online LLM output can only become validated intent, task definitions, app-knowledge updates, observation summaries, transcripts, or planner hints, never direct input.
+1. Wire pointer-prompt microphone buffers into the Parakeet-only `LocalVoiceTranscriptionAdapter`, display transcript text, and submit that text through the same validated command-intent path as typed input.
+2. Integrate `ProcessBackedLocalUIUnderstandingAdapter` into live observation only when Accessibility/metadata are insufficient and a bounded screenshot/crop artifact is available; its output must remain an observation, never a direct action.
+3. Package and publish Donkey-compatible runtime downloads, then run real machine-local sidecar binaries registered by the app-managed installer for YOLO, Parakeet, and UI understanding, and record benchmark evidence for weather/media/document tasks.
+4. Connect semantic memory retrieval, redaction, aggregate model observability, and provider-decoded memory proposal handling into the live slow-planner/model-call paths, not just contract tests.
+5. Keep the current dry-run/guarded-live safety boundary: local or online LLM output can only become validated intent, task definitions, app-knowledge updates, observation summaries, transcripts, memory proposals, or planner hints, never direct input.
## Completion Gates
@@ -102,7 +101,7 @@ Do not move the primary/supporting plans back to `plans/done/` until:
- The fast-navigation agent can run from "show me the weather for SF" to a verified Weather app result with no remote model dependency in the execution trace.
- Dry-run traces and guarded live traces explain intent parsing, app launch/focus, observation, selected rule, input/backend calls, verification, and guardrail decisions.
- The task is measurably faster than a documented manual baseline on the same machine, or the report clearly identifies which stage prevents that.
-- The broader AI harness can retrieve bounded semantic memory, redact remote-bound visual/DOM context, aggregate model-call observability, and route provider-decoded memory proposals through deterministic approval.
+- The broader AI harness uses bounded semantic memory retrieval, remote-bound visual/DOM/context redaction, aggregate model-call observability, and provider-decoded memory proposal approval in live slow-planner paths.
- Voice commands, when enabled, produce local transcript text through the model-routed transcription boundary before command parsing, with no remote dependency.
- The hot loop continues to run when the slow AI harness is disabled or failing.
- p50/p95/p99 reports cover intent parse, app launch/focus, observation, controller decision, action projection, input execution, result verification, and any capture/perception fallback.