Skip to content

Open source CapCut alternative.

TypeScript

Generalize local app task parsing and adapter

David Le4da1a5b70975
diff --git a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift
new file mode 100644
index 00000000..f655e0d9
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift
@@ -0,0 +1,231 @@
+import Foundation
+
+public enum TaskIntentParserSource: String, Codable, Equatable, Sendable {
+ case deterministic
+ case localModel = "local_model"
+ case onlineModel = "online_model"
+}
+
+public struct LocalAppTarget: Codable, Equatable, Sendable {
+ public var appName: String
+ public var bundleIdentifier: String?
+ public var titleContains: String?
+ public var metadata: [String: String]
+
+ public init(
+ appName: String,
+ bundleIdentifier: String? = nil,
+ titleContains: String? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.appName = appName
+ self.bundleIdentifier = bundleIdentifier
+ self.titleContains = titleContains
+ self.metadata = metadata
+ }
+}
+
+public struct TaskIntent: Codable, Equatable, Sendable {
+ public var intentID: String
+ public var taskType: String
+ public var targetApp: LocalAppTarget
+ public var entities: [String: String]
+ public var normalizedEntities: [String: String]
+ public var confidence: Double
+ public var parserSource: TaskIntentParserSource
+ public var needsConfirmation: Bool
+ public var sourceModelCallID: String?
+ public var metadata: [String: String]
+
+ public init(
+ intentID: String,
+ taskType: String,
+ targetApp: LocalAppTarget,
+ entities: [String: String] = [:],
+ normalizedEntities: [String: String] = [:],
+ confidence: Double,
+ parserSource: TaskIntentParserSource,
+ needsConfirmation: Bool = false,
+ sourceModelCallID: String? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.intentID = intentID
+ self.taskType = taskType
+ self.targetApp = targetApp
+ self.entities = entities
+ self.normalizedEntities = normalizedEntities
+ self.confidence = min(max(confidence, 0), 1)
+ self.parserSource = parserSource
+ self.needsConfirmation = needsConfirmation
+ self.sourceModelCallID = sourceModelCallID
+ self.metadata = metadata
+ }
+}
+
+public struct LocalAppTaskEntityRule: Codable, Equatable, Sendable {
+ public var name: String
+ public var markers: [String]
+ public var aliases: [String: String]
+ public var required: Bool
+ public var metadata: [String: String]
+
+ public init(
+ name: String,
+ markers: [String] = [],
+ aliases: [String: String] = [:],
+ required: Bool = true,
+ metadata: [String: String] = [:]
+ ) {
+ self.name = name
+ self.markers = markers
+ self.aliases = aliases
+ self.required = required
+ self.metadata = metadata
+ }
+}
+
+public enum LocalAppTaskStepRole: String, Codable, Equatable, Sendable {
+ case parseIntent
+ case launchOrFocusApp
+ case observeApp
+ case focusControl
+ case enterText
+ case submit
+ case verifyResult
+ case custom
+}
+
+public struct LocalAppTaskWorkflowStepDefinition: Codable, Equatable, Sendable {
+ public var id: String
+ public var role: LocalAppTaskStepRole
+ public var summary: String
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ role: LocalAppTaskStepRole,
+ summary: String,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.role = role
+ self.summary = summary
+ self.metadata = metadata
+ }
+}
+
+public struct LocalAppTaskDefinition: Codable, Equatable, Sendable {
+ public var taskType: String
+ public var targetApp: LocalAppTarget
+ public var triggerTerms: [String]
+ public var entityRules: [LocalAppTaskEntityRule]
+ public var workflowSteps: [LocalAppTaskWorkflowStepDefinition]
+ public var verificationEntityName: String?
+ public var metadata: [String: String]
+
+ public init(
+ taskType: String,
+ targetApp: LocalAppTarget,
+ triggerTerms: [String],
+ entityRules: [LocalAppTaskEntityRule] = [],
+ workflowSteps: [LocalAppTaskWorkflowStepDefinition] = [],
+ verificationEntityName: String? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.taskType = taskType
+ self.targetApp = targetApp
+ self.triggerTerms = triggerTerms
+ self.entityRules = entityRules
+ self.workflowSteps = workflowSteps
+ self.verificationEntityName = verificationEntityName
+ self.metadata = metadata
+ }
+}
+
+public enum LocalAppTaskStepStatus: String, Codable, Equatable, Sendable {
+ case projected
+ case blocked
+ case verified
+}
+
+public enum LocalAppTaskTerminalState: String, Codable, Equatable, Sendable {
+ case completed
+ case needsUserReview = "needs-user-review"
+ case failedSafe = "failed-safe"
+ case timedOut = "timed-out"
+}
+
+public struct LocalAppTaskObservation: Codable, Equatable, Sendable {
+ public var appIsRunning: Bool
+ public var appIsFocused: Bool
+ public var availableControls: [String: Bool]
+ public var visibleText: [String: String]
+ public var confidence: Double
+ public var metadata: [String: String]
+
+ public init(
+ appIsRunning: Bool = false,
+ appIsFocused: Bool = false,
+ availableControls: [String: Bool] = [:],
+ visibleText: [String: String] = [:],
+ confidence: Double = 0,
+ metadata: [String: String] = [:]
+ ) {
+ self.appIsRunning = appIsRunning
+ self.appIsFocused = appIsFocused
+ self.availableControls = availableControls
+ self.visibleText = visibleText
+ self.confidence = min(max(confidence, 0), 1)
+ self.metadata = metadata
+ }
+}
+
+public struct LocalAppTaskDryRunStep: Codable, Equatable, Sendable {
+ public var id: String
+ public var role: LocalAppTaskStepRole
+ public var status: LocalAppTaskStepStatus
+ public var summary: String
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ role: LocalAppTaskStepRole,
+ status: LocalAppTaskStepStatus,
+ summary: String,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.role = role
+ self.status = status
+ self.summary = summary
+ self.metadata = metadata
+ }
+}
+
+public struct LocalAppTaskDryRunPlan: Codable, Equatable, Sendable {
+ public var intent: TaskIntent
+ public var targetApp: LocalAppTarget
+ public var steps: [LocalAppTaskDryRunStep]
+ public var terminalState: LocalAppTaskTerminalState
+ public var canAttemptGuardedLive: Bool
+ public var verificationConfidence: Double
+ public var metadata: [String: String]
+
+ public init(
+ intent: TaskIntent,
+ targetApp: LocalAppTarget,
+ steps: [LocalAppTaskDryRunStep],
+ terminalState: LocalAppTaskTerminalState,
+ canAttemptGuardedLive: Bool,
+ verificationConfidence: Double,
+ metadata: [String: String] = [:]
+ ) {
+ self.intent = intent
+ self.targetApp = targetApp
+ self.steps = steps
+ self.terminalState = terminalState
+ self.canAttemptGuardedLive = canAttemptGuardedLive
+ self.verificationConfidence = min(max(verificationConfidence, 0), 1)
+ self.metadata = metadata
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift
new file mode 100644
index 00000000..75d596aa
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift
@@ -0,0 +1,365 @@
+import DonkeyContracts
+import Foundation
+
+public struct LocalAppTaskAdapter: Sendable {
+ public var definition: LocalAppTaskDefinition
+
+ public init(definition: LocalAppTaskDefinition) {
+ self.definition = definition
+ }
+
+ public func localNavigationFrameRequest(
+ for intent: TaskIntent,
+ traceID: String,
+ maxFrameCount: Int = 1
+ ) -> LocalNavigationMetadataFrameRequest? {
+ guard supports(intent) else { return nil }
+
+ return LocalNavigationMetadataFrameRequest(
+ targetID: targetID,
+ traceID: traceID,
+ maxFrameCount: maxFrameCount,
+ requestedBundleIdentifier: definition.targetApp.bundleIdentifier,
+ requestedTitleContains: definition.targetApp.titleContains
+ )
+ }
+
+ public func dryRunPlan(
+ for intent: TaskIntent,
+ observation: LocalAppTaskObservation? = nil
+ ) -> LocalAppTaskDryRunPlan {
+ guard supports(intent), intent.needsConfirmation == false else {
+ return LocalAppTaskDryRunPlan(
+ intent: intent,
+ targetApp: definition.targetApp,
+ steps: [
+ LocalAppTaskDryRunStep(
+ id: "parse-intent",
+ role: .parseIntent,
+ status: .blocked,
+ summary: "Local app task intent is unsupported or incomplete",
+ metadata: ["reason": "unsupportedOrIncompleteIntent"]
+ )
+ ],
+ terminalState: .failedSafe,
+ canAttemptGuardedLive: false,
+ verificationConfidence: 0,
+ metadata: planMetadata
+ )
+ }
+
+ let verification = verificationStatus(for: intent, observation: observation)
+ let steps = resolvedWorkflowSteps(
+ intent: intent,
+ observation: observation,
+ verification: verification
+ )
+
+ return LocalAppTaskDryRunPlan(
+ intent: intent,
+ targetApp: definition.targetApp,
+ steps: steps,
+ terminalState: verification.terminalState,
+ canAttemptGuardedLive: verification.terminalState != .failedSafe,
+ verificationConfidence: verification.confidence,
+ metadata: planMetadata
+ )
+ }
+
+ public func guardedKeyboardCommandTemplates(
+ for intent: TaskIntent,
+ issuedAt: RunTraceTimestamp
+ ) -> [ActionEngineCommand] {
+ guard supports(intent), intent.needsConfirmation == false else { return [] }
+
+ return definition.workflowSteps.compactMap { step in
+ switch step.role {
+ case .focusControl:
+ guard let key = step.metadata["key"] else { return nil }
+ return command(
+ idSuffix: step.id,
+ intent: intent,
+ issuedAt: issuedAt,
+ key: key,
+ role: step.role,
+ metadata: step.metadata
+ )
+ case .enterText:
+ let entityName = step.metadata["entityName"] ?? definition.verificationEntityName
+ guard let entityName,
+ let text = intent.normalizedEntities[entityName]
+ else {
+ return nil
+ }
+ return command(
+ idSuffix: step.id,
+ intent: intent,
+ issuedAt: issuedAt,
+ key: text,
+ role: step.role,
+ metadata: step.metadata.merging([
+ "inputRole": "textEntry",
+ "text": text
+ ]) { current, _ in current }
+ )
+ case .submit:
+ guard let key = step.metadata["key"] else { return nil }
+ return command(
+ idSuffix: step.id,
+ intent: intent,
+ issuedAt: issuedAt,
+ key: key,
+ role: step.role,
+ metadata: step.metadata
+ )
+ case .parseIntent, .launchOrFocusApp, .observeApp, .verifyResult, .custom:
+ return nil
+ }
+ }
+ }
+
+ public func verifiesVisibleText(
+ _ visibleText: String?,
+ matches intent: TaskIntent
+ ) -> Bool {
+ guard let entityName = definition.verificationEntityName,
+ let expected = intent.normalizedEntities[entityName],
+ let visibleText
+ else {
+ return false
+ }
+
+ return Self.normalizedText(visibleText).contains(Self.normalizedText(expected))
+ }
+
+ private var targetID: String {
+ "local-app-task-\(slug(definition.taskType))"
+ }
+
+ private var planMetadata: [String: String] {
+ [
+ "adapter": "local-app-task-adapter-v1",
+ "taskType": definition.taskType,
+ "appName": definition.targetApp.appName,
+ "bundleIdentifier": definition.targetApp.bundleIdentifier ?? "",
+ "guardedLiveRequiresInputPolicy": "true",
+ "defaultOSInputBackendAvailable": "false"
+ ].merging(definition.metadata) { current, _ in current }
+ }
+
+ private func resolvedWorkflowSteps(
+ intent: TaskIntent,
+ observation: LocalAppTaskObservation?,
+ verification: (
+ status: LocalAppTaskStepStatus,
+ terminalState: LocalAppTaskTerminalState,
+ confidence: Double,
+ summary: String,
+ metadata: [String: String]
+ )
+ ) -> [LocalAppTaskDryRunStep] {
+ if definition.workflowSteps.isEmpty {
+ return [
+ LocalAppTaskDryRunStep(
+ id: "parse-intent",
+ role: .parseIntent,
+ status: .verified,
+ summary: "Parsed local app task intent",
+ metadata: ["taskType": intent.taskType]
+ )
+ ]
+ }
+
+ return definition.workflowSteps.map { step in
+ LocalAppTaskDryRunStep(
+ id: step.id,
+ role: step.role,
+ status: status(for: step, observation: observation, verificationStatus: verification.status),
+ summary: summary(for: step, observation: observation, verificationSummary: verification.summary),
+ metadata: metadata(for: step, intent: intent, verificationMetadata: verification.metadata)
+ )
+ }
+ }
+
+ private func status(
+ for step: LocalAppTaskWorkflowStepDefinition,
+ observation: LocalAppTaskObservation?,
+ verificationStatus: LocalAppTaskStepStatus
+ ) -> LocalAppTaskStepStatus {
+ switch step.role {
+ case .parseIntent:
+ return .verified
+ case .launchOrFocusApp:
+ return observation?.appIsFocused == true ? .verified : .projected
+ case .observeApp:
+ return observation == nil ? .projected : .verified
+ case .focusControl:
+ if let controlID = step.metadata["controlID"],
+ observation?.availableControls[controlID] == true {
+ return .verified
+ }
+ return .projected
+ case .enterText, .submit, .custom:
+ return .projected
+ case .verifyResult:
+ return verificationStatus
+ }
+ }
+
+ private func summary(
+ for step: LocalAppTaskWorkflowStepDefinition,
+ observation: LocalAppTaskObservation?,
+ verificationSummary: String
+ ) -> String {
+ if step.role == .verifyResult {
+ return verificationSummary
+ }
+
+ if step.role == .launchOrFocusApp, observation?.appIsFocused == true {
+ return "\(definition.targetApp.appName) is already focused"
+ }
+
+ return step.summary
+ }
+
+ private func metadata(
+ for step: LocalAppTaskWorkflowStepDefinition,
+ intent: TaskIntent,
+ verificationMetadata: [String: String]
+ ) -> [String: String] {
+ var metadata = step.metadata.merging([
+ "taskIntentID": intent.intentID,
+ "taskType": intent.taskType
+ ]) { current, _ in current }
+
+ for (name, value) in intent.normalizedEntities {
+ metadata["normalizedEntity.\(name)"] = value
+ }
+
+ if step.role == .verifyResult {
+ metadata.merge(verificationMetadata) { current, _ in current }
+ }
+
+ return metadata
+ }
+
+ private func verificationStatus(
+ for intent: TaskIntent,
+ observation: LocalAppTaskObservation?
+ ) -> (
+ status: LocalAppTaskStepStatus,
+ terminalState: LocalAppTaskTerminalState,
+ confidence: Double,
+ summary: String,
+ metadata: [String: String]
+ ) {
+ guard let entityName = definition.verificationEntityName,
+ let expected = intent.normalizedEntities[entityName]
+ else {
+ return (
+ .blocked,
+ .needsUserReview,
+ 0,
+ "No verification entity is configured for this task",
+ ["reason": "missingVerificationEntity"]
+ )
+ }
+
+ guard let observation else {
+ return (
+ .blocked,
+ .needsUserReview,
+ 0,
+ "Visible app result has not been observed yet",
+ [
+ "reason": "missingObservation",
+ "expectedEntityName": entityName,
+ "expectedEntityValue": expected
+ ]
+ )
+ }
+
+ let visibleTextKey = definition.metadata["verificationTextKey"] ?? entityName
+ guard let visibleText = observation.visibleText[visibleTextKey] else {
+ return (
+ .blocked,
+ .needsUserReview,
+ observation.confidence,
+ "Verification text is not available yet",
+ [
+ "reason": "missingVisibleText",
+ "visibleTextKey": visibleTextKey,
+ "expectedEntityValue": expected
+ ]
+ )
+ }
+
+ if verifiesVisibleText(visibleText, matches: intent) {
+ return (
+ .verified,
+ .completed,
+ max(observation.confidence, 0.8),
+ "Visible app result matches the requested entity",
+ [
+ "visibleText": visibleText,
+ "expectedEntityName": entityName,
+ "expectedEntityValue": expected
+ ]
+ )
+ }
+
+ return (
+ .blocked,
+ .needsUserReview,
+ observation.confidence,
+ "Visible app result does not match the requested entity",
+ [
+ "reason": "resultMismatch",
+ "visibleText": visibleText,
+ "expectedEntityName": entityName,
+ "expectedEntityValue": expected
+ ]
+ )
+ }
+
+ private func supports(_ intent: TaskIntent) -> Bool {
+ intent.taskType == definition.taskType
+ && intent.targetApp.appName == definition.targetApp.appName
+ && intent.targetApp.bundleIdentifier == definition.targetApp.bundleIdentifier
+ }
+
+ private func command(
+ idSuffix: String,
+ intent: TaskIntent,
+ issuedAt: RunTraceTimestamp,
+ key: String,
+ role: LocalAppTaskStepRole,
+ metadata: [String: String]
+ ) -> ActionEngineCommand {
+ ActionEngineCommand(
+ id: "\(intent.intentID)-\(idSuffix)",
+ traceID: intent.metadata["traceID"] ?? intent.intentID,
+ targetID: targetID,
+ kind: .key,
+ issuedAt: issuedAt,
+ key: key,
+ metadata: metadata.merging([
+ "taskIntentID": intent.intentID,
+ "taskType": intent.taskType,
+ "targetApp": definition.targetApp.appName,
+ "bundleIdentifier": definition.targetApp.bundleIdentifier ?? "",
+ "workflowStepRole": role.rawValue
+ ]) { current, _ in current }
+ )
+ }
+
+ private func slug(_ value: String) -> String {
+ Self.normalizedText(value)
+ .split(separator: " ")
+ .joined(separator: "-")
+ }
+
+ private static func normalizedText(_ value: String) -> String {
+ LocalAppTaskIntentParser.normalizedPhrase(value)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift
new file mode 100644
index 00000000..1c8986f7
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift
@@ -0,0 +1,179 @@
+import DonkeyContracts
+import Foundation
+
+public struct LocalAppTaskIntentParser: Sendable {
+ public var taskDefinitions: [LocalAppTaskDefinition]
+
+ public init(taskDefinitions: [LocalAppTaskDefinition]) {
+ self.taskDefinitions = taskDefinitions
+ }
+
+ public func parse(_ command: String) -> TaskIntent? {
+ let normalizedCommand = Self.normalizedPhrase(command)
+ guard let definition = taskDefinitions.first(where: { matches($0, normalizedCommand: normalizedCommand) }) else {
+ return nil
+ }
+
+ let parsedEntities = parseEntities(from: command, using: definition)
+ if let missingEntity = definition.entityRules.first(where: { rule in
+ rule.required && parsedEntities.normalized[rule.name] == nil
+ }) {
+ return TaskIntent(
+ intentID: "\(definition.taskType)-needs-\(missingEntity.name)",
+ taskType: definition.taskType,
+ targetApp: definition.targetApp,
+ confidence: 0.45,
+ parserSource: .deterministic,
+ needsConfirmation: true,
+ metadata: [
+ "parser": "local-app-task-deterministic-v1",
+ "missingEntity": missingEntity.name
+ ].merging(definition.metadata) { current, _ in current }
+ )
+ }
+
+ let primaryEntity = definition.verificationEntityName
+ .flatMap { parsedEntities.normalized[$0] }
+ ?? parsedEntities.normalized.values.sorted().first
+ ?? definition.taskType
+
+ return TaskIntent(
+ intentID: "\(definition.taskType)-\(slug(primaryEntity))",
+ taskType: definition.taskType,
+ targetApp: definition.targetApp,
+ entities: parsedEntities.raw,
+ normalizedEntities: parsedEntities.normalized,
+ confidence: parsedEntities.usedAlias ? 0.96 : 0.88,
+ parserSource: .deterministic,
+ needsConfirmation: false,
+ metadata: [
+ "parser": "local-app-task-deterministic-v1",
+ "entityAliasExpanded": String(parsedEntities.usedAlias),
+ "rawCommandNormalized": normalizedCommand
+ ].merging(definition.metadata) { current, _ in current }
+ )
+ }
+
+ private func matches(
+ _ definition: LocalAppTaskDefinition,
+ normalizedCommand: String
+ ) -> Bool {
+ let paddedCommand = " \(normalizedCommand) "
+ return definition.triggerTerms
+ .map(Self.normalizedPhrase)
+ .contains { paddedCommand.contains(" \($0) ") }
+ }
+
+ private func parseEntities(
+ from command: String,
+ using definition: LocalAppTaskDefinition
+ ) -> (raw: [String: String], normalized: [String: String], usedAlias: Bool) {
+ var raw: [String: String] = [:]
+ var normalized: [String: String] = [:]
+ var usedAlias = false
+
+ for rule in definition.entityRules {
+ guard let candidate = entityCandidate(from: command, rule: rule) else { continue }
+ raw[rule.name] = candidate.raw
+ normalized[rule.name] = candidate.normalized
+ usedAlias = usedAlias || candidate.usedAlias
+ }
+
+ return (raw, normalized, usedAlias)
+ }
+
+ private func entityCandidate(
+ from command: String,
+ rule: LocalAppTaskEntityRule
+ ) -> (raw: String, normalized: String, usedAlias: Bool)? {
+ let aliases = rule.aliases.reduce(into: [:]) { result, item in
+ result[Self.normalizedPhrase(item.key)] = item.value
+ }
+ let normalizedCommand = Self.normalizedPhrase(command)
+ let paddedCommand = " \(normalizedCommand) "
+
+ if let alias = aliases.keys.sorted(by: { $0.count > $1.count }).first(where: { paddedCommand.contains(" \($0) ") }),
+ let normalized = aliases[alias] {
+ return (alias, normalized, true)
+ }
+
+ for marker in rule.markers.map(Self.normalizedPhrase) {
+ let pattern = #"\b\#(NSRegularExpression.escapedPattern(for: marker))\b\s+(.+)$"#
+ if let match = firstCapture(in: command, pattern: pattern) {
+ let cleaned = cleanEntityCandidate(match)
+ guard !cleaned.isEmpty else { continue }
+ let normalized = aliases[Self.normalizedPhrase(cleaned)] ?? titleCased(cleaned)
+ return (cleaned, normalized, normalized != titleCased(cleaned))
+ }
+ }
+
+ return nil
+ }
+
+ private func firstCapture(in command: String, pattern: String) -> String? {
+ guard let regex = try? NSRegularExpression(
+ pattern: pattern,
+ options: [.caseInsensitive]
+ ) else {
+ return nil
+ }
+
+ let range = NSRange(command.startIndex..<command.endIndex, in: command)
+ guard let match = regex.firstMatch(in: command, options: [], range: range),
+ match.numberOfRanges > 1,
+ let captureRange = Range(match.range(at: 1), in: command)
+ else {
+ return nil
+ }
+
+ return String(command[captureRange])
+ }
+
+ private func cleanEntityCandidate(_ candidate: String) -> String {
+ var cleaned = candidate.trimmingCharacters(in: .whitespacesAndNewlines)
+ cleaned = cleaned.trimmingCharacters(in: CharacterSet(charactersIn: ".,!?"))
+
+ let suffixPattern = #"\s+(today|tomorrow|tonight|please|pls)$"#
+ while let regex = try? NSRegularExpression(pattern: suffixPattern, options: [.caseInsensitive]) {
+ let range = NSRange(cleaned.startIndex..<cleaned.endIndex, in: cleaned)
+ guard let match = regex.firstMatch(in: cleaned, options: [], range: range),
+ let swiftRange = Range(match.range, in: cleaned)
+ else {
+ break
+ }
+ cleaned.removeSubrange(swiftRange)
+ cleaned = cleaned.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ return cleaned
+ }
+
+ private func titleCased(_ value: String) -> String {
+ Self.normalizedPhrase(value)
+ .split(separator: " ")
+ .map { word in
+ word.prefix(1).uppercased() + word.dropFirst()
+ }
+ .joined(separator: " ")
+ }
+
+ private func slug(_ value: String) -> String {
+ Self.normalizedPhrase(value)
+ .split(separator: " ")
+ .joined(separator: "-")
+ }
+
+ static func normalizedPhrase(_ value: String) -> String {
+ let folded = value.folding(
+ options: [.diacriticInsensitive, .caseInsensitive],
+ locale: Locale(identifier: "en_US_POSIX")
+ )
+ let scalars = folded.unicodeScalars.map { scalar -> Character in
+ CharacterSet.alphanumerics.contains(scalar) ? Character(scalar) : " "
+ }
+ return String(scalars)
+ .split(separator: " ")
+ .joined(separator: " ")
+ .lowercased()
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
new file mode 100644
index 00000000..454c5b3c
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
@@ -0,0 +1,194 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct LocalAppTaskTests {
+ @Test
+ func deterministicParserBuildsGenericTaskIntentWithAliasExpansion() throws {
+ let intent = try #require(parser().parse("show me the weather for SF"))
+
+ #expect(intent.taskType == "weather_lookup")
+ #expect(intent.targetApp.appName == "Weather")
+ #expect(intent.targetApp.bundleIdentifier == "com.apple.weather")
+ #expect(intent.entities["city"] == "sf")
+ #expect(intent.normalizedEntities["city"] == "San Francisco")
+ #expect(intent.confidence == 0.96)
+ #expect(intent.parserSource == .deterministic)
+ #expect(intent.needsConfirmation == false)
+ #expect(intent.metadata["catalogEntry"] == "fixture-weather-lookup")
+ #expect(intent.metadata["entityAliasExpanded"] == "true")
+ }
+
+ @Test
+ func deterministicParserRequestsConfirmationForMissingRequiredEntity() throws {
+ let intent = try #require(parser().parse("show me the weather"))
+
+ #expect(intent.taskType == "weather_lookup")
+ #expect(intent.intentID == "weather_lookup-needs-city")
+ #expect(intent.needsConfirmation == true)
+ #expect(intent.metadata["missingEntity"] == "city")
+ }
+
+ @Test
+ func deterministicParserIgnoresUnsupportedCommands() {
+ #expect(parser().parse("open my calendar") == nil)
+ }
+
+ @Test
+ func genericAdapterBuildsLocalNavigationRequestForTargetApp() throws {
+ let intent = try #require(parser().parse("weather in San Francisco"))
+ let request = try #require(adapter().localNavigationFrameRequest(
+ for: intent,
+ traceID: "trace-local-app-task",
+ maxFrameCount: 2
+ ))
+
+ #expect(request.targetID == "local-app-task-weather-lookup")
+ #expect(request.traceID == "trace-local-app-task")
+ #expect(request.maxFrameCount == 2)
+ #expect(request.requestedBundleIdentifier == "com.apple.weather")
+ #expect(request.requestedTitleContains == "Weather")
+ }
+
+ @Test
+ func genericAdapterProjectsDryRunStepsAndGuardedKeyboardTemplates() throws {
+ let intent = try #require(parser().parse("show me the weather for SF"))
+ let localAdapter = adapter()
+
+ let plan = localAdapter.dryRunPlan(for: intent)
+ #expect(plan.terminalState == .needsUserReview)
+ #expect(plan.canAttemptGuardedLive == true)
+ #expect(plan.verificationConfidence == 0)
+ #expect(plan.steps.map(\.role) == [
+ .parseIntent,
+ .launchOrFocusApp,
+ .observeApp,
+ .focusControl,
+ .enterText,
+ .submit,
+ .verifyResult
+ ])
+ #expect(plan.steps.last?.status == .blocked)
+ #expect(plan.metadata["defaultOSInputBackendAvailable"] == "false")
+
+ let commands = localAdapter.guardedKeyboardCommandTemplates(
+ for: intent,
+ issuedAt: timestamp(100)
+ )
+ #expect(commands.map(\.kind) == [.key, .key, .key])
+ #expect(commands.map(\.key) == ["Command+F", "San Francisco", "Return"])
+ #expect(commands[1].metadata["workflowStepRole"] == "enterText")
+ #expect(commands[1].metadata["text"] == "San Francisco")
+ #expect(commands[1].metadata["bundleIdentifier"] == "com.apple.weather")
+ }
+
+ @Test
+ func genericAdapterVerifiesObservedVisibleText() throws {
+ let intent = try #require(parser().parse("weather for SF"))
+ let localAdapter = adapter()
+ let plan = localAdapter.dryRunPlan(
+ for: intent,
+ observation: LocalAppTaskObservation(
+ appIsRunning: true,
+ appIsFocused: true,
+ availableControls: ["search": true],
+ visibleText: ["city": "San Francisco, CA"],
+ confidence: 0.91
+ )
+ )
+
+ #expect(plan.terminalState == .completed)
+ #expect(plan.verificationConfidence == 0.91)
+ #expect(plan.steps.first(where: { $0.role == .verifyResult })?.status == .verified)
+ #expect(localAdapter.verifiesVisibleText("San Francisco, CA", matches: intent) == true)
+ #expect(localAdapter.verifiesVisibleText("New York", matches: intent) == false)
+ }
+
+ private func parser() -> LocalAppTaskIntentParser {
+ LocalAppTaskIntentParser(taskDefinitions: [fixtureWeatherLookupDefinition()])
+ }
+
+ private func adapter() -> LocalAppTaskAdapter {
+ LocalAppTaskAdapter(definition: fixtureWeatherLookupDefinition())
+ }
+
+ 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"
+ ]
+ )
+ }
+
+ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
+ monotonicUptimeNanoseconds: milliseconds * 1_000_000
+ )
+ }
+}
diff --git a/docs/README.md b/docs/README.md
index 8c621ca8..639978f9 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -4,7 +4,7 @@ This folder is the product and engineering source of truth for capabilities that
Plans describe what we might build. Guides describe what Donkey currently supports and how to maintain it.
-There is an active milestone plan in `plans/master-plan.md`. It tracks the unfinished work needed before the fast local navigation and AI-harness roadmap can be considered complete, especially the first Weather lookup benchmark from natural command to local navigation, guarded input, result verification, latency reporting, and optional slow planner recovery.
+There is an active milestone plan in `plans/master-plan.md`. It tracks the unfinished work needed before the fast local navigation and AI-harness roadmap can be considered complete: generic local-app task knowledge, installed-app/task resolution, deterministic intent parsing, local navigation, guarded input, result verification, latency reporting, and optional slow planner recovery. Weather lookup is the first benchmark definition for this generic system, not a Weather-specific architecture.
## Product Guides
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index cfe54d37..9a750a90 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -32,6 +32,8 @@ Donkey also supports reflex latency reports and a synthetic replay benchmark. `R
Donkey also supports the first fast local-navigation dry-run slice end to end through the dry-run reflex loop. `LocalNavigationMetadataFrameSource` can turn macOS window candidate metadata and optional browser-tab metadata supplied by callers into metadata-only hot-loop frames. `LocalNavigationDryRunPerceptionAdapter` and `LocalNavigationDryRunWorldStateProjector` keep the local-navigation path swappable while preserving the no-remote-model fallback. `LocalNavigationControllerPolicy` can choose traceable dry-run semantic actions such as `focusWindow`, `activateCandidate`, `switchTab`, `wait`, or `observe` from typed state. This slice is metadata-only and side-effect free by default; guarded live-action smoke requires an injected backend, and richer visual inference remains future work.
+Donkey also supports the first generic local-app task 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 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.
Donkey also supports slow-path planner hint contracts. `StructuredPlannerHint` carries a goal, policy, priorities, regions of interest, preferred and avoided semantic actions, confidence, expiry, and source trace/frame/state/model-call ids. Planner hints are advisory only; they are validated for unknown actions, unsafe actions, stale state references, low-confidence replacement, and expiry before selection. `PlannerHintSelector` chooses the latest valid hint, and the reflex loop remains able to run without any planner hint.
@@ -69,7 +71,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, deterministic controller, local-navigation dry-run, 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 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
@@ -99,6 +101,8 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic
- Use monotonic timestamps for latency math. Wall-clock timestamps are for human labels and trace correlation only.
- Use latency reports for any p50/p95/p99 claim. Reports should include dropped frames, stale actions, tick rates, and worst traces.
- Keep local-navigation decisions typed and side-effect free until the guarded live-action slice. Metadata projectors may use window, browser-tab, and Accessibility facts when available, but controllers should emit semantic actions only.
+- Keep 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.
- 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.
@@ -118,7 +122,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, 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 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:
@@ -149,8 +153,11 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi
- Guarded live-action smoke lives in `apps/Donkey/Sources/DonkeyRuntime/GuardedLiveActionSmoke.swift`.
- Reflex latency reports and synthetic replay benchmarks live in `apps/Donkey/Sources/DonkeyRuntime/ReflexLatencyReport.swift`.
- Local-navigation contracts live in `apps/Donkey/Sources/DonkeyContracts/LocalNavigationContracts.swift`.
+- 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`.
+- 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`.
- AI model registry and routing live in `apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift`.
- The OpenAI Responses planner-hint adapter lives in `apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift`.
diff --git a/plans/20-off-the-shelf-run-loop.md b/plans/20-off-the-shelf-run-loop.md
index 26830e49..52417157 100644
--- a/plans/20-off-the-shelf-run-loop.md
+++ b/plans/20-off-the-shelf-run-loop.md
@@ -1,12 +1,12 @@
# Off-The-Shelf Run Loop
-> Active status: not complete. The current repo supports metadata-only local-navigation dry-run scaffolding 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 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".
## Goal
Build the first fast local navigation agent from existing system components instead of custom model work.
-The first product proof is a local Weather lookup navigation benchmark. Donkey should interpret a natural command, use local macOS navigation to open or focus Weather, type/search for San Francisco, verify the app is showing the requested place, and leave the result visible. It should feel faster than manual app navigation or a chat assistant because most work is local and deterministic.
+The 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.
@@ -51,7 +51,8 @@ The first version should prove:
Use existing, swappable components:
-- deterministic intent parser for common local commands
+- deterministic intent parser for common local commands using app-task definitions
+- installed-app and task-knowledge lookup for target app identity, workflows, controls, and verification rules
- small local model or planner hint only for ambiguous command parsing
- target/task adapters for app-specific workflows
- LaunchServices or Workspace app launch/focus
@@ -125,24 +126,25 @@ The runtime shell does not own app-specific workflow internals, perception logic
### First Benchmark: Weather Lookup
-The first supported benchmark is:
+The first supported benchmark definition is:
```text
"show me the weather for SF"
-> weather_lookup(city: "San Francisco")
- -> open/focus Weather
- -> search/select San Francisco
- -> verify displayed location
+ -> resolve target app/task metadata
+ -> open/focus the target app
+ -> perform the definition's search/select workflow
+ -> verify displayed result
```
-The first navigation adapter should support:
+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
+- 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
-- guarded text entry into the Weather search field
-- verification that the visible Weather location matches San Francisco
+- 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
### Event Bridge
@@ -354,16 +356,16 @@ Rules:
- do not expose detector tensors or raw masks directly to the controller
- prefer task-specific state over generic scene captions
-For the Weather target, state should include:
+For a local app task, state should include task-specific facts such as:
```text
app_running
app_frontmost
-search_field_available
-search_text
-selected_location
-visible_location
-weather_result_visible
+required_control_available
+entered_text
+selected_result
+visible_result_text
+requested_result_visible
confidence
verification_reason
```
@@ -382,11 +384,11 @@ Task State
Examples:
-- Weather not running -> launch app
-- Weather running but not focused -> focus app
-- search field visible and empty -> type normalized city
-- matching location suggestion visible -> select suggestion
-- visible location matches normalized city -> complete
+- target app not running -> launch app
+- target app running but not focused -> focus app
+- required control visible and empty -> type normalized entity
+- matching suggestion/result visible -> select suggestion
+- visible result matches normalized entity -> complete
- obstacle on left lane -> move center/right
- button visible and safe -> tap button center
- health low -> request planner recovery hint
@@ -427,12 +429,12 @@ LLM output must become validated hints, not direct actions.
Pick one navigation scenario with a visible, verifiable end state.
-The first benchmark is Weather lookup:
+The first benchmark is still Weather lookup, represented as a local-app task definition rather than a dedicated adapter:
- command: "show me the weather for SF"
- normalized intent: `weather_lookup(city: "San Francisco")`
-- target app: Weather
-- success: Weather is frontmost and visibly showing San Francisco weather
+- target app: resolved from task definition
+- success: target app is frontmost and visibly showing the requested result
Good follow-on tasks:
@@ -449,7 +451,7 @@ Suggested first stack:
Intent: deterministic parser with local-model fallback for ambiguity
App control: NSWorkspace/LaunchServices activation
Observation: Accessibility snapshot first, screenshot/OCR fallback
-Rules: deterministic Weather task state machine
+Rules: deterministic local-app task state machine
Input: guarded keyboard/mouse or Accessibility action backend
Reasoning: local/online planner only for recovery or ambiguity
Runtime: native Swift coordinator and trace pipeline
@@ -457,24 +459,25 @@ Runtime: native Swift coordinator and trace pipeline
## Rollout
-1. Define `TaskIntent` for `weather_lookup`.
-2. Add deterministic parsing for "weather", city names, and common aliases such as `SF`.
-3. Define Weather task-state fields and terminal states.
-4. Add a Weather navigation adapter with dry-run semantic actions.
-5. Add app launch/focus action commands and guardrails.
-6. Add guarded text-entry and submit/select commands.
-7. Add Accessibility observation for Weather controls and visible location.
-8. Add screenshot/OCR fallback only where Accessibility is insufficient.
-9. Add result verification for San Francisco.
-10. Add command-to-result latency report and manual baseline comparison.
-11. Add optional slow planner recovery only after deterministic execution works.
-12. Keep game/vision adapters as follow-on targets using the same contracts.
+1. Define generic `TaskIntent`, target-app, entity, workflow-step, observation, and verification contracts.
+2. Add deterministic parsing from local app-task definitions, including aliases such as `SF -> San Francisco` in benchmark data.
+3. Add installed-app and app-task knowledge lookup for target app identity, workflows, controls, and verification rules.
+4. Define generic task-state fields and terminal states.
+5. Extend the generic local-app task adapter from dry-run semantic actions to guarded-live orchestration.
+6. 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.
+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.
+13. Keep game/vision adapters as follow-on targets using the same contracts.
## Acceptance Criteria
- No custom model work is required.
- The hot loop can run with the LLM disabled.
-- The Weather lookup navigation benchmark can run without a remote model call.
+- The first local-app task benchmark can run without a remote model call.
- Every perception component is swappable.
- Every action is explainable from state, rule, and trace id.
- p95 local navigation/action latency stays under the target budget.
@@ -501,13 +504,14 @@ 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
- 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.
## Required Before This Plan Is Done
-- Add a measured Weather lookup navigation adapter for the concrete command "show me the weather for SF".
+- Add an app-knowledge layer and measured first local-app task benchmark for the concrete 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.
diff --git a/plans/master-plan.md b/plans/master-plan.md
index 1e7e2041..6ce8b179 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -2,7 +2,7 @@
This is the active task queue. The milestone is focused on fast local navigation: Donkey should turn a short user command into structured intent, navigate the local desktop/app surface quickly, perform guarded local actions, verify the result, and leave the target in the requested state.
-Weather lookup is the first simple benchmark scenario for this navigation engine: when the user says something like "show me the weather for SF", Donkey should open or focus Weather, type/search for San Francisco, verify the result, and present it. The same loop should later generalize to faster game/app navigation where local observation and deterministic control matter more than chat reasoning.
+Weather lookup is the first simple benchmark scenario for this navigation engine, but it should be represented as app-task knowledge rather than Weather-specific code: when the user says something like "show me the weather for SF", Donkey should resolve the installed app/task definition, open or focus the right app, type/search for San Francisco, verify the result, and present it. The same generic loop should work for many local app use cases where Donkey behaves like an expert user of the app, using local observation and deterministic control rather than chat reasoning.
Primary plans:
@@ -33,8 +33,8 @@ Build the first product-shaped loop where Donkey can run a local navigation sess
```text
user command: "show me the weather for SF"
- -> local intent parse: weather_lookup(city: "San Francisco")
- -> app/task adapter: Weather
+ -> 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
-> deterministic UI controller
@@ -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, and dry-run action projection are supported. This is not yet a live fast-navigation agent: there is no Weather benchmark adapter, no default app launch/focus/type backend, and no verified 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, 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.
- 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.
@@ -80,18 +80,19 @@ Recent commits completed these pieces:
- `9b160f8` and `201e76c`: metadata-only local-navigation dry-run, local-navigation controller contracts, memory/replay scaffolding.
- `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.
-- current working slice: Ollama-compatible local planner adapter, provider-backed local/online slow planner fallback, and explicit slow-planner completion tests.
+- 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.
- `d6e48c9`: archived plans, which was premature for this milestone.
-The code does not yet include a Weather benchmark adapter, command-to-intent parsing for navigation tasks, default app launch/focus/type execution, Accessibility action execution, 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 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.
## What Should Be Done Next
-1. Add a `weather_lookup` intent contract and parser as the first fast-navigation benchmark, including deterministic aliases such as `SF -> San Francisco`.
-2. Add a Weather navigation adapter that can dry-run and then guarded-live: launch/focus Weather, find the search affordance, type the city, submit/select, and verify the displayed location.
-3. Add the default local action backend needed for this narrow task: app launch/activation plus guarded keyboard typing/clicking or Accessibility actions, with emergency release and focus checks.
+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.
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 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, or planner hints, never direct input.
## Completion Gates