Skip to content

Open source CapCut alternative.

TypeScript

No. The setup currently installs bundled bootstrap sidecar packages from

David Lec135dc496fc3
diff --git a/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swift b/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swift
index f6f0d116..2f5cb7d6 100644
--- a/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swift
+++ b/apps/Donkey/Sources/Donkey/MicrophoneWaveformMeter.swift
@@ -1,4 +1,5 @@
import AVFoundation
+import DonkeyAI
import DonkeyContracts
import Foundation
@@ -9,6 +10,10 @@ final class MicrophoneWaveformMeter {
private var levels = PointerPromptState.defaultVoiceWaveformLevels
private var isRunning = false
private var isStarting = false
+ private var isRecordingAudio = false
+ private var capturedSamples: [Float] = []
+ private var capturedSampleRateHz = 0
+ private var capturedStartedAt: Date?
var onLevelsChanged: (([Double]) -> Void)?
@@ -38,9 +43,48 @@ final class MicrophoneWaveformMeter {
engine.stop()
isRunning = false
isStarting = false
+ isRecordingAudio = false
+ capturedSamples.removeAll(keepingCapacity: true)
+ capturedStartedAt = nil
publishSilence()
}
+ func startAudioCapture() {
+ capturedSamples.removeAll(keepingCapacity: true)
+ capturedSampleRateHz = Int(engine.inputNode.outputFormat(forBus: 0).sampleRate)
+ capturedStartedAt = Date()
+ isRecordingAudio = true
+ start()
+ }
+
+ func finishAudioCapture() -> LocalVoiceAudioBuffer? {
+ guard isRecordingAudio else { return nil }
+
+ isRecordingAudio = false
+ let sampleRateHz = capturedSampleRateHz > 0 ? capturedSampleRateHz : 48_000
+ let samples = capturedSamples
+ let startedAt = capturedStartedAt
+ capturedSamples.removeAll(keepingCapacity: true)
+ capturedStartedAt = nil
+ guard !samples.isEmpty else { return nil }
+
+ let durationMS = startedAt.map { Date().timeIntervalSince($0) * 1_000 }
+ ?? (Double(samples.count) / Double(sampleRateHz) * 1_000)
+ return LocalVoiceAudioBuffer(
+ id: "pointer-prompt-audio-\(UUID().uuidString)",
+ format: "pcm_f32le",
+ sampleRateHz: sampleRateHz,
+ channelCount: 1,
+ durationMS: durationMS,
+ data: Self.float32LittleEndianData(from: samples),
+ metadata: [
+ "source": "pointer-prompt",
+ "encoding": "pcm_f32le",
+ "sampleLayout": "mono"
+ ]
+ )
+ }
+
private func startEngine() {
guard !isRunning else {
isStarting = false
@@ -83,6 +127,12 @@ final class MicrophoneWaveformMeter {
publishLevels()
}
+ private func appendAudioSamples(_ samples: [Float]) {
+ guard isRecordingAudio, !samples.isEmpty else { return }
+
+ capturedSamples.append(contentsOf: samples)
+ }
+
private func publishSilence() {
levels = Array(repeating: 0.08, count: barCount)
publishLevels()
@@ -95,13 +145,35 @@ final class MicrophoneWaveformMeter {
nonisolated private static func makeTapBlock(meter: MicrophoneWaveformMeter) -> AVAudioNodeTapBlock {
{ [weak meter] buffer, _ in
let level = Self.normalizedLevel(from: buffer)
+ let samples = Self.monoSamples(from: buffer)
Task { @MainActor in
+ meter?.appendAudioSamples(samples)
meter?.append(level)
}
}
}
+ nonisolated private static func monoSamples(from buffer: AVAudioPCMBuffer) -> [Float] {
+ guard let channelData = buffer.floatChannelData,
+ buffer.frameLength > 0 else {
+ return []
+ }
+
+ let frameCount = Int(buffer.frameLength)
+ let firstChannel = channelData[0]
+ return Array(UnsafeBufferPointer(start: firstChannel, count: frameCount))
+ }
+
+ nonisolated private static func float32LittleEndianData(from samples: [Float]) -> Data {
+ var data = Data(capacity: samples.count * MemoryLayout<UInt32>.size)
+ for sample in samples {
+ var bits = sample.bitPattern.littleEndian
+ data.append(Data(bytes: &bits, count: MemoryLayout<UInt32>.size))
+ }
+ return data
+ }
+
nonisolated private static func normalizedLevel(from buffer: AVAudioPCMBuffer) -> Double {
guard let channelData = buffer.floatChannelData,
buffer.frameLength > 0 else {
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
index 63cc0c49..272a7189 100644
--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
@@ -18,19 +18,38 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
var catalog: LocalAppTaskCatalog
var localModelResolver: LocalModelTaskIntentResolver
var liveRunner: LocalAppTaskLiveRunner
+ var redactor: AIHarnessRedactor
+ var memoryRetriever: SemanticRunMemoryRetriever
init(
catalog: LocalAppTaskCatalog = .defaultLocal(),
localModelResolver: LocalModelTaskIntentResolver? = nil,
- liveRunner: LocalAppTaskLiveRunner? = nil
+ liveRunner: LocalAppTaskLiveRunner? = nil,
+ redactor: AIHarnessRedactor = AIHarnessRedactor(),
+ memoryRetriever: SemanticRunMemoryRetriever = SemanticRunMemoryRetriever()
) {
self.catalog = catalog
self.localModelResolver = localModelResolver ?? LocalModelTaskIntentResolver(catalog: catalog)
self.liveRunner = liveRunner ?? LocalAppTaskLiveRunner(catalog: catalog)
+ self.redactor = redactor
+ self.memoryRetriever = memoryRetriever
}
func handleSubmittedCommand(_ command: String) async -> PointerPromptCommandHandlingResult {
let traceID = "pointer-prompt-\(UUID().uuidString)"
+ let redaction = redactor.redact(command, surface: .modelContext)
+ let semanticMemoryResults = await memoryRetriever.retrieve(
+ query: RunMemorySemanticQuery(
+ text: command,
+ budget: RunMemoryRetrievalBudget(maxRecords: 3, maxPromptCharacters: 800)
+ ),
+ records: []
+ )
+ let memoryProposalDecisions = (try? ProviderDecodedMemoryProposalHandler.decisions(
+ from: Data("[]".utf8),
+ decidedAt: Self.now()
+ )) ?? []
+ let parseStartedAt = Self.uptimeMilliseconds()
let localModelResult = await localModelResolver.resolve(
command: command,
sourceTraceID: traceID
@@ -44,6 +63,8 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
? deterministicResolution
: localModelResolution
let parserSource = shouldUseDeterministicFallback ? "deterministicFallback" : "localModel"
+ let parseLatencyMS = Self.uptimeMilliseconds() - parseStartedAt
+ let modelObservability = AIModelObservabilityReportBuilder.build(from: [localModelResult.trace])
let result = await liveRunner.run(
command: command,
@@ -51,9 +72,16 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
resolution: resolution,
metadata: [
"intentParser": parserSource,
+ "latency.commandParseMS": Self.formatLatency(parseLatencyMS),
"modelCallID": localModelResult.trace.id,
"modelCallStatus": localModelResult.trace.status.rawValue,
- "modelValidationStatus": localModelResult.trace.validationStatus
+ "modelValidationStatus": localModelResult.trace.validationStatus,
+ "modelObservability.callCount": String(modelObservability.callCount),
+ "modelObservability.acceptedCount": String(modelObservability.acceptedCount),
+ "modelObservability.recoverySuccessCount": String(modelObservability.recoverySuccessCount),
+ "redaction.modelContext.count": String(redaction.redactionCount),
+ "semanticMemory.resultCount": String(semanticMemoryResults.count),
+ "memoryProposal.decisionCount": String(memoryProposalDecisions.count)
]
)
@@ -88,4 +116,19 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
return "Stopped safely"
}
}
+
+ private static func uptimeMilliseconds() -> Double {
+ ProcessInfo.processInfo.systemUptime * 1_000
+ }
+
+ private static func formatLatency(_ milliseconds: Double) -> String {
+ String(format: "%.3f", max(0, milliseconds))
+ }
+
+ private static func now() -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(),
+ monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)
+ )
+ }
}
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift
index 67c0dcba..52988f08 100644
--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift
+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift
@@ -18,6 +18,7 @@ final class PointerPromptOverlayController {
private var completedActivationTapCount = 0
private var lastActivationTapCompletedAt: Date?
private var activationHoldStartedAt: Date?
+ private var isVoiceInputActive = false
init(
model: PointerPromptOverlayModel,
@@ -162,6 +163,12 @@ final class PointerPromptOverlayController {
let isActivationModifierDown = flags.contains(activationModifierFlag)
let isCleanActivationModifierOnly = flags == activationModifierFlag
+ if isVoiceInputActive, !isActivationModifierDown {
+ finishVoiceInput()
+ resetActivationTapSequence()
+ return
+ }
+
if isCleanActivationModifierOnly {
if activationTapStartedAt == nil {
let now = Date()
@@ -272,9 +279,19 @@ final class PointerPromptOverlayController {
private func activateVoiceInputAtCurrentMouseLocation() {
activateAtCurrentMouseLocation()
+ isVoiceInputActive = true
+ microphoneWaveformMeter.startAudioCapture()
model.handle(.voiceInputRequested)
}
+ private func finishVoiceInput() {
+ guard isVoiceInputActive else { return }
+
+ isVoiceInputActive = false
+ let audio = microphoneWaveformMeter.finishAudioCapture()
+ model.submitVoiceAudio(audio)
+ }
+
private func positionAtCurrentMouseLocation() {
tick(mouseLocation: NSEvent.mouseLocation)
}
@@ -509,6 +526,7 @@ final class PointerPromptOverlayController {
private func updateMouseEventPassthrough(for panel: NSPanel) {
guard model.promptState.isActive else {
panel.ignoresMouseEvents = true
+ isVoiceInputActive = false
return
}
@@ -533,6 +551,7 @@ final class PointerPromptOverlayController {
}
model.handle(.dismissed)
+ isVoiceInputActive = false
microphoneWaveformMeter.stop()
return true
}
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift
index 4cad0076..933d8cb0 100644
--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift
+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift
@@ -12,13 +12,18 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
@Published var isInputExpanded = false
private let commandHandler: any PointerPromptCommandHandling
+ private let voiceTranscriber: LocalVoiceTranscriptionAdapter
init(
aiProvider: any AIHarnessSnapshotProviding = AIHarnessBoundary(),
commandHandler: any PointerPromptCommandHandling = LocalAppPointerPromptCommandHandler(),
+ voiceTranscriber: LocalVoiceTranscriptionAdapter = LocalVoiceTranscriptionAdapter(
+ runtime: ProcessBackedParakeetTranscriptionRuntime()
+ ),
theme: PointerPromptTheme = PointerPromptOverlayModel.bundledTheme()
) {
self.commandHandler = commandHandler
+ self.voiceTranscriber = voiceTranscriber
let aiSnapshot = aiProvider.snapshot()
promptState = PointerPromptState(
promptText: aiSnapshot.suggestedPromptText,
@@ -48,25 +53,14 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
promptState.leadingSignalLevel = .ready
case .voiceInputRequested:
promptState.leadingSignalLevel = .ready
+ promptState.promptText = "Listening..."
case .primaryActionRequested:
promptState.leadingSignalLevel = .thinking
case .messageSubmitted(let text):
let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedText.isEmpty else { return }
- messageText = ""
- inputTextHeight = PointerPromptLayout.composerInputTextMinimumHeight
- isInputExpanded = false
- promptState.leadingSignalLevel = .thinking
- promptState.promptText = "Working..."
- Task { [weak self, commandHandler] in
- let result = await commandHandler.handleSubmittedCommand(trimmedText)
- await MainActor.run {
- guard let self else { return }
- self.promptState.leadingSignalLevel = result.status == .completed ? .ready : .idle
- self.promptState.promptText = result.summary
- }
- }
+ submitCommand(trimmedText)
case .inputTextHeightChanged(let height):
let clampedHeight = PointerPromptLayout.clampedComposerInputTextHeight(height)
guard abs(inputTextHeight - clampedHeight) > 0.5 else { return }
@@ -81,6 +75,54 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink
}
}
+ func submitVoiceAudio(_ audio: LocalVoiceAudioBuffer?) {
+ guard let audio else {
+ promptState.leadingSignalLevel = .idle
+ promptState.promptText = "No voice captured"
+ return
+ }
+
+ let sourceTraceID = "pointer-prompt-voice-\(UUID().uuidString)"
+ promptState.leadingSignalLevel = .thinking
+ promptState.promptText = "Transcribing..."
+ Task { [weak self, voiceTranscriber] in
+ let result = await voiceTranscriber.transcribe(
+ LocalVoiceTranscriptionRequest(
+ audio: audio,
+ sourceTraceID: sourceTraceID
+ )
+ )
+ await MainActor.run {
+ guard let self else { return }
+ guard let transcript = result.transcript,
+ !transcript.text.isEmpty else {
+ self.promptState.leadingSignalLevel = .idle
+ self.promptState.promptText = "Voice unavailable"
+ return
+ }
+
+ self.messageText = transcript.text
+ self.submitCommand(transcript.text)
+ }
+ }
+ }
+
+ private func submitCommand(_ text: String) {
+ messageText = ""
+ inputTextHeight = PointerPromptLayout.composerInputTextMinimumHeight
+ isInputExpanded = false
+ promptState.leadingSignalLevel = .thinking
+ promptState.promptText = "Working..."
+ Task { [weak self, commandHandler] in
+ let result = await commandHandler.handleSubmittedCommand(text)
+ await MainActor.run {
+ guard let self else { return }
+ self.promptState.leadingSignalLevel = result.status == .completed ? .ready : .idle
+ self.promptState.promptText = result.summary
+ }
+ }
+ }
+
private static func bundledTheme() -> PointerPromptTheme {
guard let themeURL = Bundle.module.url(forResource: "theme", withExtension: "json"),
let themeData = try? Data(contentsOf: themeURL),
diff --git a/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
index 67ccc436..206ef679 100644
--- a/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
@@ -161,6 +161,9 @@ public struct ProcessBackedParakeetTranscriptionRuntime: LocalVoiceTranscription
confidence: response.confidence,
segments: response.segments,
metadata: result.metadata.merging(response.metadata) { current, _ in current }
+ .merging([
+ "latency.parakeetTranscriptionMS": result.latencyMS.map { String(format: "%.3f", $0) } ?? ""
+ ]) { current, _ in current }
)
} catch {
throw LocalVoiceTranscriptionRuntimeError.invalidOutput(String(describing: error))
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
index 66dbfcc0..341e774e 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
@@ -104,12 +104,16 @@ public struct LocalAppTaskLiveRunner: Sendable {
resolution: LocalAppTaskCatalogResolution,
metadata: [String: String] = [:]
) async -> LocalAppTaskLiveRunResult {
+ let runStartedAt = Self.uptimeMilliseconds()
+ var runMetadata = metadata
guard resolution.status == .resolved else {
return unresolvedResult(
command: command,
traceID: traceID,
resolution: resolution,
- metadata: metadata
+ metadata: metadata.merging([
+ "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)
+ ]) { current, _ in current }
)
}
@@ -122,14 +126,21 @@ public struct LocalAppTaskLiveRunner: Sendable {
traceID: traceID,
status: .failedSafe,
resolution: resolution,
- metadata: metadata.merging(["reason": "incompleteResolution"]) { current, _ in current }
+ metadata: runMetadata.merging([
+ "reason": "incompleteResolution",
+ "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)
+ ]) { current, _ in current }
)
}
intent.metadata["traceID"] = traceID
let adapter = catalog.adapter(for: definition)
if definition.metadata["guardedLiveDefault"] == "reviewOnly" {
+ let contextStartedAt = Self.uptimeMilliseconds()
let context = await contextProvider.snapshot()
+ runMetadata["latency.observationMS"] = Self.formatLatency(
+ Self.uptimeMilliseconds() - contextStartedAt
+ )
let documentPlan = documentFormFillPlanner.plan(
intent: intent,
definition: definition,
@@ -160,18 +171,21 @@ public struct LocalAppTaskLiveRunner: Sendable {
finalPlan: initialPlan,
observation: observation,
documentFormFillPlan: documentPlan,
- metadata: metadata.merging([
+ metadata: runMetadata.merging([
"reason": "reviewOnlyTask",
"documentFormFillPlan.status": documentPlan.status.rawValue,
- "documentFormFillPlan.proposalCount": String(documentPlan.proposals.count)
+ "documentFormFillPlan.proposalCount": String(documentPlan.proposals.count),
+ "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)
]) { current, _ in current }
)
}
+ let launchStartedAt = Self.uptimeMilliseconds()
let launchObservation = await appController.launchOrFocus(
definition: definition,
availability: availability
)
+ runMetadata["latency.launchFocusMS"] = Self.formatLatency(Self.uptimeMilliseconds() - launchStartedAt)
let initialPlan = adapter.dryRunPlan(for: intent, observation: launchObservation)
guard initialPlan.canAttemptGuardedLive else {
return LocalAppTaskLiveRunResult(
@@ -181,11 +195,15 @@ public struct LocalAppTaskLiveRunner: Sendable {
resolution: resolution,
initialPlan: initialPlan,
observation: launchObservation,
- metadata: metadata.merging(["reason": "dryRunPlanBlocked"]) { current, _ in current }
+ metadata: runMetadata.merging([
+ "reason": "dryRunPlanBlocked",
+ "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)
+ ]) { current, _ in current }
)
}
var actionTraces: [ActionEngineCommandTrace] = []
+ var accessibilityActionMS = 0.0
let accessibilityCommands = await accessibilityCommandTemplates(
intent: intent,
definition: definition
@@ -194,16 +212,19 @@ public struct LocalAppTaskLiveRunner: Sendable {
let accessibilityEngine = Self.accessibilityActionEngine(for: definition)
for (index, actionCommand) in accessibilityCommands.enumerated() {
let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 60))
+ let actionStartedAt = Self.uptimeMilliseconds()
let trace = await accessibilityEngine.handle(
spacedCommand,
permissionPolicy: permissionPolicy
)
+ accessibilityActionMS += Self.uptimeMilliseconds() - actionStartedAt
actionTraces.append(trace)
guard trace.executed || trace.decision == .projectedDryRun else {
break
}
}
}
+ runMetadata["latency.accessibilityActionMS"] = Self.formatLatency(accessibilityActionMS)
let engine = actionEngineFactory(definition)
let accessibilityHandledStepIDs: Set<String> = Set(actionTraces.compactMap { trace -> String? in
@@ -218,17 +239,28 @@ public struct LocalAppTaskLiveRunner: Sendable {
return !accessibilityHandledStepIDs.contains(workflowStepID)
}
+ var keyboardActionMS = 0.0
for (index, actionCommand) in commands.enumerated() {
let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 40))
+ let actionStartedAt = Self.uptimeMilliseconds()
let trace = await engine.handle(
spacedCommand,
permissionPolicy: permissionPolicy
)
+ keyboardActionMS += Self.uptimeMilliseconds() - actionStartedAt
actionTraces.append(trace)
guard trace.executed || trace.decision == ActionEngineCommandDecision.projectedDryRun else {
+ let observationStartedAt = Self.uptimeMilliseconds()
let finalObservation = await appController.observe(definition: definition)
+ runMetadata["latency.observationMS"] = Self.formatLatency(
+ Self.uptimeMilliseconds() - observationStartedAt
+ )
+ let verificationStartedAt = Self.uptimeMilliseconds()
let finalPlan = adapter.dryRunPlan(for: intent, observation: finalObservation)
+ runMetadata["latency.verificationMS"] = Self.formatLatency(
+ Self.uptimeMilliseconds() - verificationStartedAt
+ )
return LocalAppTaskLiveRunResult(
command: command,
traceID: traceID,
@@ -238,14 +270,24 @@ public struct LocalAppTaskLiveRunner: Sendable {
finalPlan: finalPlan,
observation: finalObservation,
actionTraces: actionTraces,
- metadata: metadata.merging(["reason": "actionDenied"]) { current, _ in current }
+ metadata: runMetadata.merging([
+ "reason": "actionDenied",
+ "latency.keyboardActionMS": Self.formatLatency(keyboardActionMS),
+ "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)
+ ]) { current, _ in current }
)
}
}
+ runMetadata["latency.keyboardActionMS"] = Self.formatLatency(keyboardActionMS)
try? await Task.sleep(nanoseconds: 700_000_000)
+ let observationStartedAt = Self.uptimeMilliseconds()
let finalObservation = await appController.observe(definition: definition)
+ runMetadata["latency.observationMS"] = Self.formatLatency(Self.uptimeMilliseconds() - observationStartedAt)
+ let verificationStartedAt = Self.uptimeMilliseconds()
let finalPlan = adapter.dryRunPlan(for: intent, observation: finalObservation)
+ runMetadata["latency.verificationMS"] = Self.formatLatency(Self.uptimeMilliseconds() - verificationStartedAt)
+ runMetadata["latency.totalMS"] = Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)
return LocalAppTaskLiveRunResult(
command: command,
traceID: traceID,
@@ -255,7 +297,7 @@ public struct LocalAppTaskLiveRunner: Sendable {
finalPlan: finalPlan,
observation: finalObservation,
actionTraces: actionTraces,
- metadata: metadata.merging([
+ metadata: runMetadata.merging([
"executedCommandCount": String(actionTraces.filter(\.executed).count),
"projectedCommandCount": String(actionTraces.filter { $0.decision == .projectedDryRun }.count)
]) { current, _ in current }
@@ -364,6 +406,14 @@ public struct LocalAppTaskLiveRunner: Sendable {
monotonicUptimeNanoseconds: UInt64((now * 1_000_000_000) + (milliseconds * 1_000_000))
)
}
+
+ private static func uptimeMilliseconds() -> Double {
+ ProcessInfo.processInfo.systemUptime * 1_000
+ }
+
+ private static func formatLatency(_ milliseconds: Double) -> String {
+ String(format: "%.3f", max(0, milliseconds))
+ }
}
public struct MacLocalAppFocusGuard: ActionEngineFocusGuard {
@@ -389,7 +439,13 @@ public struct MacLocalAppFocusGuard: ActionEngineFocusGuard {
}
public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
- public init() {}
+ public var uiUnderstandingRunner: any LocalUIUnderstandingRunning
+
+ public init(
+ uiUnderstandingRunner: any LocalUIUnderstandingRunning = ProcessBackedLocalUIUnderstandingAdapter()
+ ) {
+ self.uiUnderstandingRunner = uiUnderstandingRunner
+ }
@MainActor
public func launchOrFocus(
@@ -415,7 +471,7 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
let verificationKey = definition.metadata["verificationTextKey"]
?? definition.verificationEntityName
?? "visibleText"
- let controls: [String: Bool] = Dictionary(
+ var controls: [String: Bool] = Dictionary(
uniqueKeysWithValues: definition.workflowSteps.compactMap { step in
guard step.role == .focusControl,
let controlID = step.metadata["controlID"]
@@ -433,7 +489,7 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
textValues[verificationKey] = visibleText
}
- return LocalAppTaskObservation(
+ let accessibilityObservation = LocalAppTaskObservation(
appIsRunning: runningApplication != nil,
appIsFocused: isFocused,
availableControls: controls,
@@ -446,6 +502,128 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
"accessibilityControlCount": accessibilityIndex?.metadata["controlCount"] ?? "0"
]
)
+
+ guard shouldUseScreenshotUnderstanding(
+ definition: definition,
+ observation: accessibilityObservation
+ ) else {
+ return accessibilityObservation
+ }
+
+ guard let screenshotObservation = await screenshotUnderstandingObservation(
+ definition: definition,
+ runningApplication: runningApplication,
+ isFocused: isFocused,
+ verificationKey: verificationKey
+ ) else {
+ var metadata = accessibilityObservation.metadata
+ metadata["screenshotUnderstanding.status"] = "unavailable"
+ return LocalAppTaskObservation(
+ appIsRunning: accessibilityObservation.appIsRunning,
+ appIsFocused: accessibilityObservation.appIsFocused,
+ availableControls: accessibilityObservation.availableControls,
+ visibleText: accessibilityObservation.visibleText,
+ confidence: accessibilityObservation.confidence,
+ metadata: metadata
+ )
+ }
+
+ controls.merge(screenshotObservation.availableControls) { current, new in current || new }
+ return LocalAppTaskObservation(
+ appIsRunning: accessibilityObservation.appIsRunning || screenshotObservation.appIsRunning,
+ appIsFocused: accessibilityObservation.appIsFocused || screenshotObservation.appIsFocused,
+ availableControls: controls,
+ visibleText: accessibilityObservation.visibleText.merging(
+ screenshotObservation.visibleText
+ ) { current, _ in current },
+ confidence: max(accessibilityObservation.confidence, screenshotObservation.confidence),
+ metadata: accessibilityObservation.metadata.merging(
+ screenshotObservation.metadata
+ ) { current, _ in current }
+ )
+ }
+
+ private func shouldUseScreenshotUnderstanding(
+ definition: LocalAppTaskDefinition,
+ observation: LocalAppTaskObservation
+ ) -> Bool {
+ guard definition.observationStrategies.contains(.screenshotForLocalModel) else {
+ return false
+ }
+
+ let expectedControls = definition.workflowSteps.compactMap { step -> String? in
+ guard step.role == .focusControl else { return nil }
+ return step.metadata["controlID"]
+ }
+ let missingExpectedControl = expectedControls.contains { observation.availableControls[$0] != true }
+ return observation.visibleText.isEmpty || missingExpectedControl || observation.confidence < 0.7
+ }
+
+ @MainActor
+ private func screenshotUnderstandingObservation(
+ definition: LocalAppTaskDefinition,
+ runningApplication: NSRunningApplication?,
+ isFocused: Bool,
+ verificationKey: String
+ ) async -> LocalAppTaskObservation? {
+ guard runningApplication != nil,
+ let target = try? MacWindowResolver().selectTarget(),
+ target.bundleIdentifier == definition.targetApp.bundleIdentifier,
+ target.safetyAssessment.status == .allowed
+ else {
+ return nil
+ }
+
+ let screenshot: CapturedWindowScreenshot
+ do {
+ screenshot = try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: target)
+ } catch {
+ return nil
+ }
+
+ let imageURL = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-ui-understanding-\(UUID().uuidString).png")
+ do {
+ try screenshot.pngData.write(to: imageURL, options: .atomic)
+ } catch {
+ return nil
+ }
+ defer {
+ try? FileManager.default.removeItem(at: imageURL)
+ }
+
+ let request = LocalUIUnderstandingRequest(
+ traceID: "local-ui-understanding-\(UUID().uuidString)",
+ targetID: LocalAppTaskAdapter(definition: definition).targetID,
+ appIsRunning: true,
+ appIsFocused: isFocused,
+ imageFileURL: imageURL,
+ cropBounds: HotLoopRect(
+ x: 0,
+ y: 0,
+ width: Double(screenshot.imageWidth),
+ height: Double(screenshot.imageHeight),
+ space: .window
+ ),
+ pixelSize: HotLoopSize(
+ width: Double(screenshot.imageWidth),
+ height: Double(screenshot.imageHeight),
+ space: .window
+ ),
+ metadata: [
+ "observer": "mac-local-app-controller",
+ "observation.source": "screenshot",
+ "verificationTextKey": verificationKey,
+ "target.windowID": String(target.windowID),
+ "capture.method": screenshot.captureMethod.rawValue
+ ]
+ )
+
+ do {
+ return try await uiUnderstandingRunner.understand(request).observation(for: request)
+ } catch {
+ return nil
+ }
}
@MainActor
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift
index 5a7bb290..fce3c5f5 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift
@@ -285,17 +285,20 @@ public struct LocalModelRuntimeSetupManager: Sendable {
public var specs: [LocalModelRuntimeSpec]
public var isExecutableFile: @Sendable (String) -> Bool
public var now: @Sendable () -> Date
+ public var bundledPackageDirectory: @Sendable (LocalModelRuntimeID) -> URL?
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
+ now: @escaping @Sendable () -> Date = Date.init,
+ bundledPackageDirectory: @escaping @Sendable (LocalModelRuntimeID) -> URL? = Self.defaultBundledPackageDirectory
) throws {
self.baseDirectory = try baseDirectory ?? Self.defaultBaseDirectory()
self.specs = specs
self.isExecutableFile = isExecutableFile
self.now = now
+ self.bundledPackageDirectory = bundledPackageDirectory
}
public static let defaultSpecs: [LocalModelRuntimeSpec] = [
@@ -355,6 +358,21 @@ public struct LocalModelRuntimeSetupManager: Sendable {
.appendingPathComponent("LocalModelRuntimes", isDirectory: true)
}
+ public static func defaultBundledPackageDirectory(runtimeID: LocalModelRuntimeID) -> URL? {
+ guard let resourcesURL = Bundle.main.resourceURL else { return nil }
+ let packageDirectory = resourcesURL
+ .appendingPathComponent("LocalRuntimePackages", isDirectory: true)
+ .appendingPathComponent(runtimeID.rawValue, isDirectory: true)
+ guard FileManager.default.fileExists(
+ atPath: packageDirectory
+ .appendingPathComponent("manifest.json", isDirectory: false)
+ .path
+ ) else {
+ return nil
+ }
+ return packageDirectory
+ }
+
public func instructions() -> [LocalModelRuntimeInstallInstruction] {
specs.map { spec in
LocalModelRuntimeInstallInstruction(
@@ -550,6 +568,26 @@ public struct LocalModelRuntimeSetupManager: Sendable {
downloader: any LocalModelRuntimePackageDownloading = URLSessionLocalModelRuntimePackageDownloader(),
requiresSignature: Bool = true
) async throws -> LocalModelRuntimeDownloadResult {
+ if let packageDirectory = bundledPackageDirectory(runtimeID) {
+ let manifestURL = packageDirectory.appendingPathComponent("manifest.json", isDirectory: false)
+ let manifestData = try Data(contentsOf: manifestURL)
+ let manifest = try Self.decoder().decode(LocalModelRuntimePackageManifest.self, from: manifestData)
+ let installation = try installDownloadedPackage(
+ manifest: manifest,
+ packageDirectory: packageDirectory,
+ requiresSignature: requiresSignature
+ )
+ return LocalModelRuntimeDownloadResult(
+ runtimeID: runtimeID,
+ state: .installed,
+ installation: installation,
+ metadata: [
+ "download.source": "bundledRuntimePackage",
+ "download.packageDirectory": packageDirectory.path
+ ]
+ )
+ }
+
let spec = try spec(for: runtimeID)
guard let manifestURL = spec.manifestURL else {
throw LocalModelRuntimeSetupError.manifestMissingDownloadURL(relativePath: "manifest")
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift
index 8b81d381..159d76ba 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalUIUnderstandingAdapter.swift
@@ -165,6 +165,9 @@ public struct ProcessBackedLocalUIUnderstandingAdapter: LocalUIUnderstandingRunn
formFields: output.formFields,
confidence: output.confidence,
metadata: result.metadata.merging(output.metadata) { current, _ in current }
+ .merging([
+ "latency.uiUnderstandingMS": result.latencyMS.map { String(format: "%.3f", $0) } ?? ""
+ ]) { current, _ in current }
)
} catch {
throw LocalUIUnderstandingError.invalidOutput(String(describing: error))
diff --git a/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift
index c92757f3..a1936417 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift
@@ -282,7 +282,7 @@ public final class WindowScreenshotCaptureService {
}
}
-private final class ScreenCaptureKitWindowScreenshotCapturer: WindowScreenshotCapturing {
+final class ScreenCaptureKitWindowScreenshotCapturer: WindowScreenshotCapturing {
var captureMethod: WindowScreenshotCaptureMethod {
.screenCaptureKitDesktopIndependentWindow
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift
index f96dc681..e3865d7d 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/YOLOScreenshotSegmentationRunner.swift
@@ -180,6 +180,9 @@ public struct ProcessBackedScreenshotSegmentationBackend: ScreenshotSegmentation
preprocessMS: response.preprocessMS,
modelInferenceMS: response.modelInferenceMS,
metadata: result.metadata.merging(response.metadata) { current, _ in current }
+ .merging([
+ "latency.yoloSegmentationMS": result.latencyMS.map { String(format: "%.3f", $0) } ?? ""
+ ]) { current, _ in current }
)
} catch {
throw ScreenshotSegmentationRunnerError.invalidOutput(String(describing: error))
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift
index 8d2df68c..acd1403b 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift
@@ -17,7 +17,7 @@ struct LocalModelRuntimeSetupTests {
#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)
+ #expect(instructions.first?.spec.installSteps.first?.contains("Set Up") == true)
}
@Test
@@ -167,6 +167,54 @@ struct LocalModelRuntimeSetupTests {
#expect(FileManager.default.fileExists(atPath: status.installation?.executablePath ?? "") == true)
}
+ @Test
+ func bundledRuntimePackageInstallsWithoutNetworkDownload() async throws {
+ let root = temporaryDirectory()
+ let package = temporaryDirectory()
+ defer {
+ try? FileManager.default.removeItem(at: root)
+ try? FileManager.default.removeItem(at: package)
+ }
+ let executableData = Data("#!/bin/sh\ncat >/dev/null\nprintf '{\"status\":\"ok\",\"runtimeID\":\"yolo-segmenter\",\"runtimeVersion\":\"0.1.0\",\"modelID\":\"bootstrap-yolo26\",\"protocolVersion\":\"v1\",\"metadata\":{}}'\n".utf8)
+ let executableURL = try makeExecutable(
+ root: package,
+ relativePath: "bin/donkey-yolo-segmenter",
+ data: executableData
+ )
+ let manifest = LocalModelRuntimePackageManifest(
+ runtimeID: .yoloSegmenter,
+ runtimeVersion: "0.1.0",
+ modelID: "bootstrap-yolo26",
+ executableRelativePath: "bin/donkey-yolo-segmenter",
+ files: [
+ LocalModelRuntimePackageFile(
+ relativePath: "bin/donkey-yolo-segmenter",
+ sha256: LocalModelRuntimeSetupManager.sha256Hex(executableData),
+ isExecutable: true
+ )
+ ],
+ signature: "bundled-bootstrap-signature",
+ signingKeyID: "donkey-bootstrap"
+ )
+ let manifestData = try JSONEncoder().encode(manifest)
+ try manifestData.write(to: package.appendingPathComponent("manifest.json", isDirectory: false))
+ let manager = try LocalModelRuntimeSetupManager(
+ baseDirectory: root,
+ bundledPackageDirectory: { runtimeID in
+ runtimeID == .yoloSegmenter ? package : nil
+ }
+ )
+
+ let result = try await manager.downloadAndInstall(runtimeID: .yoloSegmenter)
+ let status = try manager.status(for: .yoloSegmenter)
+
+ #expect(result.state == .installed)
+ #expect(result.metadata["download.source"] == "bundledRuntimePackage")
+ #expect(status.state == .installed)
+ #expect(status.installation?.executablePath != executableURL.path)
+ #expect(status.installation?.downloadedDirectoryPath.contains("/Packages/yolo-segmenter/0.1.0") == true)
+ }
+
@Test
func manifestDownloadRejectsMissingSignatureAndBadChecksums() async throws {
let root = temporaryDirectory()
@@ -259,10 +307,19 @@ struct LocalModelRuntimeSetupTests {
try makeFile(root: root, relativePath: relativePath, permissions: 0o755)
}
+ private func makeExecutable(
+ root: URL,
+ relativePath: String,
+ data: Data
+ ) throws -> URL {
+ try makeFile(root: root, relativePath: relativePath, permissions: 0o755, data: data)
+ }
+
private func makeFile(
root: URL,
relativePath: String,
- permissions: Int
+ permissions: Int,
+ data: Data = Data("#!/bin/sh\ncat\n".utf8)
) throws -> URL {
let url = relativePath
.split(separator: "/")
@@ -273,7 +330,7 @@ struct LocalModelRuntimeSetupTests {
at: url.deletingLastPathComponent(),
withIntermediateDirectories: true
)
- try Data("#!/bin/sh\ncat\n".utf8).write(to: url)
+ try data.write(to: url)
try FileManager.default.setAttributes(
[.posixPermissions: permissions],
ofItemAtPath: url.path
diff --git a/dist/Donkey.app/Contents/Info.plist b/dist/Donkey.app/Contents/Info.plist
new file mode 100644
index 00000000..3e41eb0a
--- /dev/null
+++ b/dist/Donkey.app/Contents/Info.plist
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleExecutable</key>
+ <string>Donkey</string>
+ <key>CFBundleIdentifier</key>
+ <string>ai.donkey.Donkey</string>
+ <key>CFBundleName</key>
+ <string>Donkey</string>
+ <key>CFBundleDisplayName</key>
+ <string>Donkey</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>0.1.0</string>
+ <key>CFBundleVersion</key>
+ <string>1</string>
+ <key>LSMinimumSystemVersion</key>
+ <string>14.0</string>
+ <key>NSMicrophoneUsageDescription</key>
+ <string>Donkey uses the microphone for local voice commands.</string>
+ <key>NSScreenCaptureUsageDescription</key>
+ <string>Donkey captures bounded screenshots so local runtimes can understand app UI.</string>
+ <key>NSAppleEventsUsageDescription</key>
+ <string>Donkey uses local app automation only for user-requested actions.</string>
+</dict>
+</plist>
diff --git a/dist/Donkey.app/Contents/MacOS/Donkey b/dist/Donkey.app/Contents/MacOS/Donkey
new file mode 100755
index 00000000..877f7a9e
Binary files /dev/null and b/dist/Donkey.app/Contents/MacOS/Donkey differ
diff --git a/dist/Donkey.app/Contents/Resources/Donkey_Donkey.bundle/theme.json b/dist/Donkey.app/Contents/Resources/Donkey_Donkey.bundle/theme.json
new file mode 100644
index 00000000..6a1aae6d
--- /dev/null
+++ b/dist/Donkey.app/Contents/Resources/Donkey_Donkey.bundle/theme.json
@@ -0,0 +1,6 @@
+{
+ "accent": "#0D6CD8",
+ "fill": "#E0F0FF",
+ "pointerFill": "#FFFFFF",
+ "activeShadow": "rgba(0, 36, 82, 0.26)"
+}
diff --git a/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/parakeet-transcriber/bin/donkey-parakeet-transcriber b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/parakeet-transcriber/bin/donkey-parakeet-transcriber
new file mode 100755
index 00000000..5634961f
--- /dev/null
+++ b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/parakeet-transcriber/bin/donkey-parakeet-transcriber
@@ -0,0 +1,18 @@
+#!/usr/bin/env sh
+REQUEST="$(cat)"
+if printf '%s' "$REQUEST" | grep -q '"operation"[[:space:]]*:[[:space:]]*"healthCheck"'; then
+ printf '{"status":"ok","runtimeID":"parakeet-transcriber","runtimeVersion":"0.1.0-bootstrap","modelID":"nvidia/parakeet-tdt-0.6b-v3","protocolVersion":"v1","metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","sidecar.role":"voiceTranscription"}}'
+ exit 0
+fi
+
+case "parakeet-transcriber" in
+ parakeet-transcriber)
+ printf '{"text":"","language":null,"confidence":0,"segments":[],"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ yolo-segmenter)
+ printf '{"masks":[],"preprocessMS":0,"modelInferenceMS":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ ui-understander)
+ printf '{"visibleText":{},"controls":[],"formFields":[],"confidence":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+esac
diff --git a/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/parakeet-transcriber/manifest.json b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/parakeet-transcriber/manifest.json
new file mode 100644
index 00000000..cd9a8df7
--- /dev/null
+++ b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/parakeet-transcriber/manifest.json
@@ -0,0 +1,24 @@
+{
+ "runtimeID" : "parakeet-transcriber",
+ "runtimeVersion" : "0.1.0-bootstrap",
+ "modelID" : "nvidia/parakeet-tdt-0.6b-v3",
+ "platform" : "macos",
+ "architecture" : "arm64",
+ "sidecarProtocolVersion" : "v1",
+ "minimumDonkeyVersion" : "0.1.0",
+ "executableRelativePath" : "bin/donkey-parakeet-transcriber",
+ "files" : [
+ {
+ "relativePath" : "bin/donkey-parakeet-transcriber",
+ "sha256" : "a36365dfcc69ba375d343df5aa9f2e37dc0cc03501b9868b82ad4a60bc95c38f",
+ "isExecutable" : true
+ }
+ ],
+ "signature" : "bundled-bootstrap-package",
+ "signingKeyID" : "donkey-bootstrap",
+ "metadata" : {
+ "runtime.package" : "bundled-bootstrap",
+ "modelWeightsBundled" : "false",
+ "sidecar.role" : "voiceTranscription"
+ }
+}
diff --git a/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/ui-understander/bin/donkey-ui-understander b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/ui-understander/bin/donkey-ui-understander
new file mode 100755
index 00000000..fd4ac4df
--- /dev/null
+++ b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/ui-understander/bin/donkey-ui-understander
@@ -0,0 +1,18 @@
+#!/usr/bin/env sh
+REQUEST="$(cat)"
+if printf '%s' "$REQUEST" | grep -q '"operation"[[:space:]]*:[[:space:]]*"healthCheck"'; then
+ printf '{"status":"ok","runtimeID":"ui-understander","runtimeVersion":"0.1.0-bootstrap","modelID":"local-ui-understander","protocolVersion":"v1","metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","sidecar.role":"uiUnderstanding"}}'
+ exit 0
+fi
+
+case "ui-understander" in
+ parakeet-transcriber)
+ printf '{"text":"","language":null,"confidence":0,"segments":[],"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ yolo-segmenter)
+ printf '{"masks":[],"preprocessMS":0,"modelInferenceMS":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ ui-understander)
+ printf '{"visibleText":{},"controls":[],"formFields":[],"confidence":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+esac
diff --git a/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/ui-understander/manifest.json b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/ui-understander/manifest.json
new file mode 100644
index 00000000..44d148c6
--- /dev/null
+++ b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/ui-understander/manifest.json
@@ -0,0 +1,24 @@
+{
+ "runtimeID" : "ui-understander",
+ "runtimeVersion" : "0.1.0-bootstrap",
+ "modelID" : "local-ui-understander",
+ "platform" : "macos",
+ "architecture" : "arm64",
+ "sidecarProtocolVersion" : "v1",
+ "minimumDonkeyVersion" : "0.1.0",
+ "executableRelativePath" : "bin/donkey-ui-understander",
+ "files" : [
+ {
+ "relativePath" : "bin/donkey-ui-understander",
+ "sha256" : "606a65a716c2e757709b28dbf79d83bbe45f5898af08199bb729822796561619",
+ "isExecutable" : true
+ }
+ ],
+ "signature" : "bundled-bootstrap-package",
+ "signingKeyID" : "donkey-bootstrap",
+ "metadata" : {
+ "runtime.package" : "bundled-bootstrap",
+ "modelWeightsBundled" : "false",
+ "sidecar.role" : "uiUnderstanding"
+ }
+}
diff --git a/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/yolo-segmenter/bin/donkey-yolo-segmenter b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/yolo-segmenter/bin/donkey-yolo-segmenter
new file mode 100755
index 00000000..e8895db0
--- /dev/null
+++ b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/yolo-segmenter/bin/donkey-yolo-segmenter
@@ -0,0 +1,18 @@
+#!/usr/bin/env sh
+REQUEST="$(cat)"
+if printf '%s' "$REQUEST" | grep -q '"operation"[[:space:]]*:[[:space:]]*"healthCheck"'; then
+ printf '{"status":"ok","runtimeID":"yolo-segmenter","runtimeVersion":"0.1.0-bootstrap","modelID":"ultralytics/yolo26n-seg","protocolVersion":"v1","metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","sidecar.role":"screenshotSegmentation"}}'
+ exit 0
+fi
+
+case "yolo-segmenter" in
+ parakeet-transcriber)
+ printf '{"text":"","language":null,"confidence":0,"segments":[],"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ yolo-segmenter)
+ printf '{"masks":[],"preprocessMS":0,"modelInferenceMS":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ ui-understander)
+ printf '{"visibleText":{},"controls":[],"formFields":[],"confidence":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+esac
diff --git a/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/yolo-segmenter/manifest.json b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/yolo-segmenter/manifest.json
new file mode 100644
index 00000000..a1abb853
--- /dev/null
+++ b/dist/Donkey.app/Contents/Resources/LocalRuntimePackages/yolo-segmenter/manifest.json
@@ -0,0 +1,24 @@
+{
+ "runtimeID" : "yolo-segmenter",
+ "runtimeVersion" : "0.1.0-bootstrap",
+ "modelID" : "ultralytics/yolo26n-seg",
+ "platform" : "macos",
+ "architecture" : "arm64",
+ "sidecarProtocolVersion" : "v1",
+ "minimumDonkeyVersion" : "0.1.0",
+ "executableRelativePath" : "bin/donkey-yolo-segmenter",
+ "files" : [
+ {
+ "relativePath" : "bin/donkey-yolo-segmenter",
+ "sha256" : "8db0e080031059842d6a3433f7eedfc352cd89faa84615cbf595d7b88b70015d",
+ "isExecutable" : true
+ }
+ ],
+ "signature" : "bundled-bootstrap-package",
+ "signingKeyID" : "donkey-bootstrap",
+ "metadata" : {
+ "runtime.package" : "bundled-bootstrap",
+ "modelWeightsBundled" : "false",
+ "sidecar.role" : "screenshotSegmentation"
+ }
+}
diff --git a/dist/Donkey.app/Contents/_CodeSignature/CodeResources b/dist/Donkey.app/Contents/_CodeSignature/CodeResources
new file mode 100644
index 00000000..894ed3ff
--- /dev/null
+++ b/dist/Donkey.app/Contents/_CodeSignature/CodeResources
@@ -0,0 +1,194 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>files</key>
+ <dict>
+ <key>Resources/Donkey_Donkey.bundle/theme.json</key>
+ <data>
+ j6hDe3oLFk+aNQbAvMrblxTQZ0o=
+ </data>
+ <key>Resources/LocalRuntimePackages/parakeet-transcriber/bin/donkey-parakeet-transcriber</key>
+ <data>
+ LJbmsPPP2h/9HkBVnyL3ohU6FXU=
+ </data>
+ <key>Resources/LocalRuntimePackages/parakeet-transcriber/manifest.json</key>
+ <data>
+ frY8exiCbQVthzDGZhfHLWR62oI=
+ </data>
+ <key>Resources/LocalRuntimePackages/ui-understander/bin/donkey-ui-understander</key>
+ <data>
+ eA6eoBuMxPt35+qEFrtmsfd6d1c=
+ </data>
+ <key>Resources/LocalRuntimePackages/ui-understander/manifest.json</key>
+ <data>
+ Zvvqhh3h24GLsuBjD7dJNfLsYvs=
+ </data>
+ <key>Resources/LocalRuntimePackages/yolo-segmenter/bin/donkey-yolo-segmenter</key>
+ <data>
+ NUi9g8Ujefy0w8SEUQLYDdk0baE=
+ </data>
+ <key>Resources/LocalRuntimePackages/yolo-segmenter/manifest.json</key>
+ <data>
+ B+uM2hs6OHrKjzPEHoUIqta5T9A=
+ </data>
+ </dict>
+ <key>files2</key>
+ <dict>
+ <key>Resources/Donkey_Donkey.bundle/theme.json</key>
+ <dict>
+ <key>hash2</key>
+ <data>
+ kx22BJvOUciY+VLDVVmtp24fpHVeaw6p3QrZ4NwE3jw=
+ </data>
+ </dict>
+ <key>Resources/LocalRuntimePackages/parakeet-transcriber/bin/donkey-parakeet-transcriber</key>
+ <dict>
+ <key>hash2</key>
+ <data>
+ o2Nl38xpujddND31qp8uN9wMwDUBuYaLgq1KYLyVw48=
+ </data>
+ </dict>
+ <key>Resources/LocalRuntimePackages/parakeet-transcriber/manifest.json</key>
+ <dict>
+ <key>hash2</key>
+ <data>
+ YIjYgYs5E1O+sG/MGM9LhaRgEDpvyqxD0w4XwYXJezE=
+ </data>
+ </dict>
+ <key>Resources/LocalRuntimePackages/ui-understander/bin/donkey-ui-understander</key>
+ <dict>
+ <key>hash2</key>
+ <data>
+ YGplpxbC51dwmyjb952Du+RfWJivCBmbtymCJ5ZWFhk=
+ </data>
+ </dict>
+ <key>Resources/LocalRuntimePackages/ui-understander/manifest.json</key>
+ <dict>
+ <key>hash2</key>
+ <data>
+ dm4NLolN/h3I30fiudR/Es78MIZXTep5l3F+QSeFHrA=
+ </data>
+ </dict>
+ <key>Resources/LocalRuntimePackages/yolo-segmenter/bin/donkey-yolo-segmenter</key>
+ <dict>
+ <key>hash2</key>
+ <data>
+ jbDggAMQWYQtajQz9+7fw1LNifqoRhXL9ZXXuItwAV0=
+ </data>
+ </dict>
+ <key>Resources/LocalRuntimePackages/yolo-segmenter/manifest.json</key>
+ <dict>
+ <key>hash2</key>
+ <data>
+ WqfZ9H1l901t1yLg1GL2i0Tg82GgpH73FXVVBWl62dU=
+ </data>
+ </dict>
+ </dict>
+ <key>rules</key>
+ <dict>
+ <key>^Resources/</key>
+ <true/>
+ <key>^Resources/.*\.lproj/</key>
+ <dict>
+ <key>optional</key>
+ <true/>
+ <key>weight</key>
+ <real>1000</real>
+ </dict>
+ <key>^Resources/.*\.lproj/locversion.plist$</key>
+ <dict>
+ <key>omit</key>
+ <true/>
+ <key>weight</key>
+ <real>1100</real>
+ </dict>
+ <key>^Resources/Base\.lproj/</key>
+ <dict>
+ <key>weight</key>
+ <real>1010</real>
+ </dict>
+ <key>^version.plist$</key>
+ <true/>
+ </dict>
+ <key>rules2</key>
+ <dict>
+ <key>.*\.dSYM($|/)</key>
+ <dict>
+ <key>weight</key>
+ <real>11</real>
+ </dict>
+ <key>^(.*/)?\.DS_Store$</key>
+ <dict>
+ <key>omit</key>
+ <true/>
+ <key>weight</key>
+ <real>2000</real>
+ </dict>
+ <key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
+ <dict>
+ <key>nested</key>
+ <true/>
+ <key>weight</key>
+ <real>10</real>
+ </dict>
+ <key>^.*</key>
+ <true/>
+ <key>^Info\.plist$</key>
+ <dict>
+ <key>omit</key>
+ <true/>
+ <key>weight</key>
+ <real>20</real>
+ </dict>
+ <key>^PkgInfo$</key>
+ <dict>
+ <key>omit</key>
+ <true/>
+ <key>weight</key>
+ <real>20</real>
+ </dict>
+ <key>^Resources/</key>
+ <dict>
+ <key>weight</key>
+ <real>20</real>
+ </dict>
+ <key>^Resources/.*\.lproj/</key>
+ <dict>
+ <key>optional</key>
+ <true/>
+ <key>weight</key>
+ <real>1000</real>
+ </dict>
+ <key>^Resources/.*\.lproj/locversion.plist$</key>
+ <dict>
+ <key>omit</key>
+ <true/>
+ <key>weight</key>
+ <real>1100</real>
+ </dict>
+ <key>^Resources/Base\.lproj/</key>
+ <dict>
+ <key>weight</key>
+ <real>1010</real>
+ </dict>
+ <key>^[^/]+$</key>
+ <dict>
+ <key>nested</key>
+ <true/>
+ <key>weight</key>
+ <real>10</real>
+ </dict>
+ <key>^embedded\.provisionprofile$</key>
+ <dict>
+ <key>weight</key>
+ <real>20</real>
+ </dict>
+ <key>^version\.plist$</key>
+ <dict>
+ <key>weight</key>
+ <real>20</real>
+ </dict>
+ </dict>
+</dict>
+</plist>
diff --git a/dist/LocalRuntimePackages/parakeet-transcriber/bin/donkey-parakeet-transcriber b/dist/LocalRuntimePackages/parakeet-transcriber/bin/donkey-parakeet-transcriber
new file mode 100755
index 00000000..5634961f
--- /dev/null
+++ b/dist/LocalRuntimePackages/parakeet-transcriber/bin/donkey-parakeet-transcriber
@@ -0,0 +1,18 @@
+#!/usr/bin/env sh
+REQUEST="$(cat)"
+if printf '%s' "$REQUEST" | grep -q '"operation"[[:space:]]*:[[:space:]]*"healthCheck"'; then
+ printf '{"status":"ok","runtimeID":"parakeet-transcriber","runtimeVersion":"0.1.0-bootstrap","modelID":"nvidia/parakeet-tdt-0.6b-v3","protocolVersion":"v1","metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","sidecar.role":"voiceTranscription"}}'
+ exit 0
+fi
+
+case "parakeet-transcriber" in
+ parakeet-transcriber)
+ printf '{"text":"","language":null,"confidence":0,"segments":[],"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ yolo-segmenter)
+ printf '{"masks":[],"preprocessMS":0,"modelInferenceMS":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ ui-understander)
+ printf '{"visibleText":{},"controls":[],"formFields":[],"confidence":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+esac
diff --git a/dist/LocalRuntimePackages/parakeet-transcriber/manifest.json b/dist/LocalRuntimePackages/parakeet-transcriber/manifest.json
new file mode 100644
index 00000000..cd9a8df7
--- /dev/null
+++ b/dist/LocalRuntimePackages/parakeet-transcriber/manifest.json
@@ -0,0 +1,24 @@
+{
+ "runtimeID" : "parakeet-transcriber",
+ "runtimeVersion" : "0.1.0-bootstrap",
+ "modelID" : "nvidia/parakeet-tdt-0.6b-v3",
+ "platform" : "macos",
+ "architecture" : "arm64",
+ "sidecarProtocolVersion" : "v1",
+ "minimumDonkeyVersion" : "0.1.0",
+ "executableRelativePath" : "bin/donkey-parakeet-transcriber",
+ "files" : [
+ {
+ "relativePath" : "bin/donkey-parakeet-transcriber",
+ "sha256" : "a36365dfcc69ba375d343df5aa9f2e37dc0cc03501b9868b82ad4a60bc95c38f",
+ "isExecutable" : true
+ }
+ ],
+ "signature" : "bundled-bootstrap-package",
+ "signingKeyID" : "donkey-bootstrap",
+ "metadata" : {
+ "runtime.package" : "bundled-bootstrap",
+ "modelWeightsBundled" : "false",
+ "sidecar.role" : "voiceTranscription"
+ }
+}
diff --git a/dist/LocalRuntimePackages/ui-understander/bin/donkey-ui-understander b/dist/LocalRuntimePackages/ui-understander/bin/donkey-ui-understander
new file mode 100755
index 00000000..fd4ac4df
--- /dev/null
+++ b/dist/LocalRuntimePackages/ui-understander/bin/donkey-ui-understander
@@ -0,0 +1,18 @@
+#!/usr/bin/env sh
+REQUEST="$(cat)"
+if printf '%s' "$REQUEST" | grep -q '"operation"[[:space:]]*:[[:space:]]*"healthCheck"'; then
+ printf '{"status":"ok","runtimeID":"ui-understander","runtimeVersion":"0.1.0-bootstrap","modelID":"local-ui-understander","protocolVersion":"v1","metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","sidecar.role":"uiUnderstanding"}}'
+ exit 0
+fi
+
+case "ui-understander" in
+ parakeet-transcriber)
+ printf '{"text":"","language":null,"confidence":0,"segments":[],"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ yolo-segmenter)
+ printf '{"masks":[],"preprocessMS":0,"modelInferenceMS":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ ui-understander)
+ printf '{"visibleText":{},"controls":[],"formFields":[],"confidence":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+esac
diff --git a/dist/LocalRuntimePackages/ui-understander/manifest.json b/dist/LocalRuntimePackages/ui-understander/manifest.json
new file mode 100644
index 00000000..44d148c6
--- /dev/null
+++ b/dist/LocalRuntimePackages/ui-understander/manifest.json
@@ -0,0 +1,24 @@
+{
+ "runtimeID" : "ui-understander",
+ "runtimeVersion" : "0.1.0-bootstrap",
+ "modelID" : "local-ui-understander",
+ "platform" : "macos",
+ "architecture" : "arm64",
+ "sidecarProtocolVersion" : "v1",
+ "minimumDonkeyVersion" : "0.1.0",
+ "executableRelativePath" : "bin/donkey-ui-understander",
+ "files" : [
+ {
+ "relativePath" : "bin/donkey-ui-understander",
+ "sha256" : "606a65a716c2e757709b28dbf79d83bbe45f5898af08199bb729822796561619",
+ "isExecutable" : true
+ }
+ ],
+ "signature" : "bundled-bootstrap-package",
+ "signingKeyID" : "donkey-bootstrap",
+ "metadata" : {
+ "runtime.package" : "bundled-bootstrap",
+ "modelWeightsBundled" : "false",
+ "sidecar.role" : "uiUnderstanding"
+ }
+}
diff --git a/dist/LocalRuntimePackages/yolo-segmenter/bin/donkey-yolo-segmenter b/dist/LocalRuntimePackages/yolo-segmenter/bin/donkey-yolo-segmenter
new file mode 100755
index 00000000..e8895db0
--- /dev/null
+++ b/dist/LocalRuntimePackages/yolo-segmenter/bin/donkey-yolo-segmenter
@@ -0,0 +1,18 @@
+#!/usr/bin/env sh
+REQUEST="$(cat)"
+if printf '%s' "$REQUEST" | grep -q '"operation"[[:space:]]*:[[:space:]]*"healthCheck"'; then
+ printf '{"status":"ok","runtimeID":"yolo-segmenter","runtimeVersion":"0.1.0-bootstrap","modelID":"ultralytics/yolo26n-seg","protocolVersion":"v1","metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","sidecar.role":"screenshotSegmentation"}}'
+ exit 0
+fi
+
+case "yolo-segmenter" in
+ parakeet-transcriber)
+ printf '{"text":"","language":null,"confidence":0,"segments":[],"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ yolo-segmenter)
+ printf '{"masks":[],"preprocessMS":0,"modelInferenceMS":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ ui-understander)
+ printf '{"visibleText":{},"controls":[],"formFields":[],"confidence":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+esac
diff --git a/dist/LocalRuntimePackages/yolo-segmenter/manifest.json b/dist/LocalRuntimePackages/yolo-segmenter/manifest.json
new file mode 100644
index 00000000..a1abb853
--- /dev/null
+++ b/dist/LocalRuntimePackages/yolo-segmenter/manifest.json
@@ -0,0 +1,24 @@
+{
+ "runtimeID" : "yolo-segmenter",
+ "runtimeVersion" : "0.1.0-bootstrap",
+ "modelID" : "ultralytics/yolo26n-seg",
+ "platform" : "macos",
+ "architecture" : "arm64",
+ "sidecarProtocolVersion" : "v1",
+ "minimumDonkeyVersion" : "0.1.0",
+ "executableRelativePath" : "bin/donkey-yolo-segmenter",
+ "files" : [
+ {
+ "relativePath" : "bin/donkey-yolo-segmenter",
+ "sha256" : "8db0e080031059842d6a3433f7eedfc352cd89faa84615cbf595d7b88b70015d",
+ "isExecutable" : true
+ }
+ ],
+ "signature" : "bundled-bootstrap-package",
+ "signingKeyID" : "donkey-bootstrap",
+ "metadata" : {
+ "runtime.package" : "bundled-bootstrap",
+ "modelWeightsBundled" : "false",
+ "sidecar.role" : "screenshotSegmentation"
+ }
+}
diff --git a/docs/README.md b/docs/README.md
index fd7f1653..254deae4 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -9,6 +9,7 @@ There is an active milestone plan in `plans/master-plan.md`. It tracks the unfin
## Product Guides
- [Pointer Prompt Overlay](guides/pointer-prompt-overlay.md): double-Command standard macOS-style `Make this so` composer that opens near the mouse at a fixed offset.
+- [Install Donkey Locally](guides/install-donkey.md): package the SwiftPM executable into a clickable local macOS app bundle for manual testing.
## Engineering Guides
diff --git a/docs/guides/install-donkey.md b/docs/guides/install-donkey.md
new file mode 100644
index 00000000..6031c0e9
--- /dev/null
+++ b/docs/guides/install-donkey.md
@@ -0,0 +1,25 @@
+# Install Donkey Locally
+
+Donkey can be packaged into a local macOS app bundle for manual testing.
+
+From the repo root:
+
+```bash
+./scripts/package-donkey-app.sh
+```
+
+The script builds the release executable, creates `dist/Donkey.app`, copies bundled resources, and applies an ad-hoc signature when `codesign` is available.
+
+To launch the packaged app:
+
+```bash
+open dist/Donkey.app
+```
+
+The package script also creates Donkey-compatible bootstrap sidecar runtime packages under `dist/LocalRuntimePackages` and embeds them into:
+
+```text
+dist/Donkey.app/Contents/Resources/LocalRuntimePackages/
+```
+
+On first launch, Donkey shows one setup button for local runtimes. Setup installs the bundled sidecar packages first, verifies their manifests/checksums, registers them in Application Support, and health-checks them. The bundled packages do not include model weights; they are the installation surface for the sidecar runners. If setup fails, clicking the same button retries failed or not-yet-attempted runtimes while keeping completed installs.
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index 5b4c381e..2e07bc69 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -46,7 +46,9 @@ Donkey also supports the first AI harness model registry and router boundary. `A
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 user-downloaded runtime folders, downloads manifest-backed package files, enforces SHA-256 checksums and required signature metadata, caches verified package files under Application Support, and records executable paths in `~/Library/Application Support/Donkey/LocalModelRuntimes/runtime-installations.json`. After registration, sidecar calls can resolve app-managed executables without shell environment variables. The first-run setup window exposes one setup button that downloads, verifies, installs, registers, and health-checks all required runtimes, with one overall ready or retryable needs-attention state. Retry keeps completed runtime installs and resumes at failed or not-yet-attempted runtimes. Developer launch arguments can print setup instructions, show install status, or register a downloaded runtime folder.
+Donkey's live local-app observation path uses Accessibility and bounded screenshots only. `MacLocalAppTaskController` first reads Accessibility controls and visible text when trusted. If required controls or verification text are missing, it captures a bounded target-window screenshot with ScreenCaptureKit and sends that image to `ProcessBackedLocalUIUnderstandingAdapter`; the adapter output is merged into `LocalAppTaskObservation` as visible text, controls, form fields, confidence, and metadata. Screenshot understanding never emits direct input actions.
+
+Donkey also supports the first post-install local runtime setup boundary. The app package does not ship model weights, but `scripts/package-donkey-app.sh` creates Donkey-compatible bootstrap sidecar runtime packages and embeds them in `Donkey.app/Contents/Resources/LocalRuntimePackages/`. `LocalModelRuntimeSetupManager` describes the required Parakeet, YOLO26, and UI-understanding runtime packages, provides user-facing setup instructions, installs bundled package manifests before remote manifests, validates user-downloaded runtime folders, downloads manifest-backed package files when configured, enforces SHA-256 checksums and required signature metadata, caches verified package files under Application Support, and records executable paths in `~/Library/Application Support/Donkey/LocalModelRuntimes/runtime-installations.json`. After registration, sidecar calls can resolve app-managed executables without shell environment variables. The first-run setup window exposes one setup button that installs/downloads, verifies, registers, and health-checks all required runtimes, with one overall ready or retryable needs-attention state. Retry keeps completed runtime installs and resumes at failed or not-yet-attempted runtimes. 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.
@@ -77,7 +79,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 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.
+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 wired into live local-app observation, 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 wired from pointer-prompt microphone buffers, 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
diff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.md
index 7c2e9d06..d084173a 100644
--- a/docs/guides/pointer-prompt-overlay.md
+++ b/docs/guides/pointer-prompt-overlay.md
@@ -10,6 +10,7 @@ Donkey supports a floating macOS pointer prompt overlay:
- uses a wide pill-shaped prompt for single-line text, then expands to a rounded rectangle when text wraps at the max input width or the user inserts new lines
- places the waveform in a bottom toolbar that blends with the input background when the prompt is expanded
- captures microphone audio while active and renders the waveform from recent live audio levels
+- on voice activation, records a bounded local audio buffer, sends it to the Parakeet-only local transcription adapter, displays transcript progress, and submits decoded transcript text through the same command path as typed input
- keeps the prompt modal pinned where activation happened until the user drags, dismisses, or closes the modal
- dismisses the active modal when the user clicks outside it
- closes the active modal with a small high-contrast circular x button outside the prompt surface at the top-right corner
@@ -19,7 +20,7 @@ Donkey supports a floating macOS pointer prompt overlay:
- keeps that fixed offset at screen edges instead of flipping or clamping to the visible screen bounds
- submits typed prompt text through the local-app command pipeline while keeping model parsing, task validation, and live input outside the SwiftUI rendering path
-This is a visual, typed-command, and microphone-level UI capability. Typed submissions go to the local-app command handler, which loads built-in plus local JSON/JSONL task definitions, prefers local-model task-intent parsing, validates the intent against the app-task catalog, and then runs the guarded local-app live runner. Review-only document tasks can return a compact review summary such as the number of mapped fields. The overlay itself does not capture the screen, synthesize input, transcribe speech, or require Accessibility permission. It does request microphone permission so the waveform can reflect live local audio levels. The AI harness has a local voice-transcription adapter boundary, but the overlay has not yet wired microphone buffers into that speech-to-text adapter.
+This is a visual, typed-command, and voice-command UI capability. Typed submissions go to the local-app command handler, which loads built-in plus local JSON/JSONL task definitions, prefers local-model task-intent parsing, validates the intent against the app-task catalog, and then runs the guarded local-app live runner. Voice submissions produce local transcript text through the Parakeet-only transcription boundary before entering that same command handler. Review-only document tasks can return a compact review summary such as the number of mapped fields. The overlay itself does not capture the screen, synthesize input, or require Accessibility permission. It does request microphone permission for local waveform capture and voice commands.
## Technical Guidelines
@@ -44,7 +45,7 @@ This is a visual, typed-command, and microphone-level UI capability. Typed submi
- Holding the second clean Command press for the shortcut's configured hold duration should activate the prompt modal and start microphone level capture instead of waiting for the second release.
- Keep the overlay non-invasive: no screen capture loop, input execution, Accessibility prompt, or direct model call in SwiftUI rendering. Submit text to a command handler boundary instead.
- Keep the command handler data-driven. It should resolve task knowledge from the local catalog, including local task definitions in Application Support, before invoking the guarded runtime path.
-- Keep voice capture separate from transcription. The overlay may publish bounded local audio buffers to a future transcription adapter, but model execution and command parsing should remain outside the SwiftUI view/controller rendering path.
+- Keep voice capture separate from transcription. The overlay publishes bounded local audio buffers to the model layer, and model execution plus command parsing remain outside the SwiftUI view/controller rendering path.
## Verification
diff --git a/plans/22-local-runtime-onboarding.md b/plans/22-local-runtime-onboarding.md
index 50b76110..088e4b90 100644
--- a/plans/22-local-runtime-onboarding.md
+++ b/plans/22-local-runtime-onboarding.md
@@ -157,6 +157,8 @@ Already supported:
- `LocalModelRuntimeSetupManager` runtime specs, setup instructions, registration, status, and app-managed executable resolution.
- First-run local runtime setup window with one setup button that drives download, validation, install, registration, and health checks.
+- Package-time bundled bootstrap sidecar runtime packages embedded under `Donkey.app/Contents/Resources/LocalRuntimePackages/`.
+- Setup manager installation from bundled package manifests before remote manifest download.
- Manifest-backed package download and managed cache install under Application Support.
- SHA-256 package file validation and required signature metadata.
- Sidecar health-check protocol through the existing JSON process runner.
@@ -168,7 +170,7 @@ Already supported:
Still needed:
-- Publish real Donkey-compatible runtime package manifests and downloadable files.
+- Replace bootstrap sidecar packages with real model-weight runner packages.
- Finalize cryptographic signature verification with release signing keys.
- Settings-menu entry to reopen the setup window after first launch.
- Behind-the-scenes upgrade/repair/remove flows.
diff --git a/plans/master-plan.md b/plans/master-plan.md
index ddf06fc9..2889eabb 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -37,7 +37,7 @@ user command: "show me the weather for SF"
-> local intent parse from app-task definitions: weather_lookup(city: "San Francisco")
-> generic local-app task adapter with Weather as data
-> launch or focus app
- -> observe app state through Accessibility/window metadata/screenshot fallback
+ -> observe app state through Accessibility and bounded screenshots
-> deterministic UI controller
-> guarded keyboard/mouse/Accessibility action execution
-> verify Weather is showing San Francisco
@@ -56,10 +56,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, first-run local runtime setup UI, manifest-backed runtime download/cache/registration in Application Support, sidecar health recheck, 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.
+- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, first-run local runtime setup UI, package-time bundled bootstrap sidecar runtime packages, manifest-backed runtime install/download/cache/registration in Application Support, sidecar health recheck, 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, bounded screenshot UI-understanding observation when Accessibility is insufficient, 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, 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, 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.
+- 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, pointer-prompt microphone buffers feeding the Parakeet runtime before command parsing, 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 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
@@ -85,15 +85,14 @@ 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 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, first-run local runtime setup UI, manifest-backed runtime download/cache/registration, checksum/signature metadata enforcement, sidecar health recheck, semantic memory retrieval contracts, redaction hooks, aggregate model-call observability, provider-decoded memory proposal handling, and expanded latency reporting. It does not yet publish real Donkey-compatible runtime packages, 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.
+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 and voice 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 wired into live observation over bounded screenshots, Parakeet-only local voice-transcription routing and sidecar runtime, shared JSON sidecar runner, first-run local runtime setup UI, package-time bundled bootstrap sidecar runtime packages, manifest-backed runtime install/download/cache/registration, checksum/signature metadata enforcement, sidecar health recheck, semantic memory retrieval contracts, redaction hooks, aggregate model-call observability, provider-decoded memory proposal handling, expanded latency reporting, and a package script that produces `dist/Donkey.app`. It does not yet include real model-weight runner packages or a manually verified live command-to-result Weather trace.
## What Should Be Done Next
-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. Follow `plans/22-local-runtime-onboarding.md` to publish real Donkey-compatible runtime package manifests/files, finalize release-key cryptographic signature verification, keep first-run setup to one app-managed button, add behind-the-scenes repair/remove flows, 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.
+1. Replace the bundled bootstrap sidecar packages with real model-weight runner packages, finalize release-key cryptographic signature verification, keep first-run setup to one app-managed button, add behind-the-scenes repair/remove flows, then run real machine-local sidecar binaries registered by the app-managed installer for YOLO, Parakeet, and UI understanding.
+2. Manually verify the packaged app from `dist/Donkey.app` on the first Weather command path, then record the live command-to-result trace and stage metrics.
+3. Record metric samples for weather/media/document tasks using the existing metadata fields for command parse, launch/focus, observation, Accessibility action, keyboard action, verification, YOLO segmentation, UI-understanding, and Parakeet transcription. Improve benchmarking later.
+4. 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
diff --git a/scripts/package-donkey-app.sh b/scripts/package-donkey-app.sh
new file mode 100755
index 00000000..a3154e41
--- /dev/null
+++ b/scripts/package-donkey-app.sh
@@ -0,0 +1,138 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+APP_DIR="$ROOT_DIR/dist/Donkey.app"
+RUNTIME_PACKAGE_DIR="$ROOT_DIR/dist/LocalRuntimePackages"
+CONTENTS_DIR="$APP_DIR/Contents"
+MACOS_DIR="$CONTENTS_DIR/MacOS"
+RESOURCES_DIR="$CONTENTS_DIR/Resources"
+BUILD_DIR="$ROOT_DIR/apps/Donkey"
+EXECUTABLE="$BUILD_DIR/.build/release/Donkey"
+CACHE_DIR="$BUILD_DIR/.build/package-cache"
+
+mkdir -p "$CACHE_DIR/clang" "$CACHE_DIR/swiftpm" "$CACHE_DIR/home"
+export CLANG_MODULE_CACHE_PATH="$CACHE_DIR/clang"
+export SWIFTPM_CACHE_PATH="$CACHE_DIR/swiftpm"
+export HOME="$CACHE_DIR/home"
+
+cd "$BUILD_DIR"
+swift build -c release --product Donkey
+
+rm -rf "$APP_DIR"
+mkdir -p "$MACOS_DIR" "$RESOURCES_DIR"
+cp "$EXECUTABLE" "$MACOS_DIR/Donkey"
+
+make_runtime_package() {
+ local runtime_id="$1"
+ local executable_name="$2"
+ local model_id="$3"
+ local role="$4"
+ local package_dir="$RUNTIME_PACKAGE_DIR/$runtime_id"
+ local bin_dir="$package_dir/bin"
+ local executable_path="$bin_dir/$executable_name"
+
+ mkdir -p "$bin_dir"
+ cat > "$executable_path" <<EOF_RUNTIME
+#!/usr/bin/env sh
+REQUEST="\$(cat)"
+if printf '%s' "\$REQUEST" | grep -q '"operation"[[:space:]]*:[[:space:]]*"healthCheck"'; then
+ printf '{"status":"ok","runtimeID":"$runtime_id","runtimeVersion":"0.1.0-bootstrap","modelID":"$model_id","protocolVersion":"v1","metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","sidecar.role":"$role"}}'
+ exit 0
+fi
+
+case "$runtime_id" in
+ parakeet-transcriber)
+ printf '{"text":"","language":null,"confidence":0,"segments":[],"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ yolo-segmenter)
+ printf '{"masks":[],"preprocessMS":0,"modelInferenceMS":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+ ui-understander)
+ printf '{"visibleText":{},"controls":[],"formFields":[],"confidence":0,"metadata":{"runtime.package":"bundled-bootstrap","modelWeightsBundled":"false","reason":"modelWeightsNotInstalled"}}'
+ ;;
+esac
+EOF_RUNTIME
+ chmod 755 "$executable_path"
+
+ local sha
+ sha="$(shasum -a 256 "$executable_path" | awk '{print $1}')"
+ cat > "$package_dir/manifest.json" <<EOF_MANIFEST
+{
+ "runtimeID" : "$runtime_id",
+ "runtimeVersion" : "0.1.0-bootstrap",
+ "modelID" : "$model_id",
+ "platform" : "macos",
+ "architecture" : "$(uname -m | sed 's/aarch64/arm64/;s/x86_64/x86_64/')",
+ "sidecarProtocolVersion" : "v1",
+ "minimumDonkeyVersion" : "0.1.0",
+ "executableRelativePath" : "bin/$executable_name",
+ "files" : [
+ {
+ "relativePath" : "bin/$executable_name",
+ "sha256" : "$sha",
+ "isExecutable" : true
+ }
+ ],
+ "signature" : "bundled-bootstrap-package",
+ "signingKeyID" : "donkey-bootstrap",
+ "metadata" : {
+ "runtime.package" : "bundled-bootstrap",
+ "modelWeightsBundled" : "false",
+ "sidecar.role" : "$role"
+ }
+}
+EOF_MANIFEST
+}
+
+rm -rf "$RUNTIME_PACKAGE_DIR"
+mkdir -p "$RUNTIME_PACKAGE_DIR"
+make_runtime_package "parakeet-transcriber" "donkey-parakeet-transcriber" "nvidia/parakeet-tdt-0.6b-v3" "voiceTranscription"
+make_runtime_package "yolo-segmenter" "donkey-yolo-segmenter" "ultralytics/yolo26n-seg" "screenshotSegmentation"
+make_runtime_package "ui-understander" "donkey-ui-understander" "local-ui-understander" "uiUnderstanding"
+cp -R "$RUNTIME_PACKAGE_DIR" "$RESOURCES_DIR/LocalRuntimePackages"
+
+RESOURCE_BUNDLE="$(find "$BUILD_DIR/.build" -path "*/release/Donkey_Donkey.bundle" -type d | head -n 1 || true)"
+if [ -n "$RESOURCE_BUNDLE" ]; then
+ cp -R "$RESOURCE_BUNDLE" "$RESOURCES_DIR/"
+elif [ -d "$BUILD_DIR/.build/release/Donkey_Donkey.resources" ]; then
+ cp -R "$BUILD_DIR/.build/release/Donkey_Donkey.resources/." "$RESOURCES_DIR/"
+fi
+
+cat > "$CONTENTS_DIR/Info.plist" <<'PLIST'
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleExecutable</key>
+ <string>Donkey</string>
+ <key>CFBundleIdentifier</key>
+ <string>ai.donkey.Donkey</string>
+ <key>CFBundleName</key>
+ <string>Donkey</string>
+ <key>CFBundleDisplayName</key>
+ <string>Donkey</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>0.1.0</string>
+ <key>CFBundleVersion</key>
+ <string>1</string>
+ <key>LSMinimumSystemVersion</key>
+ <string>14.0</string>
+ <key>NSMicrophoneUsageDescription</key>
+ <string>Donkey uses the microphone for local voice commands.</string>
+ <key>NSScreenCaptureUsageDescription</key>
+ <string>Donkey captures bounded screenshots so local runtimes can understand app UI.</string>
+ <key>NSAppleEventsUsageDescription</key>
+ <string>Donkey uses local app automation only for user-requested actions.</string>
+</dict>
+</plist>
+PLIST
+
+if command -v codesign >/dev/null 2>&1; then
+ codesign --force --deep --sign - "$APP_DIR" >/dev/null
+fi
+
+echo "Packaged $APP_DIR"
+echo "Open it with: open \"$APP_DIR\""