Open source CapCut alternative.
TypeScript
Add local app task catalog and availability checks
David Le99a505f779dd
diff --git a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swiftindex f655e0d9..90bb9b8d 100644--- a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift@@ -114,12 +114,20 @@ public struct LocalAppTaskWorkflowStepDefinition: Codable, Equatable, Sendable {}}+public enum LocalAppObservationStrategy: String, Codable, Equatable, Sendable {+ case accessibility+ case windowMetadata+ case screenshotForLocalModel = "screenshot_for_local_model"+ case screenshotOCR = "screenshot_ocr"+}+public struct LocalAppTaskDefinition: Codable, Equatable, Sendable {public var taskType: Stringpublic var targetApp: LocalAppTargetpublic var triggerTerms: [String]public var entityRules: [LocalAppTaskEntityRule]public var workflowSteps: [LocalAppTaskWorkflowStepDefinition]+ public var observationStrategies: [LocalAppObservationStrategy]public var verificationEntityName: String?public var metadata: [String: String]@@ -129,6 +137,7 @@ public struct LocalAppTaskDefinition: Codable, Equatable, Sendable {triggerTerms: [String],entityRules: [LocalAppTaskEntityRule] = [],workflowSteps: [LocalAppTaskWorkflowStepDefinition] = [],+ observationStrategies: [LocalAppObservationStrategy] = [.accessibility, .windowMetadata, .screenshotForLocalModel],verificationEntityName: String? = nil,metadata: [String: String] = [:]) {@@ -137,6 +146,7 @@ public struct LocalAppTaskDefinition: Codable, Equatable, Sendable {self.triggerTerms = triggerTermsself.entityRules = entityRulesself.workflowSteps = workflowSteps+ self.observationStrategies = observationStrategiesself.verificationEntityName = verificationEntityNameself.metadata = metadata}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swiftnew file mode 100644index 00000000..89d1450a--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift@@ -0,0 +1,259 @@+import AppKit+import DonkeyContracts+import Foundation++public struct LocalAppAvailability: Equatable, Sendable {+ public var target: LocalAppTarget+ public var isInstalled: Bool+ public var appURL: URL?+ public var metadata: [String: String]++ public init(+ target: LocalAppTarget,+ isInstalled: Bool,+ appURL: URL? = nil,+ metadata: [String: String] = [:]+ ) {+ self.target = target+ self.isInstalled = isInstalled+ self.appURL = appURL+ self.metadata = metadata+ }+}++public protocol LocalAppAvailabilityProviding: Sendable {+ func availability(for target: LocalAppTarget) -> LocalAppAvailability+}++public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {+ public init() {}++ public func availability(for target: LocalAppTarget) -> LocalAppAvailability {+ guard let bundleIdentifier = target.bundleIdentifier else {+ return LocalAppAvailability(+ target: target,+ isInstalled: false,+ metadata: ["reason": "missingBundleIdentifier"]+ )+ }++ let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier)+ return LocalAppAvailability(+ target: target,+ isInstalled: appURL != nil,+ appURL: appURL,+ metadata: [+ "bundleIdentifier": bundleIdentifier,+ "provider": "mac-nsworkspace"+ ]+ )+ }+}++public struct StaticLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {+ public var installedBundleIdentifiers: Set<String>++ public init(installedBundleIdentifiers: Set<String>) {+ self.installedBundleIdentifiers = installedBundleIdentifiers+ }++ public func availability(for target: LocalAppTarget) -> LocalAppAvailability {+ let bundleIdentifier = target.bundleIdentifier ?? ""+ return LocalAppAvailability(+ target: target,+ isInstalled: installedBundleIdentifiers.contains(bundleIdentifier),+ metadata: [+ "bundleIdentifier": bundleIdentifier,+ "provider": "static"+ ]+ )+ }+}++public enum LocalAppTaskCatalogResolutionStatus: String, Equatable, Sendable {+ case resolved+ case needsConfirmation+ case unsupportedCommand+ case appUnavailable+}++public struct LocalAppTaskCatalogResolution: Equatable, Sendable {+ public var status: LocalAppTaskCatalogResolutionStatus+ public var intent: TaskIntent?+ public var definition: LocalAppTaskDefinition?+ public var availability: LocalAppAvailability?+ public var metadata: [String: String]++ public init(+ status: LocalAppTaskCatalogResolutionStatus,+ intent: TaskIntent? = nil,+ definition: LocalAppTaskDefinition? = nil,+ availability: LocalAppAvailability? = nil,+ metadata: [String: String] = [:]+ ) {+ self.status = status+ self.intent = intent+ self.definition = definition+ self.availability = availability+ self.metadata = metadata+ }+}++public struct LocalAppTaskCatalog: Sendable {+ public var taskDefinitions: [LocalAppTaskDefinition]+ public var availabilityProvider: any LocalAppAvailabilityProviding++ public init(+ taskDefinitions: [LocalAppTaskDefinition],+ availabilityProvider: any LocalAppAvailabilityProviding = MacLocalAppAvailabilityProvider()+ ) {+ self.taskDefinitions = taskDefinitions+ self.availabilityProvider = availabilityProvider+ }++ public func resolve(command: String) -> LocalAppTaskCatalogResolution {+ guard let intent = LocalAppTaskIntentParser(taskDefinitions: taskDefinitions).parse(command) else {+ return LocalAppTaskCatalogResolution(+ status: .unsupportedCommand,+ metadata: ["reason": "noTaskDefinitionMatched"]+ )+ }++ guard let definition = taskDefinitions.first(where: { supports(intent: intent, definition: $0) }) else {+ return LocalAppTaskCatalogResolution(+ status: .unsupportedCommand,+ intent: intent,+ metadata: ["reason": "parsedIntentDefinitionMissing"]+ )+ }++ if intent.needsConfirmation {+ return LocalAppTaskCatalogResolution(+ status: .needsConfirmation,+ intent: intent,+ definition: definition,+ metadata: ["reason": intent.metadata["missingEntity"] ?? "needsConfirmation"]+ )+ }++ let availability = availabilityProvider.availability(for: definition.targetApp)+ guard availability.isInstalled else {+ return LocalAppTaskCatalogResolution(+ status: .appUnavailable,+ intent: intent,+ definition: definition,+ availability: availability,+ metadata: ["reason": "targetAppUnavailable"]+ )+ }++ return LocalAppTaskCatalogResolution(+ status: .resolved,+ intent: intent,+ definition: definition,+ availability: availability,+ metadata: [+ "taskType": definition.taskType,+ "targetApp": definition.targetApp.appName+ ]+ )+ }++ public func adapter(for definition: LocalAppTaskDefinition) -> LocalAppTaskAdapter {+ LocalAppTaskAdapter(definition: definition)+ }++ private func supports(+ intent: TaskIntent,+ definition: LocalAppTaskDefinition+ ) -> Bool {+ intent.taskType == definition.taskType+ && intent.targetApp.appName == definition.targetApp.appName+ && intent.targetApp.bundleIdentifier == definition.targetApp.bundleIdentifier+ }+}++public enum BuiltInLocalAppTaskDefinitions {+ public static var weatherLookup: LocalAppTaskDefinition {+ LocalAppTaskDefinition(+ taskType: "weather_lookup",+ targetApp: LocalAppTarget(+ appName: "Weather",+ bundleIdentifier: "com.apple.weather",+ titleContains: "Weather"+ ),+ triggerTerms: ["weather", "forecast", "temperature", "temp"],+ entityRules: [+ LocalAppTaskEntityRule(+ name: "city",+ markers: ["for", "in", "at", "near"],+ aliases: [+ "sf": "San Francisco",+ "san fran": "San Francisco",+ "san francisco": "San Francisco",+ "nyc": "New York",+ "new york city": "New York",+ "la": "Los Angeles",+ "los angeles": "Los Angeles"+ ]+ )+ ],+ workflowSteps: [+ LocalAppTaskWorkflowStepDefinition(+ id: "parse-intent",+ role: .parseIntent,+ summary: "Parse the local app task intent"+ ),+ LocalAppTaskWorkflowStepDefinition(+ id: "launch-or-focus",+ role: .launchOrFocusApp,+ summary: "Launch or focus the target app"+ ),+ LocalAppTaskWorkflowStepDefinition(+ id: "observe-app",+ role: .observeApp,+ summary: "Observe the target app state",+ metadata: ["strategyOrder": "accessibility,windowMetadata,screenshotForLocalModel"]+ ),+ LocalAppTaskWorkflowStepDefinition(+ id: "focus-search",+ role: .focusControl,+ summary: "Focus the task control",+ metadata: [+ "controlID": "search",+ "key": "Command+F"+ ]+ ),+ LocalAppTaskWorkflowStepDefinition(+ id: "enter-city",+ role: .enterText,+ summary: "Enter the normalized entity",+ metadata: ["entityName": "city"]+ ),+ LocalAppTaskWorkflowStepDefinition(+ id: "submit-search",+ role: .submit,+ summary: "Submit the task",+ metadata: ["key": "Return"]+ ),+ LocalAppTaskWorkflowStepDefinition(+ id: "verify-city",+ role: .verifyResult,+ summary: "Verify the visible result"+ )+ ],+ observationStrategies: [.accessibility, .windowMetadata, .screenshotForLocalModel],+ verificationEntityName: "city",+ metadata: [+ "catalogEntry": "built-in-weather-lookup",+ "verificationTextKey": "city",+ "visualFallback": "localModel",+ "ocrFallbackDefault": "false"+ ]+ )+ }++ public static var defaults: [LocalAppTaskDefinition] {+ [weatherLookup]+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swiftindex 454c5b3c..55d79e47 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift@@ -17,7 +17,7 @@ struct LocalAppTaskTests {#expect(intent.confidence == 0.96)#expect(intent.parserSource == .deterministic)#expect(intent.needsConfirmation == false)- #expect(intent.metadata["catalogEntry"] == "fixture-weather-lookup")+ #expect(intent.metadata["catalogEntry"] == "built-in-weather-lookup")#expect(intent.metadata["entityAliasExpanded"] == "true")}@@ -72,6 +72,8 @@ struct LocalAppTaskTests {])#expect(plan.steps.last?.status == .blocked)#expect(plan.metadata["defaultOSInputBackendAvailable"] == "false")+ #expect(plan.metadata["visualFallback"] == "localModel")+ #expect(plan.metadata["ocrFallbackDefault"] == "false")let commands = localAdapter.guardedKeyboardCommandTemplates(for: intent,@@ -106,83 +108,49 @@ struct LocalAppTaskTests {#expect(localAdapter.verifiesVisibleText("New York", matches: intent) == false)}- private func parser() -> LocalAppTaskIntentParser {- LocalAppTaskIntentParser(taskDefinitions: [fixtureWeatherLookupDefinition()])- }+ @Test+ func catalogResolvesCommandAgainstAvailableInstalledAppDefinition() throws {+ let catalog = LocalAppTaskCatalog(+ taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])+ )- private func adapter() -> LocalAppTaskAdapter {- LocalAppTaskAdapter(definition: fixtureWeatherLookupDefinition())+ let resolution = catalog.resolve(command: "show me the weather for SF")++ #expect(resolution.status == .resolved)+ #expect(resolution.intent?.normalizedEntities["city"] == "San Francisco")+ #expect(resolution.definition?.taskType == "weather_lookup")+ #expect(resolution.definition?.observationStrategies == [.accessibility, .windowMetadata, .screenshotForLocalModel])+ #expect(resolution.availability?.isInstalled == true)++ let definition = try #require(resolution.definition)+ let intent = try #require(resolution.intent)+ let plan = catalog.adapter(for: definition).dryRunPlan(for: intent)+ #expect(plan.steps.map(\.role).contains(.verifyResult))}- private func fixtureWeatherLookupDefinition() -> LocalAppTaskDefinition {- LocalAppTaskDefinition(- taskType: "weather_lookup",- targetApp: LocalAppTarget(- appName: "Weather",- bundleIdentifier: "com.apple.weather",- titleContains: "Weather"- ),- triggerTerms: ["weather", "forecast", "temperature", "temp"],- entityRules: [- LocalAppTaskEntityRule(- name: "city",- markers: ["for", "in", "at", "near"],- aliases: [- "sf": "San Francisco",- "san fran": "San Francisco",- "san francisco": "San Francisco"- ]- )- ],- workflowSteps: [- LocalAppTaskWorkflowStepDefinition(- id: "parse-intent",- role: .parseIntent,- summary: "Parse the local app task intent"- ),- LocalAppTaskWorkflowStepDefinition(- id: "launch-or-focus",- role: .launchOrFocusApp,- summary: "Launch or focus the target app"- ),- LocalAppTaskWorkflowStepDefinition(- id: "observe-app",- role: .observeApp,- summary: "Observe the target app state"- ),- LocalAppTaskWorkflowStepDefinition(- id: "focus-search",- role: .focusControl,- summary: "Focus the task control",- metadata: [- "controlID": "search",- "key": "Command+F"- ]- ),- LocalAppTaskWorkflowStepDefinition(- id: "enter-city",- role: .enterText,- summary: "Enter the normalized entity",- metadata: ["entityName": "city"]- ),- LocalAppTaskWorkflowStepDefinition(- id: "submit-search",- role: .submit,- summary: "Submit the task",- metadata: ["key": "Return"]- ),- LocalAppTaskWorkflowStepDefinition(- id: "verify-city",- role: .verifyResult,- summary: "Verify the visible result"- )- ],- verificationEntityName: "city",- metadata: [- "catalogEntry": "fixture-weather-lookup",- "verificationTextKey": "city"- ]+ @Test+ func catalogSeparatesUnsupportedMissingEntityAndUnavailableApp() {+ let availableCatalog = LocalAppTaskCatalog(+ taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])+ )+ #expect(availableCatalog.resolve(command: "open my calendar").status == .unsupportedCommand)+ #expect(availableCatalog.resolve(command: "show me the weather").status == .needsConfirmation)++ let unavailableCatalog = LocalAppTaskCatalog(+ taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: []))+ #expect(unavailableCatalog.resolve(command: "show me the weather for SF").status == .appUnavailable)+ }++ private func parser() -> LocalAppTaskIntentParser {+ LocalAppTaskIntentParser(taskDefinitions: [BuiltInLocalAppTaskDefinitions.weatherLookup])+ }++ private func adapter() -> LocalAppTaskAdapter {+ LocalAppTaskAdapter(definition: BuiltInLocalAppTaskDefinitions.weatherLookup)}private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.mdindex 9a750a90..37c0b2ee 100644--- a/docs/guides/minimal-run-coordinator.md+++ b/docs/guides/minimal-run-coordinator.md@@ -32,7 +32,7 @@ Donkey also supports reflex latency reports and a synthetic replay benchmark. `RDonkey also supports the first fast local-navigation dry-run slice end to end through the dry-run reflex loop. `LocalNavigationMetadataFrameSource` can turn macOS window candidate metadata and optional browser-tab metadata supplied by callers into metadata-only hot-loop frames. `LocalNavigationDryRunPerceptionAdapter` and `LocalNavigationDryRunWorldStateProjector` keep the local-navigation path swappable while preserving the no-remote-model fallback. `LocalNavigationControllerPolicy` can choose traceable dry-run semantic actions such as `focusWindow`, `activateCandidate`, `switchTab`, `wait`, or `observe` from typed state. This slice is metadata-only and side-effect free by default; guarded live-action smoke requires an injected backend, and richer visual inference remains future work.-Donkey also supports the first generic local-app task intent and dry-run adapter boundary. `TaskIntent` can represent a parsed task, target app, normalized entities, parser source, confidence, and confirmation state. `LocalAppTaskDefinition` describes app-task knowledge as data: target app metadata, deterministic trigger terms, required entities and aliases, workflow steps, and verification rules. `LocalAppTaskIntentParser` can parse common local commands without a model call when a task definition is available, and `LocalAppTaskAdapter` can build a target-app local-navigation metadata request, project dry-run workflow steps, emit guarded keyboard command templates for an injected action backend, and verify observed visible text against the requested entity. Weather lookup is only the first benchmark definition for this generic boundary; the implementation is not Weather-specific. Default app launch/focus, default OS typing, Accessibility actions, app-knowledge retrieval, and live result verification remain unsupported.+Donkey also supports the first generic local-app task catalog, intent, and dry-run adapter boundary. `TaskIntent` can represent a parsed task, target app, normalized entities, parser source, confidence, and confirmation state. `LocalAppTaskDefinition` describes app-task knowledge as data: target app metadata, deterministic trigger terms, required entities and aliases, workflow steps, observation strategies, and verification rules. `LocalAppTaskCatalog` resolves commands against known task definitions, checks target-app availability through an injected provider, and exposes built-in benchmark definitions such as Weather lookup as data rather than source-specific adapters. `LocalAppTaskIntentParser` can parse common local commands without a model call when a task definition is available, and `LocalAppTaskAdapter` can build a target-app local-navigation metadata request, project dry-run workflow steps, emit guarded keyboard command templates for an injected action backend, and verify observed visible text against the requested entity. Default app launch/focus, default OS typing, Accessibility actions, live local-model UI understanding, and live result verification remain unsupported.Donkey also supports a guarded live-action smoke boundary for the first local-navigation behavior. `GuardedLiveActionSmokeRunner` requires an end-to-end dry-run result, a latency report with p95 evidence, a non-fallback latest action, explicit input policy allowance, and a passing action-engine focus guard before mapping semantic local-navigation actions to typed action-engine commands. The smoke path records replayable action traces and can execute only through an injected backend; no default OS input backend is enabled.@@ -71,7 +71,7 @@ Donkey supports a runtime-level manual target context capture service that wiresThe 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, deterministic controller, local-navigation dry-run, generic local-app task intent/dry-run adapter, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, OpenAI and Ollama-compatible planner adapters, memory, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run live vision models or OCR over captured pixels, ship a default OS input backend, perform Accessibility actions, 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, deterministic controller, local-navigation dry-run, generic local-app task catalog/intent/dry-run adapter, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, OpenAI and Ollama-compatible planner adapters, memory, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run live vision models or OCR over captured pixels, ship a default OS input backend, perform Accessibility actions, 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@@ -103,6 +103,7 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic- Keep local-navigation decisions typed and side-effect free until the guarded live-action slice. Metadata projectors may use window, browser-tab, and Accessibility facts when available, but controllers should emit semantic actions only.- Keep deterministic task intents separate from planner hints. A supported local command should parse to `TaskIntent` from local app-task definitions without a model call; slow planner output may only help ambiguous parsing, app-knowledge lookup, or recovery after validation.- Keep local-app task adapter output inspectable before live control. Dry-run steps should show the normalized entities, target app identity, observation boundary, guarded command templates, and verification status before any injected backend is allowed to type or click.+- Prefer Accessibility and metadata for app observation. When visual interpretation is needed, route bounded screenshot/crop context to a local model UI-understanding path before introducing OCR-specific plumbing; OCR remains an optional measured adapter, not the default fallback.- Treat planner hints as validated, expiring advice. Controllers may use the latest valid hint, but planner output must never become direct input.- Keep slow planner work beside the reflex loop. Trigger it from compact state, trace, memory, and artifact references; never await model calls from the hot tick before recording the reflex trace.- Keep model selection in `AIModelRegistry` data. Do not scatter provider model ids through planner code.@@ -122,7 +123,7 @@ From `apps/Donkey/`:swift test```-The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, recorded off-the-shelf vision evidence projection, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, deterministic local-app task parsing and alias expansion, local-app navigation request construction, generic dry-run step projection, guarded keyboard command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, OpenAI Responses request shaping and failure handling, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, recorded off-the-shelf vision evidence projection, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, deterministic local-app task parsing and alias expansion, local-app catalog resolution and app availability checks, local-app navigation request construction, generic dry-run step projection, guarded keyboard command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, OpenAI Responses request shaping and failure handling, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.Manual smoke commands:@@ -156,6 +157,7 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi- Task intent and local-app task dry-run contracts live in `apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift`.- Local-navigation metadata projection and dry-run action selection live in `apps/Donkey/Sources/DonkeyRuntime/LocalNavigationController.swift`.- Local-navigation dry-run frame source, loop adapter, world-state projector, and generic controller wrapper live in `apps/Donkey/Sources/DonkeyRuntime/LocalNavigationDryRunLoop.swift`.+- Local-app task catalog resolution and built-in benchmark definitions live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift`.- Deterministic local-app task parsing lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift`.- Generic local-app dry-run adapter and guarded keyboard command templates live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift`.- Slow-planner sidecar triggers, snapshots, validated hint bus, and hint-aware controller wrapper live in `apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift`.diff --git a/plans/20-off-the-shelf-run-loop.md b/plans/20-off-the-shelf-run-loop.mdindex 52417157..db5d3888 100644--- a/plans/20-off-the-shelf-run-loop.md+++ b/plans/20-off-the-shelf-run-loop.md@@ -1,6 +1,6 @@# Off-The-Shelf Run Loop-> Active status: not complete. The current repo supports metadata-only local-navigation dry-run scaffolding, generic local-app task parsing/adaptation, and guarded live-action smoke, but not a live fast-navigation agent for a concrete command such as "show me the weather for SF".+> Active status: not complete. The current repo supports metadata-only local-navigation dry-run scaffolding, generic local-app task catalog parsing/adaptation, target-app availability checks, and guarded live-action smoke, but not a live fast-navigation agent for a concrete command such as "show me the weather for SF".## Goal@@ -8,7 +8,7 @@ Build the first fast local navigation agent from existing system components instThe first product proof is a local Weather lookup navigation benchmark expressed through a generic local-app task system. Donkey should interpret a natural command, resolve the installed app and task definition, use local macOS navigation to open or focus the target app, perform the defined expert-user workflow, verify the app is showing the requested result, and leave the result visible. It should feel faster than manual app navigation or a chat assistant because most work is local and deterministic.-Fast navigation is the focus across apps and games. Use Accessibility, app/window metadata, LaunchServices, keyboard input, screenshot/OCR fallback, open-vocabulary detectors, segmentation, templates, and classical CV as swappable navigation signals. Start with the cheapest local signal that can reliably move the target toward the requested state.+Fast navigation is the focus across apps and games. Use Accessibility, app/window metadata, LaunchServices, keyboard input, bounded screenshot/crop context for local model UI understanding, open-vocabulary detectors, segmentation, templates, OCR when specifically measured as useful, and classical CV as swappable navigation signals. Start with the cheapest local signal that can reliably move the target toward the requested state.## Target Shape@@ -39,7 +39,7 @@ The first version should prove:- command-to-intent parsing is reliable for common tasks- macOS app launch/focus is reliable- Accessibility/window metadata can extract useful app state-- screenshot/OCR fallback is available only when needed+- local visual fallback is available only when Accessibility and metadata are insufficient- state is compact and timestamped- controller rules can act on that state- guarded live input can type/search safely@@ -58,10 +58,11 @@ Use existing, swappable components:- LaunchServices or Workspace app launch/focus- Accessibility snapshots/actions for app UI state and controls- keyboard/mouse input behind guardrails-- template matching or OCR for UI fallback+- local model UI understanding for bounded screenshot/crop fallback+- template matching or OCR only when measured as better for a narrow UI fallback- YOLO-family detector for boxes, UI elements, enemies, objects, and markers- SAM / SAM2 / MobileSAM / FastSAM for masks when boxes are not enough-- OCR for text, labels, and menus when Accessibility is insufficient+- OCR for text, labels, and menus only when a task-specific benchmark shows it is better than local model UI understanding- color/edge/motion heuristics for simple fast signals- deterministic state machines for action decisions- LLM planner only for slow hints and recovery@@ -88,7 +89,7 @@ Preferred inference paths:- CUDA graphs for fixed-shape repeated inference when launch overhead matters- DirectML or WinML as a broad Windows fallback- Core ML / Metal on Apple hardware-- CPU only for tiny templates, OCR snippets, or very small models+- CPU only for tiny templates, OCR snippets, or very small local modelsRuntime rules:@@ -142,7 +143,7 @@ The first local-app task adapter should stay generic and support:- deterministic alias expansion for common city shorthand such as `SF`- dry-run trace output before live input- app launch/focus through a narrow macOS app-control boundary based on resolved target app metadata-- observation through Accessibility first, window metadata second, screenshot/OCR fallback last+- observation through Accessibility first, window metadata second, local model UI understanding over bounded screenshots/crops third, OCR only as an optional measured adapter- guarded text entry into the resolved task control- verification that visible app output matches the normalized requested entity- terminal result states: completed, needs-user-review, failed-safe, timed-out@@ -259,7 +260,7 @@ Natural command-> NSWorkspace/LaunchServices app activation-> Accessibility tree/action when trusted-> guarded keyboard/mouse fallback- -> ScreenCaptureKit/OCR only for missing UI facts+ -> ScreenCaptureKit/local model UI understanding only for missing UI facts```Use Accessibility for window bounds, focus checks, controls, dialogs, and setup flows. Use screenshot perception only when the app does not expose the needed state through Accessibility.@@ -301,9 +302,9 @@ Use segmentation sparingly in the hot loop. It is often better as:- setup/calibration helper- fallback when detection is ambiguous-### OCR And UI Parsing+### Local Model UI Understanding And OCR-Use OCR for:+Use local model UI understanding over bounded screenshot or crop context for:- menus- labels@@ -312,7 +313,9 @@ Use OCR for:- quest text- countdowns-OCR should usually run on cropped regions, not the full frame.+OCR remains a useful narrow adapter, but it should not be the default visual fallback. Prefer local model UI understanding when the question is semantic, layout-dependent, or app-specific. Use OCR when the needed signal is plain text, the crop is small, and measured p95/cost/reliability beats the local model path.++Local model or OCR work should usually run on cropped regions, not the full frame.### Templates And Classical CV@@ -406,7 +409,7 @@ Use LLMs for:- interpreting unfamiliar screens- choosing objectives- explaining failures-- deciding which detector/OCR/template signals matter+- deciding which detector/local-model/OCR/template signals matter- suggesting recovery steps- summarizing memory- reading slow-path screenshots or UI snapshots@@ -450,7 +453,7 @@ Suggested first stack:```textIntent: deterministic parser with local-model fallback for ambiguityApp control: NSWorkspace/LaunchServices activation-Observation: Accessibility snapshot first, screenshot/OCR fallback+Observation: Accessibility snapshot first, local model UI understanding over bounded screenshot/crop fallbackRules: deterministic local-app task state machineInput: guarded keyboard/mouse or Accessibility action backendReasoning: local/online planner only for recovery or ambiguity@@ -467,7 +470,7 @@ Runtime: native Swift coordinator and trace pipeline6. Add app launch/focus action commands and guardrails.7. Add guarded text-entry and submit/select commands.8. Add Accessibility observation for resolved controls and visible result text.-9. Add screenshot/OCR fallback only where Accessibility is insufficient.+9. Add local model UI-understanding fallback only where Accessibility and metadata are insufficient; keep OCR optional and measured.10. Add result verification for normalized requested entities.11. Add command-to-result latency report and manual baseline comparison.12. Add optional slow planner recovery only after deterministic execution works.@@ -483,7 +486,7 @@ Runtime: native Swift coordinator and trace pipeline- p95 local navigation/action latency stays under the target budget.- command-to-result latency is measured against a manual baseline.- LLM output is validated before it changes controller configuration.-- Segmentation and OCR are cropped and measured before live use.+- Local model UI understanding, segmentation, and OCR are cropped and measured before live use.- The runtime coordinator can start, pause, abort, timeout, and complete a run.- Abort releases held input and publishes a terminal lifecycle event.- Session queue drops stale live-control work instead of building backlog.@@ -504,20 +507,20 @@ The runtime foundation now supports a product-shaped local-navigation slice of t- p50/p95/p99 latency reports across capture, preprocess, model, perception, state update, controller decision, action projection, and input stages- action-engine permission, focus, rate, hold-duration, release, and backend-execution guardrails- guarded live-action smoke through an injected backend only after dry-run latency evidence, explicit input policy allowance, and focus guard success-- generic local-app task intent contracts, data-driven task definitions, deterministic parsing, dry-run workflow-step projection, guarded keyboard command templates, and visible-text verification+- generic local-app task catalog, intent contracts, built-in benchmark definition, deterministic parsing, dry-run workflow-step projection, guarded keyboard command templates, and visible-text verification- optional slow-planner sidecar that publishes only validated hints without blocking reflex latency-This is still not the full off-the-shelf vision stack and must not be treated as completion. It can replay and trace compact local vision evidence, but it does not ship live local detector/OCR/segmentation/model adapters over captured pixels, continuous streaming capture, a default OS input backend, high-volume persisted replay traces, or target-specific visual calibration.+This is still not the full off-the-shelf vision stack and must not be treated as completion. It can replay and trace compact local vision evidence, but it does not ship live local detector/local-model/OCR/segmentation adapters over captured pixels, continuous streaming capture, a default OS input backend, high-volume persisted replay traces, or target-specific visual calibration.## Required Before This Plan Is Done-- Add an app-knowledge layer and measured first local-app task benchmark for the concrete command "show me the weather for SF".+- Add measured guarded-live execution for the first local-app task benchmark command "show me the weather for SF".- Prove fast local navigation from parsed intent, local app observation, deterministic controller state, and guarded live input, not remote planning.- Add a default narrow macOS app-control backend for launch/focus/type/select/verify with focus guard and emergency release.-- Add result verification through Accessibility or screenshot/OCR fallback.+- Add result verification through Accessibility or local model UI-understanding fallback, with OCR only if a narrow benchmark justifies it.- Add continuous streaming capture once queue-depth, stale-result, and trace sinks are ready for longer sessions.- Add durable high-volume replay trace persistence and target-specific benchmark baselines.-- Keep segmentation/OCR optional and introduce them only with cropped, measured, target-specific evidence.+- Keep local model UI understanding, segmentation, and OCR optional in the live path until each has cropped, measured, target-specific evidence.## Where To Lookdiff --git a/plans/master-plan.md b/plans/master-plan.mdindex 6ce8b179..3592a19e 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -56,7 +56,7 @@ The normal Weather benchmark path should work without a remote model call. A tin## Supported Boundary- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, in-memory reflex trace retention, and stage-split latency reports are supported.-- Fast navigation hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, recorded off-the-shelf detector/template/OCR/segmentation evidence projection, 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, deterministic parsing with entity alias expansion, generic dry-run task adaptation, local-navigation request construction, step projection, guarded keyboard command templates, and visible-text verification are supported. Weather lookup is now only the first benchmark definition for this generic boundary. This is not yet a live fast-navigation agent: there is no default app launch/focus/type backend, no Accessibility action execution, no app-knowledge retrieval layer, and no verified live command-to-result loop.+- 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, 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, deterministic parsing with entity alias expansion, catalog command resolution, target-app availability checks, generic dry-run task adaptation, local-navigation request construction, step projection, guarded keyboard command templates, visible-text verification, and built-in Weather benchmark data are supported. This is not yet a live fast-navigation agent: there is no default app launch/focus/type backend, no Accessibility action execution, no live local-model UI-understanding fallback, and no verified live command-to-result loop.- Safety boundary: action-engine command contracts, permission/focus/rate/hold/release guardrails, guarded live-action smoke with an injected backend, and replayable command traces are supported before any default OS input or Accessibility-action backend exists.- Slow AI boundary: structured planner hints, validation/expiry/latest-valid selection, loop-adjacent slow-planner trigger/snapshot sidecar, model registry/router, OpenAI Responses and Ollama-compatible planner adapters, provider-backed local/online planner fallback, source-linked memory, and replay/eval scaffolding are supported as optional sidecar pieces. This is not yet the complete AI harness because semantic retrieval, redaction, aggregate model observability, and provider-decoded memory write proposals remain active.- Source of truth: detailed supported behavior lives in `docs/guides/minimal-run-coordinator.md`; active unfinished work lives in this plan and its primary/supporting plans.@@ -81,18 +81,18 @@ Recent commits completed these pieces:- `0e21088`: OpenAI Responses adapter, planner hint contracts, model registry/router scaffolding.- `9bebfbb`: slow-planner sidecar trigger/snapshot/hint bus and guarded live-action smoke boundary.- recent slice: Ollama-compatible local planner adapter, provider-backed local/online slow planner fallback, and explicit slow-planner completion tests.-- current slice: generic local-app task intent/parser and dry-run adapter boundary, with Weather lookup represented as catalog-style benchmark data.+- current slice: generic local-app task catalog, intent/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 intent/parser and dry-run adapter boundary. It does not yet include default app launch/focus/type execution, Accessibility action execution, an app-knowledge/catalog retrieval layer for installed apps, live result verification, local detector/OCR/segmentation/model inference adapters, semantic memory retrieval, remote-input redaction hooks, aggregate model observability, or provider-decoded memory write proposals.+The code now includes the first generic local-app task catalog, deterministic intent/parser, app availability check, and dry-run adapter boundary. It does not yet include default app launch/focus/type execution, Accessibility action execution, live local-model UI understanding over bounded screenshots/crops, live result verification, semantic memory retrieval, remote-input redaction hooks, aggregate model observability, or provider-decoded memory write proposals.## What Should Be Done Next-1. Add the generic app-knowledge layer that can enumerate installed apps, resolve a task definition for a user command, and represent app expertise as data: target app identity, task triggers, entities, aliases, workflow steps, observation strategy, allowed controls, and verification rules.-2. Extend the generic local-app task adapter from dry-run projection to guarded-live orchestration: launch/focus the target app, observe app state, find the needed control, enter normalized entities, submit/select, and verify the requested result.-3. Add the default local action backend needed for this narrow first benchmark: app launch/activation plus guarded keyboard typing/clicking or Accessibility actions, with emergency release and focus checks.+1. Extend the generic local-app task adapter from dry-run projection to guarded-live orchestration: launch/focus the target app, observe app state, find the needed control, enter normalized entities, submit/select, and verify the requested result.+2. Add the default local action backend needed for this narrow first benchmark: app launch/activation plus guarded keyboard typing/clicking or Accessibility actions, with emergency release and focus checks.+3. Add a local model UI-understanding fallback for bounded screenshot/crop context when Accessibility and metadata are insufficient. Prefer this before OCR-specific extraction; OCR can remain a measured optional adapter.4. Add benchmark/reporting evidence for command-to-result latency, local navigation/action latency, verification confidence, and comparison against manual/chat-style workflows.-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, or planner hints, never direct input.+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, or planner hints, never direct input.## Completion Gates