Skip to content

Open source CapCut alternative.

TypeScript

Make local tasks cache-backed and model classified

David Le4c8309b38bbc
diff --git a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift
index 51691059..06098394 100644
--- a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift
@@ -316,13 +316,12 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
entry: AIModelRegistryEntry,
adapterRequest: TaskIntentAdapterRequest
) -> [String: Any] {
- [
+ return [
"model": entry.modelID,
"prompt": promptText(for: adapterRequest),
"stream": false,
"format": TaskIntentWireCodec.jsonSchema(
- taskTypes: adapterRequest.taskDefinitions.map(\.taskType),
- appNames: adapterRequest.taskDefinitions.map(\.targetApp.appName)
+ taskDefinitions: adapterRequest.taskDefinitions
),
"options": [
"num_ctx": 2048,
@@ -337,21 +336,30 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
private func promptText(for request: TaskIntentAdapterRequest) -> String {
let tasks = request.taskDefinitions.map { definition in
let entities = definition.entityRules.map { rule in
- "\(rule.name) required=\(rule.required) aliases=\(rule.aliases.keys.sorted().joined(separator: ","))"
+ "\(rule.name) required=\(rule.required)"
}
.joined(separator: "; ")
let workflow = definition.workflowSteps
.filter { $0.role != .parseIntent }
.map(\.summary)
.joined(separator: " -> ")
+ let automation = [
+ definition.metadata["automationBackend"].map { "automation_backend=\($0)" },
+ definition.metadata["appleScript.action"].map { "apple_script_action=\($0)" },
+ definition.metadata["appleScript.entityName"].map { "apple_script_entity=\($0)" }
+ ]
+ .compactMap(\.self)
+ .joined(separator: " | ")
return [
"task_type=\(definition.taskType)",
"app=\(definition.targetApp.appName)",
"bundle=\(definition.targetApp.bundleIdentifier ?? "unknown")",
"capability=\(workflow)",
- "entities=\(entities)"
+ "entities=\(entities)",
+ automation
]
+ .filter { !$0.isEmpty }
.joined(separator: " | ")
}
.joined(separator: "\n")
@@ -363,6 +371,8 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
"Use only the provided task definitions. Do not invent apps, task types, entities, or actions.",
"If no capability fits, return the closest supported task with confidence below 0.55.",
"If a required entity is missing, set needsConfirmation=true and include missingEntity in metadata.",
+ "For dynamic local-item capabilities, extract the requested local app/file/folder name into entities.appName and normalizedEntities.appName. Use targetAppName for the resolved item name when you know it.",
+ "For AppleScript-backed capabilities, include compact appleScript.source or appleScript.template metadata only when the provided action is insufficient; prefer task metadata and normalized entities for speed.",
"Command: \(request.command)",
"Supported task capabilities:",
tasks
@@ -443,14 +453,6 @@ public struct LocalModelTaskIntentResolver: Sendable {
)
guard let intent = result.intent else {
- if let fallbackIntent = LocalAppTaskIntentParser(taskDefinitions: catalog.taskDefinitions).parse(command) {
- var fallbackTrace = result.trace
- fallbackTrace.validationStatus = "deterministicFallback"
- fallbackTrace.metadata["fallback.parser"] = "local-app-task-deterministic-v1"
- fallbackTrace.metadata["fallback.reason"] = "localModelIntentUnavailable"
- return (catalog.resolve(intent: fallbackIntent), fallbackTrace)
- }
-
return (
LocalAppTaskCatalogResolution(
status: .needsConfirmation,
@@ -472,8 +474,15 @@ private struct OllamaTaskIntentResponse: Decodable {
}
private enum TaskIntentWireCodec {
- static func jsonSchema(taskTypes: [String], appNames: [String]) -> [String: Any] {
- [
+ static func jsonSchema(taskDefinitions: [LocalAppTaskDefinition]) -> [String: Any] {
+ let allowsDynamicTargets = taskDefinitions.contains { definition in
+ definition.metadata["dynamicTarget"] == "true"
+ }
+ let targetAppNameSchema: [String: Any] = allowsDynamicTargets
+ ? ["type": "string"]
+ : ["type": "string", "enum": Array(Set(taskDefinitions.map(\.targetApp.appName))).sorted()]
+
+ return [
"type": "object",
"additionalProperties": false,
"required": [
@@ -486,8 +495,8 @@ private enum TaskIntentWireCodec {
"metadata"
],
"properties": [
- "taskType": ["type": "string", "enum": Array(Set(taskTypes)).sorted()],
- "targetAppName": ["type": "string", "enum": Array(Set(appNames)).sorted()],
+ "taskType": ["type": "string", "enum": Array(Set(taskDefinitions.map(\.taskType))).sorted()],
+ "targetAppName": targetAppNameSchema,
"entities": [
"type": "object",
"additionalProperties": ["type": "string"]
@@ -514,18 +523,32 @@ private enum TaskIntentWireCodec {
) throws -> TaskIntent? {
let data = Data(outputText.utf8)
let wire = try JSONDecoder().decode(TaskIntentWire.self, from: data)
- guard let definition = definitions.first(where: {
+ let exactDefinition = definitions.first(where: {
$0.taskType == wire.taskType && $0.targetApp.appName == wire.targetAppName
- }) else {
+ })
+ let dynamicDefinition = definitions.first(where: {
+ $0.taskType == wire.taskType && $0.metadata["dynamicTarget"] == "true"
+ })
+ guard let definition = exactDefinition ?? dynamicDefinition else {
return nil
}
- let normalizedEntities = normalizedEntities(from: wire, definition: definition)
+ var entities = wire.entities
+ var normalizedEntities = normalizedEntities(from: wire, definition: definition)
+ if definition.metadata["dynamicTarget"] == "true",
+ normalizedEntities["appName"] == nil,
+ wire.targetAppName != definition.targetApp.appName {
+ entities["appName"] = wire.targetAppName
+ normalizedEntities["appName"] = wire.targetAppName
+ }
let missingRequiredEntity = definition.entityRules.first { rule in
rule.required && normalizedEntities[rule.name] == nil
}
var metadata = wire.metadata.merging(definition.metadata) { current, _ in current }
metadata["parser"] = parserName
+ if definition.metadata["dynamicTarget"] == "true" {
+ metadata["requestedItemName"] = normalizedEntities["appName"] ?? entities["appName"] ?? ""
+ }
if let missingRequiredEntity {
metadata["missingEntity"] = missingRequiredEntity.name
}
@@ -541,8 +564,8 @@ private enum TaskIntentWireCodec {
? "\(definition.taskType)-needs-\(missingRequiredEntity?.name ?? "confirmation")"
: "\(definition.taskType)-\(slug(primaryEntity))",
taskType: definition.taskType,
- targetApp: definition.targetApp,
- entities: wire.entities,
+ targetApp: targetApp(from: wire, definition: definition),
+ entities: entities,
normalizedEntities: normalizedEntities,
confidence: wire.confidence,
parserSource: .localModel,
@@ -566,6 +589,23 @@ private enum TaskIntentWireCodec {
return normalized
}
+ private static func targetApp(
+ from wire: TaskIntentWire,
+ definition: LocalAppTaskDefinition
+ ) -> LocalAppTarget {
+ guard definition.metadata["dynamicTarget"] == "true",
+ wire.targetAppName != definition.targetApp.appName else {
+ return definition.targetApp
+ }
+
+ return LocalAppTarget(
+ appName: wire.targetAppName,
+ bundleIdentifier: nil,
+ titleContains: wire.targetAppName,
+ metadata: definition.targetApp.metadata
+ )
+ }
+
private static func slug(_ value: String) -> String {
LocalAppTaskIntentParser.normalizedPhrase(value)
.split(separator: " ")
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift
new file mode 100644
index 00000000..5a3a0c05
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift
@@ -0,0 +1,105 @@
+import DonkeyContracts
+import Foundation
+
+public enum AppHarnessTurnClassificationKind: String, Equatable, Sendable {
+ case actionable
+ case answer
+ case unknown
+}
+
+public struct AppHarnessTurnClassification: Equatable, Sendable {
+ public var kind: AppHarnessTurnClassificationKind
+ public var response: String?
+ public var router: String
+ public var missingDetail: String?
+ public var metadata: [String: String]
+
+ public init(
+ kind: AppHarnessTurnClassificationKind,
+ response: String? = nil,
+ router: String,
+ missingDetail: String? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.kind = kind
+ self.response = response
+ self.router = router
+ self.missingDetail = missingDetail
+ self.metadata = metadata
+ }
+}
+
+public struct AppHarnessTurnClassifier: Sendable {
+ public init() {}
+
+ public func classify(
+ text: String,
+ request _: AppHarnessTurnRequest,
+ catalog _: LocalAppTaskCatalog
+ ) -> AppHarnessTurnClassification {
+ let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ let cacheCandidates = LocalItemResolutionCache.shared.search(query: trimmedText, limit: 3)
+ let classifierMetadata = [
+ "classifier": "fast-local-v1",
+ "cache.candidateKinds": cacheCandidates.map(\.entry.kind).joined(separator: ","),
+ "cache.candidateNames": cacheCandidates.map(\.entry.displayName).joined(separator: ",")
+ ]
+ if let response = Self.simpleArithmeticResponse(for: trimmedText) {
+ return AppHarnessTurnClassification(
+ kind: .answer,
+ response: response,
+ router: "simpleArithmetic",
+ metadata: classifierMetadata
+ )
+ }
+
+ return AppHarnessTurnClassification(
+ kind: .unknown,
+ router: "modelIntentRequired",
+ missingDetail: "actionable request",
+ metadata: classifierMetadata
+ )
+ }
+
+ private static func simpleArithmeticResponse(for text: String) -> String? {
+ let pattern = #"(-?\d+(?:\.\d+)?)\s*([+\-*/×x÷])\s*(-?\d+(?:\.\d+)?)"#
+ guard let regex = try? NSRegularExpression(pattern: pattern),
+ let match = regex.firstMatch(
+ in: text,
+ range: NSRange(text.startIndex..<text.endIndex, in: text)
+ ),
+ let lhsRange = Range(match.range(at: 1), in: text),
+ let operatorRange = Range(match.range(at: 2), in: text),
+ let rhsRange = Range(match.range(at: 3), in: text),
+ let lhs = Double(text[lhsRange]),
+ let rhs = Double(text[rhsRange])
+ else {
+ return nil
+ }
+
+ let operation = String(text[operatorRange])
+ let value: Double
+ switch operation {
+ case "+":
+ value = lhs + rhs
+ case "-":
+ value = lhs - rhs
+ case "*", "x", "X", "×":
+ value = lhs * rhs
+ case "/", "÷":
+ guard rhs != 0 else { return "I can't divide by zero." }
+ value = lhs / rhs
+ default:
+ return nil
+ }
+
+ return "\(formatNumber(lhs)) \(operation) \(formatNumber(rhs)) = \(formatNumber(value))."
+ }
+
+ private static func formatNumber(_ value: Double) -> String {
+ if value.rounded() == value {
+ return String(Int(value))
+ }
+ return String(value)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift
index f959d9f1..8713293d 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift
@@ -402,18 +402,8 @@ public struct AppHarnessContextPacketBuilder: Sendable {
)
}
- private static func isTransientCorrection(_ event: PointerPromptTaskEvent) -> Bool {
- let normalized = LocalAppTaskIntentParser.normalizedPhrase(event.text)
- guard event.role == .assistant || event.role == .system else { return false }
-
- return normalized.contains("retry")
- || normalized.contains("try again")
- || normalized.contains("invalid format")
- || normalized.contains("invalid output")
- || normalized.contains("unknown tool")
- || normalized.contains("missing prerequisite")
- || normalized.contains("step nudge")
- || normalized.contains("retry nudge")
+ private static func isTransientCorrection(_: PointerPromptTaskEvent) -> Bool {
+ false
}
}
@@ -434,13 +424,16 @@ private struct HarnessEventCompactionResult: Equatable, Sendable {
public struct AppHarnessTurnRouter: Sendable {
public var catalog: LocalAppTaskCatalog
public var contextBuilder: AppHarnessContextPacketBuilder
+ public var turnClassifier: AppHarnessTurnClassifier
public init(
catalog: LocalAppTaskCatalog,
- contextBuilder: AppHarnessContextPacketBuilder = AppHarnessContextPacketBuilder()
+ contextBuilder: AppHarnessContextPacketBuilder = AppHarnessContextPacketBuilder(),
+ turnClassifier: AppHarnessTurnClassifier = AppHarnessTurnClassifier()
) {
self.catalog = catalog
self.contextBuilder = contextBuilder
+ self.turnClassifier = turnClassifier
}
public func route(
@@ -467,78 +460,35 @@ public struct AppHarnessTurnRouter: Sendable {
)
}
- let deterministicResolution = catalog.resolve(command: trimmedText)
- switch deterministicResolution.status {
- case .resolved:
- return AppHarnessRoutingResult(
- contextPacket: packet,
- outcome: AppHarnessRoutingOutcome(
- decision: decision(
- kind: .runLocalTask,
- traceID: traceID,
- resolution: deterministicResolution,
- metadata: ["router": "deterministicCatalog"]
- ),
- resolution: deterministicResolution,
- metadata: ["router": "deterministicCatalog"]
- )
- )
- case .needsConfirmation:
- let missingDetail = deterministicResolution.metadata["reason"] ?? "detail"
- let response = clarificationPrompt(for: missingDetail, resolution: deterministicResolution)
- return AppHarnessRoutingResult(
- contextPacket: packet,
- outcome: AppHarnessRoutingOutcome(
- decision: decision(
- kind: .askClarification,
- traceID: traceID,
- message: response,
- missingDetail: missingDetail,
- resolution: deterministicResolution,
- metadata: ["router": "deterministicCatalog"]
- ),
- assistantResponse: response,
- missingDetail: missingDetail,
- resolution: deterministicResolution,
- metadata: ["router": "deterministicCatalog"]
- )
- )
- case .appUnavailable:
- return AppHarnessRoutingResult(
- contextPacket: packet,
- outcome: AppHarnessRoutingOutcome(
- decision: decision(
- kind: .runLocalTask,
- traceID: traceID,
- resolution: deterministicResolution,
- metadata: ["router": "deterministicCatalog"]
- ),
- resolution: deterministicResolution,
- metadata: ["router": "deterministicCatalog"]
- )
- )
- case .unsupportedCommand:
- break
- }
+ let modelIntentResolution = LocalAppTaskCatalogResolution(
+ status: .unsupportedCommand,
+ metadata: ["reason": "modelIntentRequired"]
+ )
- if request.turn.isFollowUp && !Self.isConversational(trimmedText) {
+ let classification = turnClassifier.classify(
+ text: trimmedText,
+ request: request,
+ catalog: catalog
+ )
+
+ if request.turn.isFollowUp && classification.kind == .unknown {
return AppHarnessRoutingResult(
contextPacket: packet,
outcome: AppHarnessRoutingOutcome(
decision: decision(
kind: .runLocalTask,
traceID: traceID,
- resolution: deterministicResolution,
+ resolution: modelIntentResolution,
metadata: ["router": "followUpActionContext"]
),
- resolution: deterministicResolution,
+ resolution: modelIntentResolution,
metadata: ["router": "followUpActionContext"]
)
)
}
- if Self.isConversational(trimmedText) {
- let response = conversationResponse(for: trimmedText)
+ if classification.kind == .answer,
+ let response = classification.response {
return AppHarnessRoutingResult(
contextPacket: packet,
outcome: AppHarnessRoutingOutcome(
@@ -546,30 +496,25 @@ public struct AppHarnessTurnRouter: Sendable {
kind: .respond,
traceID: traceID,
message: response,
- metadata: ["router": "conversationRules"]
+ metadata: ["router": classification.router]
),
assistantResponse: response,
- metadata: ["router": "conversationRules"]
+ metadata: ["router": classification.router].merging(classification.metadata) { current, _ in current }
)
)
}
- let response = "What would you like Donkey to do?"
return AppHarnessRoutingResult(
contextPacket: packet,
outcome: AppHarnessRoutingOutcome(
decision: decision(
- kind: .askClarification,
+ kind: .runLocalTask,
traceID: traceID,
- message: response,
- missingDetail: "actionable request",
- resolution: deterministicResolution,
- metadata: ["router": "unsupportedClarification"]
+ resolution: modelIntentResolution,
+ metadata: ["router": "modelIntent"]
),
- assistantResponse: response,
- missingDetail: "actionable request",
- resolution: deterministicResolution,
- metadata: ["router": "unsupportedClarification"]
+ resolution: modelIntentResolution,
+ metadata: ["router": "modelIntent"].merging(classification.metadata) { current, _ in current }
)
)
}
@@ -595,61 +540,26 @@ public struct AppHarnessTurnRouter: Sendable {
)
}
- private func conversationResponse(for text: String) -> String {
- let normalized = LocalAppTaskIntentParser.normalizedPhrase(text)
- if normalized.contains("what can") || normalized.contains("help") || normalized.contains("capabil") {
- let examples = catalog.taskDefinitions
- .map { $0.taskType.split(separator: "_").joined(separator: " ") }
- .sorted()
- .joined(separator: ", ")
- return examples.isEmpty
- ? "I can keep a task thread going and ask for details before taking action."
- : "I can keep a task thread going, ask for missing details, and run supported local tasks such as \(examples)."
- }
-
- return "Hi. Tell me what local app task you want to work on."
- }
-
private func clarificationPrompt(
for missingDetail: String,
resolution: LocalAppTaskCatalogResolution
) -> String {
- switch missingDetail {
- case "city":
- return "Which city should I use?"
- case "query":
- return "What should I play?"
- case "document":
- return "Which document should I use?"
- default:
- if let taskType = resolution.definition?.taskType.split(separator: "_").joined(separator: " ") {
- return "What \(missingDetail) should I use for \(taskType)?"
- }
- return "What \(missingDetail) should I use?"
+ let readableDetail = missingDetail
+ .split(separator: "_")
+ .joined(separator: " ")
+ if let definition = resolution.definition {
+ let taskTitle = Self.displayTitle(for: definition)
+ return "What \(readableDetail) should I use for \(taskTitle)?"
}
+ return "What \(readableDetail) should I use?"
}
- private static func isConversational(_ text: String) -> Bool {
- let normalized = LocalAppTaskIntentParser.normalizedPhrase(text)
- let greetings: Set<String> = [
- "hi",
- "hello",
- "hey",
- "good morning",
- "good afternoon",
- "good evening",
- "thanks",
- "thank you"
- ]
- if greetings.contains(normalized) {
- return true
+ private static func displayTitle(for definition: LocalAppTaskDefinition) -> String {
+ if let displayTitle = definition.metadata["displayTitle"], !displayTitle.isEmpty {
+ return displayTitle
}
-
- return normalized.contains("what can you do")
- || normalized.contains("what can donkey do")
- || normalized.contains("help")
- || normalized.contains("capabilities")
- || normalized.contains("how does donkey work")
- || normalized.contains("who are you")
+ return definition.taskType
+ .split(separator: "_")
+ .joined(separator: " ")
}
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
index f664205a..849a020d 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppAccessibilityControls.swift
@@ -74,7 +74,7 @@ public struct LocalAppAccessibilityControlIndex: Codable, Equatable, Sendable {
let kindMatches = acceptedKinds.isEmpty || acceptedKinds.contains(control.kind)
return kindMatches
&& (
- normalizedLabel.contains(normalizedID)
+ normalizedLabel == normalizedID
|| normalizedMetadataID == normalizedID
|| LocalAppTaskIntentParser.normalizedPhrase(control.id) == normalizedID
)
@@ -177,7 +177,7 @@ public struct LocalAppAccessibilityControlDiscovery: Sendable {
private func inferredControlID(label: String, kind: LocalAppControlKind) -> String {
let normalized = LocalAppTaskIntentParser.normalizedPhrase(label)
- if kind == .searchField || normalized.contains("search") {
+ if kind == .searchField {
return "search"
}
return normalized.replacingOccurrences(of: " ", with: "-")
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift
index cd302955..93e17ce8 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift
@@ -119,6 +119,62 @@ public struct LocalAppTaskAdapter: Sendable {
}
}
+ public func guardedAutomationCommandTemplates(
+ for intent: TaskIntent,
+ issuedAt: RunTraceTimestamp
+ ) -> [ActionEngineCommand] {
+ guard supports(intent),
+ intent.needsConfirmation == false,
+ definition.metadata["automationBackend"] == "appleScript"
+ else {
+ return []
+ }
+
+ let automationMetadata = definition.metadata.merging(intent.metadata) { _, new in new }
+ let action = automationMetadata["appleScript.action"] ?? "generated.\(definition.taskType)"
+ let entityName = automationMetadata["appleScript.entityName"]
+ ?? definition.verificationEntityName
+ ?? definition.entityRules.first?.name
+ let entityValue = entityName.flatMap { name in
+ intent.normalizedEntities[name] ?? intent.entities[name]
+ } ?? intent.normalizedEntities.values.sorted().first
+ ?? intent.entities.values.sorted().first
+ ?? ""
+ let trimmedEntityValue = entityValue.trimmingCharacters(in: .whitespacesAndNewlines)
+ let hasScriptSource = automationMetadata["appleScript.source"]?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
+ || automationMetadata["appleScript.template"]?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
+ guard !trimmedEntityValue.isEmpty || hasScriptSource else { return [] }
+
+ let workflowStepID = "apple-script-\(slug(action))"
+ var commandMetadata = automationMetadata.merging([
+ "taskIntentID": intent.intentID,
+ "taskType": intent.taskType,
+ "targetApp": definition.targetApp.appName,
+ "bundleIdentifier": definition.targetApp.bundleIdentifier ?? "",
+ "workflowStepID": workflowStepID,
+ "workflowStepRole": LocalAppTaskStepRole.custom.rawValue,
+ "automationBackend": "appleScript",
+ "appleScript.action": action,
+ "appleScript.entityName": entityName ?? "",
+ "appleScript.entityValue": trimmedEntityValue
+ ]) { current, _ in current }
+ if commandMetadata["appleScript.query"] == nil {
+ commandMetadata["appleScript.query"] = trimmedEntityValue
+ }
+
+ return [
+ ActionEngineCommand(
+ id: "\(intent.intentID)-\(workflowStepID)",
+ traceID: intent.metadata["traceID"] ?? intent.intentID,
+ targetID: targetID,
+ kind: .controller,
+ issuedAt: issuedAt,
+ key: trimmedEntityValue.isEmpty ? nil : trimmedEntityValue,
+ metadata: commandMetadata
+ )
+ ]
+ }
+
public func verifiesVisibleText(
_ visibleText: String?,
matches intent: TaskIntent
@@ -145,20 +201,16 @@ public struct LocalAppTaskAdapter: Sendable {
"bundleIdentifier": definition.targetApp.bundleIdentifier ?? "",
"guardedLiveRequiresInputPolicy": "true",
"defaultOSInputBackendAvailable": "true",
- "defaultOSInputBackend": "mac-keyboard"
+ "defaultOSInputBackend": definition.metadata["automationBackend"] == "appleScript"
+ ? "mac-apple-script"
+ : "mac-keyboard"
].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]
- )
+ verification: LocalAppTaskVerificationResult
) -> [LocalAppTaskDryRunStep] {
if definition.workflowSteps.isEmpty {
return [
@@ -248,79 +300,11 @@ public struct LocalAppTaskAdapter: Sendable {
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
- ]
+ ) -> LocalAppTaskVerificationResult {
+ LocalAppTaskVerificationPolicy.verify(
+ intent: intent,
+ definition: definition,
+ observation: observation
)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
index c9ecb50c..df461fac 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
@@ -23,6 +23,8 @@ public struct LocalAppAvailability: Equatable, Sendable {
public protocol LocalAppAvailabilityProviding: Sendable {
func availability(for target: LocalAppTarget) -> LocalAppAvailability
+ func availability(namedApp appName: String) -> LocalAppAvailability
+ func availability(namedLocalItem itemName: String) -> LocalAppAvailability
}
public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {
@@ -30,15 +32,19 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {
public func availability(for target: LocalAppTarget) -> LocalAppAvailability {
guard let bundleIdentifier = target.bundleIdentifier else {
- return LocalAppAvailability(
- target: target,
- isInstalled: false,
- metadata: ["reason": "missingBundleIdentifier"]
- )
+ return availability(namedApp: target.appName)
}
let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier)
- return LocalAppAvailability(
+ if appURL == nil,
+ let cachedAvailability = LocalItemResolutionCache.shared.cachedAvailability(
+ named: target.appName,
+ preferredKind: .application
+ ) {
+ return cachedAvailability
+ }
+
+ let availability = LocalAppAvailability(
target: target,
isInstalled: appURL != nil,
appURL: appURL,
@@ -47,18 +53,341 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {
"provider": "mac-nsworkspace"
]
)
+ LocalItemResolutionCache.shared.record(
+ availability: availability,
+ query: target.appName,
+ source: "bundleLookup"
+ )
+ return availability
+ }
+
+ public func availability(namedApp appName: String) -> LocalAppAvailability {
+ availability(namedLocalItem: appName, preferredKind: .application)
+ }
+
+ public func availability(namedLocalItem itemName: String) -> LocalAppAvailability {
+ availability(namedLocalItem: itemName, preferredKind: nil)
+ }
+
+ private func availability(
+ namedLocalItem itemName: String,
+ preferredKind: LocalItemKind?
+ ) -> LocalAppAvailability {
+ let requestedName = LocalAppLookup.cleanedLookupName(itemName)
+ guard !requestedName.isEmpty else {
+ return LocalAppAvailability(
+ target: LocalAppTarget(appName: itemName),
+ isInstalled: false,
+ metadata: [
+ "provider": "mac-local-item-lookup",
+ "reason": "missingLookupName"
+ ]
+ )
+ }
+
+ if let cachedAvailability = LocalItemResolutionCache.shared.cachedAvailability(
+ named: requestedName,
+ preferredKind: preferredKind
+ ) {
+ return cachedAvailability
+ }
+
+ if preferredKind == .application,
+ let runningApplication = Self.runningApplication(named: requestedName) {
+ let appName = runningApplication.localizedName ?? requestedName
+ let availability = LocalAppAvailability(
+ target: LocalAppTarget(
+ appName: appName,
+ bundleIdentifier: runningApplication.bundleIdentifier,
+ titleContains: appName
+ ),
+ isInstalled: true,
+ appURL: runningApplication.bundleURL,
+ metadata: [
+ "provider": "mac-local-item-lookup",
+ "requestedItemName": requestedName,
+ "bundleIdentifier": runningApplication.bundleIdentifier ?? "",
+ "itemKind": LocalItemKind.application.rawValue,
+ "itemURL": runningApplication.bundleURL?.path ?? "",
+ "match": "runningApplication"
+ ]
+ )
+ LocalItemResolutionCache.shared.record(
+ availability: availability,
+ query: requestedName,
+ source: "runningApplication"
+ )
+ return availability
+ }
+
+ guard let match = Self.localItem(named: requestedName, preferredKind: preferredKind) else {
+ let availability = LocalAppAvailability(
+ target: LocalAppTarget(appName: LocalAppLookup.titleCased(requestedName)),
+ isInstalled: false,
+ metadata: [
+ "provider": "mac-local-item-lookup",
+ "reason": "localItemUnavailable",
+ "requestedItemName": requestedName
+ ]
+ )
+ LocalItemResolutionCache.shared.record(
+ availability: availability,
+ query: requestedName,
+ source: "missingLookup"
+ )
+ return availability
+ }
+
+ let defaultApplication = Self.defaultApplication(for: match)
+ let availability = LocalAppAvailability(
+ target: LocalAppTarget(
+ appName: match.displayName,
+ bundleIdentifier: match.bundleIdentifier ?? defaultApplication?.bundleIdentifier,
+ titleContains: match.displayName,
+ metadata: [
+ "localItem.kind": match.kind.rawValue,
+ "localItem.path": match.url.path,
+ "localItem.defaultApplication": defaultApplication?.displayName ?? ""
+ ]
+ ),
+ isInstalled: true,
+ appURL: match.url,
+ metadata: [
+ "provider": match.provider,
+ "requestedItemName": requestedName,
+ "bundleIdentifier": match.bundleIdentifier ?? defaultApplication?.bundleIdentifier ?? "",
+ "itemKind": match.kind.rawValue,
+ "itemURL": match.url.path,
+ "defaultApplication": defaultApplication?.displayName ?? "",
+ "match": match.matchKind
+ ]
+ )
+ LocalItemResolutionCache.shared.record(
+ availability: availability,
+ query: requestedName,
+ source: match.provider
+ )
+ return availability
+ }
+
+ private static func runningApplication(named appName: String) -> NSRunningApplication? {
+ let normalizedName = LocalAppLookup.normalized(appName)
+ return NSWorkspace.shared.runningApplications.first { application in
+ guard let localizedName = application.localizedName else { return false }
+ return LocalAppLookup.nameMatches(
+ candidate: localizedName,
+ requested: normalizedName
+ ) != nil
+ }
+ }
+
+ private static func localItem(
+ named itemName: String,
+ preferredKind: LocalItemKind?
+ ) -> LocalItemMatch? {
+ let normalizedName = LocalAppLookup.normalized(itemName)
+ let matches = spotlightItems(named: itemName, requested: normalizedName, preferredKind: preferredKind)
+ + fallbackFileSystemItems(named: normalizedName, preferredKind: preferredKind)
+ return matches
+ .sorted(by: LocalItemMatch.isBetterMatch)
+ .first
+ }
+
+ private static func spotlightItems(
+ named itemName: String,
+ requested normalizedName: String,
+ preferredKind: LocalItemKind?
+ ) -> [LocalItemMatch] {
+ let escapedName = itemName.replacingOccurrences(of: "\"", with: "\\\"")
+ var query = #"kMDItemDisplayName == "*\#(escapedName)*"cd || kMDItemFSName == "*\#(escapedName)*"cd"#
+ if preferredKind == .application {
+ query = "(\(query)) && kMDItemContentTypeTree == \"com.apple.application-bundle\""
+ }
+
+ guard let output = runProcess(
+ executableURL: URL(fileURLWithPath: "/usr/bin/mdfind"),
+ arguments: [query],
+ timeoutSeconds: 1.5
+ ) else {
+ return []
+ }
+
+ return output
+ .split(whereSeparator: \.isNewline)
+ .prefix(100)
+ .compactMap { line in
+ localItemMatch(
+ url: URL(fileURLWithPath: String(line)),
+ requested: normalizedName,
+ provider: "mdfind",
+ preferredKind: preferredKind
+ )
+ }
+ }
+
+ private static func fallbackFileSystemItems(
+ named normalizedName: String,
+ preferredKind: LocalItemKind?
+ ) -> [LocalItemMatch] {
+ var matches: [LocalItemMatch] = []
+ for rootURL in fallbackSearchRoots() {
+ guard let enumerator = FileManager.default.enumerator(
+ at: rootURL,
+ includingPropertiesForKeys: [.isDirectoryKey, .contentTypeKey],
+ options: [.skipsHiddenFiles, .skipsPackageDescendants]
+ ) else {
+ continue
+ }
+
+ for case let itemURL as URL in enumerator {
+ guard let match = localItemMatch(
+ url: itemURL,
+ requested: normalizedName,
+ provider: "filesystem",
+ preferredKind: preferredKind
+ ) else {
+ continue
+ }
+ matches.append(match)
+ if matches.count >= 100 { return matches }
+ }
+ }
+
+ return matches
+ }
+
+ private static func localItemMatch(
+ url: URL,
+ requested normalizedName: String,
+ provider: String,
+ preferredKind: LocalItemKind?
+ ) -> LocalItemMatch? {
+ let kind = LocalItemKind(url: url)
+ if let preferredKind, kind != preferredKind {
+ return nil
+ }
+
+ let displayName = displayName(for: url, kind: kind)
+ guard let nameMatch = LocalAppLookup.nameMatches(
+ candidate: displayName,
+ requested: normalizedName
+ ) ?? LocalAppLookup.nameMatches(
+ candidate: url.deletingPathExtension().lastPathComponent,
+ requested: normalizedName
+ ) else {
+ return nil
+ }
+
+ let bundle = kind == .application ? Bundle(url: url) : nil
+ return LocalItemMatch(
+ url: url,
+ displayName: displayName,
+ kind: kind,
+ bundleIdentifier: bundle?.bundleIdentifier,
+ score: nameMatch.score + kind.scoreBias(preferredKind: preferredKind),
+ matchKind: nameMatch.kind,
+ provider: provider
+ )
+ }
+
+ private static func defaultApplication(for match: LocalItemMatch) -> LocalItemDefaultApplication? {
+ guard match.kind != .application,
+ let applicationURL = NSWorkspace.shared.urlForApplication(toOpen: match.url)
+ else {
+ return nil
+ }
+
+ let bundle = Bundle(url: applicationURL)
+ let displayName = bundle?.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
+ ?? bundle?.object(forInfoDictionaryKey: "CFBundleName") as? String
+ ?? applicationURL.deletingPathExtension().lastPathComponent
+ return LocalItemDefaultApplication(
+ displayName: displayName,
+ bundleIdentifier: bundle?.bundleIdentifier
+ )
+ }
+
+ private static func displayName(for url: URL, kind: LocalItemKind) -> String {
+ if kind == .application,
+ let bundle = Bundle(url: url) {
+ return bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
+ ?? bundle.object(forInfoDictionaryKey: "CFBundleName") as? String
+ ?? url.deletingPathExtension().lastPathComponent
+ }
+
+ return url.lastPathComponent
+ }
+
+ private static func fallbackSearchRoots() -> [URL] {
+ let homeApplications = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Applications", isDirectory: true)
+ let homeDirectory = FileManager.default.homeDirectoryForCurrentUser
+ return [
+ URL(fileURLWithPath: "/Applications", isDirectory: true),
+ URL(fileURLWithPath: "/Applications/Utilities", isDirectory: true),
+ URL(fileURLWithPath: "/System/Applications", isDirectory: true),
+ URL(fileURLWithPath: "/System/Applications/Utilities", isDirectory: true),
+ homeApplications,
+ homeDirectory.appendingPathComponent("Desktop", isDirectory: true),
+ homeDirectory.appendingPathComponent("Documents", isDirectory: true),
+ homeDirectory.appendingPathComponent("Downloads", isDirectory: true)
+ ]
+ }
+
+ private static func runProcess(
+ executableURL: URL,
+ arguments: [String],
+ timeoutSeconds: TimeInterval
+ ) -> String? {
+ let process = Process()
+ process.executableURL = executableURL
+ process.arguments = arguments
+
+ let output = Pipe()
+ process.standardOutput = output
+ process.standardError = Pipe()
+
+ do {
+ try process.run()
+ } catch {
+ return nil
+ }
+
+ let deadline = Date().addingTimeInterval(timeoutSeconds)
+ while process.isRunning && Date() < deadline {
+ Thread.sleep(forTimeInterval: 0.02)
+ }
+
+ if process.isRunning {
+ process.terminate()
+ }
+
+ let data = output.fileHandleForReading.readDataToEndOfFile()
+ return String(data: data, encoding: .utf8)
}
}
public struct StaticLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {
public var installedBundleIdentifiers: Set<String>
+ public var installedApplicationNames: [String: String]
+ public var installedLocalItemNames: [String: String]
- public init(installedBundleIdentifiers: Set<String>) {
+ public init(
+ installedBundleIdentifiers: Set<String>,
+ installedApplicationNames: [String: String] = [:],
+ installedLocalItemNames: [String: String] = [:]
+ ) {
self.installedBundleIdentifiers = installedBundleIdentifiers
+ self.installedApplicationNames = installedApplicationNames
+ self.installedLocalItemNames = installedLocalItemNames
}
public func availability(for target: LocalAppTarget) -> LocalAppAvailability {
let bundleIdentifier = target.bundleIdentifier ?? ""
+ guard !bundleIdentifier.isEmpty else {
+ return availability(namedApp: target.appName)
+ }
+
return LocalAppAvailability(
target: target,
isInstalled: installedBundleIdentifiers.contains(bundleIdentifier),
@@ -68,6 +397,207 @@ public struct StaticLocalAppAvailabilityProvider: LocalAppAvailabilityProviding
]
)
}
+
+ public func availability(namedApp appName: String) -> LocalAppAvailability {
+ availability(namedLocalItem: appName, preferredKind: .application)
+ }
+
+ public func availability(namedLocalItem itemName: String) -> LocalAppAvailability {
+ availability(namedLocalItem: itemName, preferredKind: nil)
+ }
+
+ private func availability(
+ namedLocalItem itemName: String,
+ preferredKind: LocalItemKind?
+ ) -> LocalAppAvailability {
+ let requestedName = LocalAppLookup.cleanedLookupName(itemName)
+ let normalizedRequestedName = LocalAppLookup.normalized(requestedName)
+ if let match = installedApplicationNames.first(where: { item in
+ LocalAppLookup.normalized(item.key) == normalizedRequestedName
+ }), preferredKind == nil || preferredKind == .application {
+ let bundleIdentifier = match.value
+ return LocalAppAvailability(
+ target: LocalAppTarget(
+ appName: match.key,
+ bundleIdentifier: bundleIdentifier,
+ titleContains: match.key,
+ metadata: [
+ "localItem.kind": LocalItemKind.application.rawValue
+ ]
+ ),
+ isInstalled: installedBundleIdentifiers.contains(bundleIdentifier),
+ metadata: [
+ "bundleIdentifier": bundleIdentifier,
+ "provider": "static",
+ "requestedItemName": requestedName,
+ "itemKind": LocalItemKind.application.rawValue
+ ]
+ )
+ }
+
+ if let bundleIdentifier = installedBundleIdentifiers.first(where: { bundleIdentifier in
+ LocalAppLookup.normalized(Self.inferredAppName(from: bundleIdentifier)) == normalizedRequestedName
+ }), preferredKind == nil || preferredKind == .application {
+ let appName = Self.inferredAppName(from: bundleIdentifier)
+ return LocalAppAvailability(
+ target: LocalAppTarget(
+ appName: appName,
+ bundleIdentifier: bundleIdentifier,
+ titleContains: appName,
+ metadata: [
+ "localItem.kind": LocalItemKind.application.rawValue
+ ]
+ ),
+ isInstalled: true,
+ metadata: [
+ "bundleIdentifier": bundleIdentifier,
+ "provider": "static",
+ "requestedItemName": requestedName,
+ "itemKind": LocalItemKind.application.rawValue
+ ]
+ )
+ }
+
+ if let match = installedLocalItemNames.first(where: { item in
+ LocalAppLookup.nameMatches(
+ candidate: item.key,
+ requested: normalizedRequestedName
+ ) != nil || LocalAppLookup.nameMatches(
+ candidate: URL(fileURLWithPath: item.key).deletingPathExtension().lastPathComponent,
+ requested: normalizedRequestedName
+ ) != nil
+ }), preferredKind == nil || preferredKind?.rawValue == match.value {
+ let itemKind = match.value
+ return LocalAppAvailability(
+ target: LocalAppTarget(
+ appName: match.key,
+ titleContains: match.key,
+ metadata: [
+ "localItem.kind": itemKind
+ ]
+ ),
+ isInstalled: true,
+ metadata: [
+ "provider": "static",
+ "requestedItemName": requestedName,
+ "itemKind": itemKind
+ ]
+ )
+ }
+
+ return LocalAppAvailability(
+ target: LocalAppTarget(appName: LocalAppLookup.titleCased(requestedName)),
+ isInstalled: false,
+ metadata: [
+ "provider": "static",
+ "reason": "localItemUnavailable",
+ "requestedItemName": requestedName
+ ]
+ )
+ }
+
+ private static func inferredAppName(from bundleIdentifier: String) -> String {
+ LocalAppLookup.titleCased(bundleIdentifier.split(separator: ".").last.map(String.init) ?? bundleIdentifier)
+ }
+}
+
+private struct LocalItemMatch: Equatable {
+ var url: URL
+ var displayName: String
+ var kind: LocalItemKind
+ var bundleIdentifier: String?
+ var score: Int
+ var matchKind: String
+ var provider: String
+
+ static func isBetterMatch(lhs: LocalItemMatch, rhs: LocalItemMatch) -> Bool {
+ if lhs.score == rhs.score {
+ if lhs.displayName.count == rhs.displayName.count {
+ return lhs.url.path.count < rhs.url.path.count
+ }
+ return lhs.displayName.count < rhs.displayName.count
+ }
+ return lhs.score < rhs.score
+ }
+}
+
+private struct LocalItemDefaultApplication: Equatable {
+ var displayName: String
+ var bundleIdentifier: String?
+}
+
+enum LocalItemKind: String, Equatable, Hashable {
+ case application
+ case folder
+ case file
+ case other
+
+ init(url: URL) {
+ if url.pathExtension == "app" {
+ self = .application
+ return
+ }
+
+ var isDirectory: ObjCBool = false
+ if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory),
+ isDirectory.boolValue {
+ self = .folder
+ return
+ }
+
+ self = url.pathExtension.isEmpty ? .other : .file
+ }
+
+ func scoreBias(preferredKind: LocalItemKind?) -> Int {
+ if self == preferredKind {
+ return -10
+ }
+
+ switch self {
+ case .application:
+ return 0
+ case .folder:
+ return 8
+ case .file:
+ return 12
+ case .other:
+ return 20
+ }
+ }
+}
+
+enum LocalAppLookup {
+ static func cleanedLookupName(_ value: String) -> String {
+ normalized(value).trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ static func normalized(_ value: String) -> String {
+ LocalAppTaskIntentParser.normalizedPhrase(value)
+ }
+
+ static func titleCased(_ value: String) -> String {
+ normalized(value)
+ .split(separator: " ")
+ .map { word in word.prefix(1).uppercased() + word.dropFirst() }
+ .joined(separator: " ")
+ }
+
+ static func nameMatches(
+ candidate: String,
+ requested normalizedRequestedName: String
+ ) -> (score: Int, kind: String)? {
+ let normalizedCandidate = normalized(candidate)
+ if normalizedCandidate == normalizedRequestedName {
+ return (0, "exact")
+ }
+ if normalizedCandidate.hasSuffix(" \(normalizedRequestedName)") {
+ return (1, "suffix")
+ }
+ if normalizedCandidate.contains(" \(normalizedRequestedName) ") {
+ return (2, "contains")
+ }
+ return nil
+ }
}
public enum LocalAppTaskCatalogResolutionStatus: String, Equatable, Sendable {
@@ -111,18 +641,32 @@ public struct LocalAppTaskCatalog: Sendable {
self.availabilityProvider = availabilityProvider
}
- public func resolve(command: String) -> LocalAppTaskCatalogResolution {
- guard let intent = LocalAppTaskIntentParser(taskDefinitions: taskDefinitions).parse(command) else {
+ public func resolve(command _: String) -> LocalAppTaskCatalogResolution {
+ LocalAppTaskCatalogResolution(
+ status: .unsupportedCommand,
+ metadata: ["reason": "modelIntentRequired"]
+ )
+ }
+
+ public func resolve(intent: TaskIntent) -> LocalAppTaskCatalogResolution {
+ if intent.parserSource != .deterministic,
+ intent.confidence < Self.minimumModelIntentConfidence {
return LocalAppTaskCatalogResolution(
- status: .unsupportedCommand,
- metadata: ["reason": "noTaskDefinitionMatched"]
+ status: .needsConfirmation,
+ intent: intent,
+ metadata: [
+ "reason": "lowConfidenceIntent",
+ "taskType": intent.taskType,
+ "targetApp": intent.targetApp.appName,
+ "intentConfidence": String(intent.confidence)
+ ]
)
}
- return resolve(intent: intent)
- }
+ if intent.taskType == Self.genericAppOpenTaskType {
+ return resolveGenericAppOpen(intent: intent)
+ }
- public func resolve(intent: TaskIntent) -> LocalAppTaskCatalogResolution {
guard let definition = taskDefinitions.first(where: { supports(intent: intent, definition: $0) }) else {
return LocalAppTaskCatalogResolution(
status: .unsupportedCommand,
@@ -175,10 +719,130 @@ public struct LocalAppTaskCatalog: Sendable {
&& intent.targetApp.appName == definition.targetApp.appName
&& intent.targetApp.bundleIdentifier == definition.targetApp.bundleIdentifier
}
+
+ private func resolveGenericAppOpen(intent: TaskIntent) -> LocalAppTaskCatalogResolution {
+ let requestedAppName = intent.metadata["requestedItemName"]
+ ?? intent.entities["appName"]
+ ?? intent.targetApp.appName
+ let cleanedRequestedAppName = LocalAppLookup.cleanedLookupName(requestedAppName)
+ guard !cleanedRequestedAppName.isEmpty,
+ cleanedRequestedAppName != LocalAppLookup.cleanedLookupName(Self.genericLocalItemTarget.appName)
+ else {
+ return LocalAppTaskCatalogResolution(
+ status: .needsConfirmation,
+ intent: intent,
+ definition: Self.genericAppOpenDefinition(target: Self.genericLocalItemTarget),
+ metadata: [
+ "reason": "appName",
+ "taskType": Self.genericAppOpenTaskType
+ ]
+ )
+ }
+ let availability = availabilityProvider.availability(namedLocalItem: cleanedRequestedAppName)
+ let target = availability.target
+ let definition = Self.genericAppOpenDefinition(target: target)
+ var resolvedIntent = intent
+ resolvedIntent.targetApp = target
+ resolvedIntent.normalizedEntities["appName"] = target.appName
+ resolvedIntent.metadata["bundleIdentifier"] = target.bundleIdentifier ?? ""
+ resolvedIntent.metadata["targetApp"] = target.appName
+ resolvedIntent.metadata["requestedItemName"] = cleanedRequestedAppName
+
+ guard availability.isInstalled else {
+ return LocalAppTaskCatalogResolution(
+ status: .appUnavailable,
+ intent: resolvedIntent,
+ definition: definition,
+ availability: availability,
+ metadata: [
+ "reason": "targetAppUnavailable",
+ "taskType": definition.taskType,
+ "targetApp": target.appName,
+ "requestedItemName": cleanedRequestedAppName,
+ "lookupProvider": availability.metadata["provider"] ?? "",
+ "itemKind": availability.metadata["itemKind"] ?? target.metadata["localItem.kind"] ?? ""
+ ]
+ )
+ }
+
+ return LocalAppTaskCatalogResolution(
+ status: .resolved,
+ intent: resolvedIntent,
+ definition: definition,
+ availability: availability,
+ metadata: [
+ "taskType": definition.taskType,
+ "targetApp": target.appName,
+ "requestedItemName": cleanedRequestedAppName,
+ "lookupProvider": availability.metadata["provider"] ?? "",
+ "itemKind": availability.metadata["itemKind"] ?? target.metadata["localItem.kind"] ?? ""
+ ]
+ )
+ }
+
+ public static var genericLocalItemOpenDefinition: LocalAppTaskDefinition {
+ genericAppOpenDefinition(target: genericLocalItemTarget)
+ }
+
+ public static func genericAppOpenDefinition(target: LocalAppTarget) -> LocalAppTaskDefinition {
+ LocalAppTaskDefinition(
+ taskType: genericAppOpenTaskType,
+ targetApp: target,
+ triggerTerms: [],
+ entityRules: [
+ LocalAppTaskEntityRule(
+ name: "appName",
+ required: true,
+ metadata: [
+ "dynamicLookupEntity": "true",
+ "description": "Requested local app, file, or folder name selected by the model"
+ ]
+ )
+ ],
+ workflowSteps: BuiltInLocalAppTaskDefinitions.commonWorkflowPrefix + [
+ LocalAppTaskWorkflowStepDefinition(
+ id: "verify-opened-app",
+ role: .verifyResult,
+ summary: "Verify the target app is visible or focused"
+ )
+ ],
+ observationStrategies: [.accessibility, .windowMetadata],
+ verificationEntityName: "appName",
+ metadata: [
+ "catalogEntry": "generic-app-open",
+ "displayTitle": "open local item",
+ "taskLabelTemplate": "Open {appName}",
+ "verificationTextKey": "appName",
+ "domain": "app",
+ "dynamicTarget": target.metadata["dynamicTarget"] ?? "false",
+ "localItem.kind": target.metadata["localItem.kind"] ?? "",
+ "localItem.path": target.metadata["localItem.path"] ?? ""
+ ]
+ )
+ }
+
+ private func slug(_ value: String) -> String {
+ LocalAppTaskIntentParser.normalizedPhrase(value)
+ .split(separator: " ")
+ .joined(separator: "-")
+ }
+
+ private static let genericAppOpenTaskType = "app_open"
+ private static let minimumModelIntentConfidence = 0.55
+ private static var genericLocalItemTarget: LocalAppTarget {
+ LocalAppTarget(
+ appName: "Local Item",
+ titleContains: nil,
+ metadata: [
+ "dynamicTarget": "true",
+ "localItem.kind": "dynamic"
+ ]
+ )
+ }
}
public enum BuiltInLocalAppTaskDefinitions {
- private static var commonWorkflowPrefix: [LocalAppTaskWorkflowStepDefinition] {
+ public static var commonWorkflowPrefix: [LocalAppTaskWorkflowStepDefinition] {
[
LocalAppTaskWorkflowStepDefinition(
id: "parse-intent",
@@ -207,20 +871,10 @@ public enum BuiltInLocalAppTaskDefinitions {
bundleIdentifier: "com.apple.weather",
titleContains: "Weather"
),
- triggerTerms: ["weather", "forecast", "temperature", "temp"],
+ triggerTerms: [],
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"
- ]
+ name: "city"
)
],
workflowSteps: commonWorkflowPrefix + [
@@ -261,7 +915,10 @@ public enum BuiltInLocalAppTaskDefinitions {
verificationEntityName: "city",
metadata: [
"catalogEntry": "built-in-weather-lookup",
+ "displayTitle": "weather lookup",
+ "taskLabelTemplate": "Weather for {city}",
"verificationTextKey": "city",
+ "screenshotFallback": "missingVerificationOrControls",
"visualFallback": "localModel",
"ocrFallbackDefault": "false"
]
@@ -276,16 +933,10 @@ public enum BuiltInLocalAppTaskDefinitions {
bundleIdentifier: "com.apple.Music",
titleContains: "Music"
),
- triggerTerms: ["play", "listen to", "put on"],
+ triggerTerms: [],
entityRules: [
LocalAppTaskEntityRule(
- name: "query",
- markers: ["play", "listen to", "put on"],
- aliases: [
- "cold play": "Coldplay",
- "coldplay": "Coldplay"
- ],
- metadata: ["capture": "afterTrigger"]
+ name: "query"
)
],
workflowSteps: commonWorkflowPrefix + [
@@ -310,17 +961,30 @@ public enum BuiltInLocalAppTaskDefinitions {
summary: "Submit the media search or playback command",
metadata: ["key": "Return"]
),
+ LocalAppTaskWorkflowStepDefinition(
+ id: "play-first-media-result",
+ role: .submit,
+ summary: "Play the first matching media result",
+ metadata: ["key": "Return"]
+ ),
LocalAppTaskWorkflowStepDefinition(
id: "verify-media-query",
role: .verifyResult,
- summary: "Verify the requested media is visible or selected"
+ summary: "Verify the playback command was sent"
)
],
observationStrategies: [.accessibility, .windowMetadata, .screenshotForLocalModel],
verificationEntityName: "query",
metadata: [
"catalogEntry": "built-in-media-playback",
+ "displayTitle": "media playback",
+ "taskLabelTemplate": "Play {query}",
"verificationTextKey": "query",
+ "verificationMode": "playbackCommandAttempted",
+ "automationBackend": "appleScript",
+ "appleScript.action": "music.playMediaQuery",
+ "appleScript.entityName": "query",
+ "screenshotFallback": "missingVerificationOrControls",
"domain": "media",
"visualFallback": "localModel",
"ocrFallbackDefault": "false"
@@ -336,26 +1000,14 @@ public enum BuiltInLocalAppTaskDefinitions {
bundleIdentifier: "com.apple.Preview",
titleContains: nil
),
- triggerTerms: ["fill pdf", "fill out pdf", "complete pdf", "fill form", "fill out this pdf"],
+ triggerTerms: [],
entityRules: [
LocalAppTaskEntityRule(
name: "document",
- markers: ["fill", "complete"],
- aliases: [
- "this pdf": "current PDF",
- "the pdf": "current PDF",
- "this form": "current form"
- ],
metadata: ["contextRole": "documentTarget"]
),
LocalAppTaskEntityRule(
name: "dataSource",
- markers: ["using", "with", "from"],
- aliases: [
- "this data": "provided data",
- "the data": "provided data",
- "these details": "provided data"
- ],
metadata: ["contextRole": "structuredInputData"]
)
],
@@ -388,18 +1040,22 @@ public enum BuiltInLocalAppTaskDefinitions {
verificationEntityName: "document",
metadata: [
"catalogEntry": "built-in-document-form-fill",
+ "displayTitle": "document form fill",
+ "taskLabelTemplate": "Fill {document}",
"domain": "document",
"requiresDocumentContext": "true",
"requiresStructuredData": "true",
"guardedLiveDefault": "reviewOnly",
+ "screenshotFallback": "missingVerificationOrControls",
"visualFallback": "localModel",
"ocrFallbackDefault": "false"
]
)
}
- public static var defaults: [LocalAppTaskDefinition] {
+ public static var benchmarkFixtures: [LocalAppTaskDefinition] {
[
+ LocalAppTaskCatalog.genericLocalItemOpenDefinition,
weatherLookup,
mediaPlayback,
documentFormFill
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift
index cee5c8cd..2fd33975 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift
@@ -9,9 +9,14 @@ public enum LocalAppTaskDefinitionLoaderError: Error, Equatable, Sendable {
public struct LocalAppTaskDefinitionLoader: Sendable {
public var decoder: JSONDecoder
+ public var cache: LocalItemResolutionCache
- public init(decoder: JSONDecoder = JSONDecoder()) {
+ public init(
+ decoder: JSONDecoder = JSONDecoder(),
+ cache: LocalItemResolutionCache = .shared
+ ) {
self.decoder = decoder
+ self.cache = cache
}
public static var defaultDirectoryURL: URL {
@@ -50,13 +55,24 @@ public struct LocalAppTaskDefinitionLoader: Sendable {
return definitions
}
- public func mergedWithBuiltIns(from directoryURL: URL) throws -> [LocalAppTaskDefinition] {
- BuiltInLocalAppTaskDefinitions.defaults + (try loadDirectory(directoryURL))
+ public func cachedDefinitions(from directoryURL: URL) throws -> [LocalAppTaskDefinition] {
+ let definitions = try loadDirectory(directoryURL)
+ cache.prewarmTaskDefinitions(definitions)
+ return cache.taskDefinitions()
}
public func defaultDefinitions() -> [LocalAppTaskDefinition] {
- (try? mergedWithBuiltIns(from: Self.defaultDirectoryURL))
- ?? BuiltInLocalAppTaskDefinitions.defaults
+ cache.prewarmTaskDefinitions(Self.runtimeSeedDefinitions)
+ if let generatedDefinitions = try? loadDirectory(Self.defaultDirectoryURL) {
+ cache.prewarmTaskDefinitions(generatedDefinitions)
+ }
+ return cache.taskDefinitions()
+ }
+
+ public static var runtimeSeedDefinitions: [LocalAppTaskDefinition] {
+ [
+ LocalAppTaskCatalog.genericLocalItemOpenDefinition
+ ]
}
private func loadJSON(from url: URL) throws -> [LocalAppTaskDefinition] {
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift
index 3169e5dd..154d9670 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift
@@ -8,190 +8,8 @@ public struct LocalAppTaskIntentParser: Sendable {
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,
- definition: definition
- ) 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,
- definition: LocalAppTaskDefinition
- ) -> (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))
- }
- }
-
- if rule.metadata["capture"] == "afterTrigger",
- let candidate = captureAfterTrigger(from: command, definition: definition) {
- let normalized = aliases[Self.normalizedPhrase(candidate)] ?? titleCased(candidate)
- return (candidate, normalized, normalized != titleCased(candidate))
- }
-
- return nil
- }
-
- private func captureAfterTrigger(from command: String, definition: LocalAppTaskDefinition) -> String? {
- let normalizedCommand = Self.normalizedPhrase(command)
- let triggers = definition.triggerTerms
- .map(Self.normalizedPhrase)
- .sorted { $0.count > $1.count }
-
- for trigger in triggers {
- guard normalizedCommand == trigger || normalizedCommand.hasPrefix("\(trigger) ") else {
- continue
- }
-
- let candidate = String(normalizedCommand.dropFirst(trigger.count))
- .trimmingCharacters(in: .whitespacesAndNewlines)
- guard !candidate.isEmpty else { continue }
- return cleanEntityCandidate(candidate)
- }
-
- 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: "-")
+ public func parse(_: String) -> TaskIntent? {
+ nil
}
public static func normalizedPhrase(_ value: String) -> String {
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
index 5662396f..2dbe5ff1 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift
@@ -103,7 +103,7 @@ public struct LocalAppTaskLiveRunner: Sendable {
command: command,
traceID: traceID,
resolution: catalog.resolve(command: command),
- metadata: ["intentParser": "deterministic"]
+ metadata: ["intentParser": "externalRequired"]
)
}
@@ -351,39 +351,75 @@ public struct LocalAppTaskLiveRunner: Sendable {
summary: "Dry-run plan allows guarded live execution",
metadata: ["terminalState": initialPlan.terminalState.rawValue]
)
+ if LocalAppTaskVerificationPolicy.mode(for: definition) == .openedLocalItem,
+ initialPlan.terminalState == .completed {
+ stepTracker.skip(.approval, summary: "No review gate required for opened local item")
+ stepTracker.skip(.execute, summary: "Local item was opened through NSWorkspace")
+ stepTracker.complete(
+ .verify,
+ summary: "Local item open request confirmed",
+ metadata: ["terminalState": initialPlan.terminalState.rawValue]
+ )
+ await coordinator?.complete(reason: "Local item opened")
+ let progress = stepTracker.snapshot()
+ return LocalAppTaskLiveRunResult(
+ command: command,
+ traceID: traceID,
+ status: .completed,
+ resolution: resolution,
+ initialPlan: initialPlan,
+ finalPlan: initialPlan,
+ observation: launchObservation,
+ workflowProgress: progress,
+ metadata: runMetadata.merging([
+ "reason": "openedLocalItem",
+ "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt)
+ ], uniquingKeysWith: { current, _ in current }).merging(
+ Self.workflowProgressMetadata(progress),
+ uniquingKeysWith: { current, _ in current }
+ )
+ )
+ }
stepTracker.skip(.approval, summary: "No review gate required for this local-app task")
var actionTraces: [ActionEngineCommandTrace] = []
- var accessibilityActionMS = 0.0
- let accessibilityCommands = await accessibilityCommandTemplates(
- intent: intent,
- definition: definition
+ let automationCommands = adapter.guardedAutomationCommandTemplates(
+ for: intent,
+ issuedAt: Self.now()
)
- if !accessibilityCommands.isEmpty {
- let accessibilityEngine = Self.accessibilityActionEngine(for: definition)
- for (index, actionCommand) in accessibilityCommands.enumerated() {
- await coordinator?.waitIfPaused()
- let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 60))
- let actionStartedAt = Self.uptimeMilliseconds()
- await coordinator?.recordToolEvent(
- capability: .accessibility,
- decision: permissionPolicy.decision(for: .accessibility),
- toolName: "mac-accessibility-action-engine",
- summary: "Executing guarded Accessibility command",
- traceID: traceID,
- metadata: [
- "commandID": spacedCommand.id,
- "workflowStepID": spacedCommand.metadata["workflowStepID"] ?? ""
- ]
- )
- let trace = await accessibilityEngine.handle(
- spacedCommand,
- permissionPolicy: permissionPolicy
- )
- accessibilityActionMS += Self.uptimeMilliseconds() - actionStartedAt
- actionTraces.append(trace)
- guard trace.executed || trace.decision == .projectedDryRun else {
- break
+ let usesAutomationBackend = !automationCommands.isEmpty
+ var accessibilityActionMS = 0.0
+ if !usesAutomationBackend {
+ let accessibilityCommands = await accessibilityCommandTemplates(
+ intent: intent,
+ definition: definition
+ )
+ if !accessibilityCommands.isEmpty {
+ let accessibilityEngine = Self.accessibilityActionEngine(for: definition)
+ for (index, actionCommand) in accessibilityCommands.enumerated() {
+ await coordinator?.waitIfPaused()
+ let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 60))
+ let actionStartedAt = Self.uptimeMilliseconds()
+ await coordinator?.recordToolEvent(
+ capability: .accessibility,
+ decision: permissionPolicy.decision(for: .accessibility),
+ toolName: "mac-accessibility-action-engine",
+ summary: "Executing guarded Accessibility command",
+ traceID: traceID,
+ metadata: [
+ "commandID": spacedCommand.id,
+ "workflowStepID": spacedCommand.metadata["workflowStepID"] ?? ""
+ ]
+ )
+ let trace = await accessibilityEngine.handle(
+ spacedCommand,
+ permissionPolicy: permissionPolicy
+ )
+ accessibilityActionMS += Self.uptimeMilliseconds() - actionStartedAt
+ actionTraces.append(trace)
+ guard trace.executed || trace.decision == .projectedDryRun else {
+ break
+ }
}
}
}
@@ -395,13 +431,15 @@ public struct LocalAppTaskLiveRunner: Sendable {
return workflowStepID(from: trace.command)
})
runMetadata["accessibilityHandledStepIDs"] = accessibilityHandledStepIDs.sorted().joined(separator: ",")
- let commands = adapter.guardedKeyboardCommandTemplates(
- for: intent,
- issuedAt: Self.now()
- ).filter { command in
- guard let workflowStepID = command.metadata["workflowStepID"] else { return true }
- return !accessibilityHandledStepIDs.contains(workflowStepID)
- }
+ let commands = usesAutomationBackend
+ ? automationCommands
+ : adapter.guardedKeyboardCommandTemplates(
+ for: intent,
+ issuedAt: Self.now()
+ ).filter { command in
+ guard let workflowStepID = command.metadata["workflowStepID"] else { return true }
+ return !accessibilityHandledStepIDs.contains(workflowStepID)
+ }
var keyboardActionMS = 0.0
stepTracker.start(.execute, summary: "Executing guarded local-app actions")
@@ -409,11 +447,17 @@ public struct LocalAppTaskLiveRunner: Sendable {
await coordinator?.waitIfPaused()
let spacedCommand = actionCommand.withIssuedAt(Self.now(advancedByMilliseconds: Double(index) * 40))
let actionStartedAt = Self.uptimeMilliseconds()
+ let automationBackend = actionCommand.metadata["automationBackend"] ?? ""
+ let actionToolName = automationBackend == "appleScript"
+ ? "mac-applescript-action-engine"
+ : "mac-keyboard-action-engine"
await coordinator?.recordToolEvent(
capability: .input,
decision: permissionPolicy.decision(for: .input),
- toolName: "mac-keyboard-action-engine",
- summary: "Executing guarded keyboard command",
+ toolName: actionToolName,
+ summary: automationBackend == "appleScript"
+ ? "Executing guarded AppleScript command"
+ : "Executing guarded keyboard command",
traceID: traceID,
metadata: [
"commandID": spacedCommand.id,
@@ -492,6 +536,11 @@ public struct LocalAppTaskLiveRunner: Sendable {
}
}
runMetadata["latency.keyboardActionMS"] = Self.formatLatency(keyboardActionMS)
+ if usesAutomationBackend {
+ runMetadata["automation.backend"] = automationCommands.first?.metadata["automationBackend"] ?? ""
+ runMetadata["automation.action"] = automationCommands.first?.metadata["appleScript.action"] ?? ""
+ runMetadata["latency.automationActionMS"] = Self.formatLatency(keyboardActionMS)
+ }
stepTracker.complete(
.execute,
summary: "Guarded local-app actions completed",
@@ -564,13 +613,17 @@ public struct LocalAppTaskLiveRunner: Sendable {
}
public static func defaultActionEngine(for definition: LocalAppTaskDefinition) -> ActionEngineGuardrail {
- ActionEngineGuardrail(
+ let inputBackend: any ActionEngineInputBackend = definition.metadata["automationBackend"] == "appleScript"
+ ? MacAppleScriptActionEngineInputBackend()
+ : MacKeyboardActionEngineInputBackend()
+
+ return ActionEngineGuardrail(
configuration: ActionEngineConfiguration(liveInputEnabled: true),
focusGuard: MacLocalAppFocusGuard(
targetID: LocalAppTaskAdapter(definition: definition).targetID,
bundleIdentifier: definition.targetApp.bundleIdentifier
),
- inputBackend: MacKeyboardActionEngineInputBackend()
+ inputBackend: inputBackend
)
}
@@ -794,6 +847,37 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
definition: LocalAppTaskDefinition,
availability: LocalAppAvailability
) async -> LocalAppTaskObservation {
+ if let itemURL = availability.appURL,
+ let itemKind = availability.metadata["itemKind"],
+ itemKind != "application" {
+ let opened = await openLocalItem(at: itemURL)
+ if let bundleIdentifier = definition.targetApp.bundleIdentifier {
+ await waitForFrontmostApplication(
+ LocalAppTarget(
+ appName: definition.targetApp.appName,
+ bundleIdentifier: bundleIdentifier,
+ titleContains: definition.targetApp.titleContains
+ )
+ )
+ }
+ let isFocused = definition.targetApp.bundleIdentifier == nil
+ || NSWorkspace.shared.frontmostApplication?.bundleIdentifier == definition.targetApp.bundleIdentifier
+ return LocalAppTaskObservation(
+ appIsRunning: opened,
+ appIsFocused: opened && isFocused,
+ availableControls: [:],
+ visibleText: ["appName": definition.targetApp.appName],
+ confidence: opened ? 0.72 : 0.2,
+ metadata: [
+ "observer": "mac-local-app-controller",
+ "openedLocalItem": String(opened),
+ "localItem.kind": itemKind,
+ "localItem.path": itemURL.path,
+ "defaultApplication": availability.metadata["defaultApplication"] ?? ""
+ ]
+ )
+ }
+
if let appURL = availability.appURL {
await openApplication(at: appURL)
} else if let runningApplication = runningApplication(for: definition.targetApp) {
@@ -1017,6 +1101,11 @@ public struct MacLocalAppTaskController: LocalAppTaskAppControlling {
}
}
+ @MainActor
+ private func openLocalItem(at url: URL) async -> Bool {
+ NSWorkspace.shared.open(url)
+ }
+
@MainActor
private func waitForFrontmostApplication(_ target: LocalAppTarget) async {
let bundleIdentifier = target.bundleIdentifier
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swift
index 8a9ff5fb..1fe9bb3f 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskObservationFallbackPolicy.swift
@@ -11,11 +11,54 @@ public enum LocalAppTaskObservationFallbackPolicy {
return false
}
+ switch screenshotFallbackMode(for: definition) {
+ case .never:
+ return false
+ case .always:
+ return true
+ case .missingVerificationText:
+ return accessibilityObservation.visibleText[verificationKey]?.isEmpty != false
+ case .missingControls:
+ return missingRequiredControls(
+ definition: definition,
+ accessibilityObservation: accessibilityObservation
+ )
+ case .missingVerificationOrControls:
+ break
+ }
+
if accessibilityObservation.visibleText[verificationKey]?.isEmpty == false {
return false
}
- return definition.workflowSteps.contains { step in
+ return missingRequiredControls(
+ definition: definition,
+ accessibilityObservation: accessibilityObservation
+ ) || accessibilityObservation.visibleText.isEmpty
+ }
+
+ static func screenshotFallbackMode(
+ for definition: LocalAppTaskDefinition
+ ) -> LocalAppTaskScreenshotFallbackMode {
+ switch definition.metadata["screenshotFallback"] {
+ case "never":
+ return .never
+ case "always":
+ return .always
+ case "missingVerificationText":
+ return .missingVerificationText
+ case "missingControls":
+ return .missingControls
+ default:
+ return .missingVerificationOrControls
+ }
+ }
+
+ private static func missingRequiredControls(
+ definition: LocalAppTaskDefinition,
+ accessibilityObservation: LocalAppTaskObservation
+ ) -> Bool {
+ definition.workflowSteps.contains { step in
guard step.role == .focusControl,
let controlID = step.metadata["controlID"]
else {
@@ -23,6 +66,14 @@ public enum LocalAppTaskObservationFallbackPolicy {
}
return accessibilityObservation.availableControls[controlID] != true
- } || accessibilityObservation.visibleText.isEmpty
+ }
}
}
+
+enum LocalAppTaskScreenshotFallbackMode: String, Equatable, Sendable {
+ case never
+ case always
+ case missingVerificationText
+ case missingControls
+ case missingVerificationOrControls
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskVerificationPolicy.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskVerificationPolicy.swift
new file mode 100644
index 00000000..39019bef
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskVerificationPolicy.swift
@@ -0,0 +1,255 @@
+import DonkeyContracts
+import Foundation
+
+enum LocalAppTaskVerificationMode: String, Equatable, Sendable {
+ case focusedApp
+ case openedLocalItem
+ case commandAttempted
+ case visibleText
+}
+
+struct LocalAppTaskVerificationResult: Equatable, Sendable {
+ var status: LocalAppTaskStepStatus
+ var terminalState: LocalAppTaskTerminalState
+ var confidence: Double
+ var summary: String
+ var metadata: [String: String]
+}
+
+enum LocalAppTaskVerificationPolicy {
+ static func mode(for definition: LocalAppTaskDefinition) -> LocalAppTaskVerificationMode {
+ switch definition.metadata["verificationMode"] {
+ case "focusedApp":
+ return .focusedApp
+ case "openedLocalItem":
+ return .openedLocalItem
+ case "playbackCommandAttempted", "commandAttempted":
+ return .commandAttempted
+ case "visibleText":
+ return .visibleText
+ default:
+ if let itemKind = definition.metadata["localItem.kind"], !itemKind.isEmpty {
+ return itemKind == LocalItemKind.application.rawValue ? .focusedApp : .openedLocalItem
+ }
+ if definition.metadata["automationBackend"]?.isEmpty == false {
+ return .commandAttempted
+ }
+ return .visibleText
+ }
+ }
+
+ static func verify(
+ intent: TaskIntent,
+ definition: LocalAppTaskDefinition,
+ observation: LocalAppTaskObservation?
+ ) -> LocalAppTaskVerificationResult {
+ switch mode(for: definition) {
+ case .focusedApp:
+ return verifyFocusedApp(definition: definition, observation: observation)
+ case .openedLocalItem:
+ return verifyOpenedLocalItem(definition: definition, observation: observation)
+ case .commandAttempted:
+ return verifyCommandAttempted(definition: definition, observation: observation)
+ case .visibleText:
+ return verifyVisibleText(intent: intent, definition: definition, observation: observation)
+ }
+ }
+
+ private static func verifyFocusedApp(
+ definition: LocalAppTaskDefinition,
+ observation: LocalAppTaskObservation?
+ ) -> LocalAppTaskVerificationResult {
+ guard let observation else {
+ return blocked(
+ summary: "Target app has not been observed yet",
+ metadata: ["reason": "missingObservation"]
+ )
+ }
+
+ if observation.appIsFocused {
+ return verified(
+ confidence: max(observation.confidence, 0.8),
+ summary: "Target app is focused",
+ metadata: [
+ "verificationMode": modeName(for: definition),
+ "targetApp": definition.targetApp.appName
+ ]
+ )
+ }
+
+ return blocked(
+ confidence: observation.confidence,
+ summary: "Target app is not focused",
+ metadata: [
+ "reason": "targetAppNotFocused",
+ "verificationMode": modeName(for: definition),
+ "targetApp": definition.targetApp.appName
+ ]
+ )
+ }
+
+ private static func verifyOpenedLocalItem(
+ definition: LocalAppTaskDefinition,
+ observation: LocalAppTaskObservation?
+ ) -> LocalAppTaskVerificationResult {
+ guard let observation else {
+ return blocked(
+ summary: "Local item has not been observed yet",
+ metadata: ["reason": "missingObservation"]
+ )
+ }
+
+ if observation.metadata["openedLocalItem"] == "true" || observation.appIsFocused {
+ return verified(
+ confidence: max(observation.confidence, 0.72),
+ summary: "Local item was opened",
+ metadata: [
+ "verificationMode": modeName(for: definition),
+ "targetItem": definition.targetApp.appName,
+ "localItem.kind": definition.metadata["localItem.kind"] ?? ""
+ ]
+ )
+ }
+
+ return blocked(
+ confidence: observation.confidence,
+ summary: "Local item could not be confirmed open",
+ metadata: [
+ "reason": "localItemOpenUnconfirmed",
+ "verificationMode": modeName(for: definition),
+ "targetItem": definition.targetApp.appName
+ ]
+ )
+ }
+
+ private static func verifyCommandAttempted(
+ definition: LocalAppTaskDefinition,
+ observation: LocalAppTaskObservation?
+ ) -> LocalAppTaskVerificationResult {
+ guard let observation else {
+ return blocked(
+ summary: "\(definition.targetApp.appName) has not been observed yet",
+ metadata: ["reason": "missingObservation"]
+ )
+ }
+
+ if observation.appIsFocused || observation.appIsRunning {
+ return verified(
+ confidence: max(observation.confidence, 0.72),
+ summary: "Command was sent to \(definition.targetApp.appName)",
+ metadata: [
+ "verificationMode": modeName(for: definition),
+ "targetApp": definition.targetApp.appName
+ ]
+ )
+ }
+
+ return blocked(
+ confidence: observation.confidence,
+ summary: "\(definition.targetApp.appName) is not running for command verification",
+ metadata: [
+ "reason": "targetAppNotRunning",
+ "verificationMode": modeName(for: definition),
+ "targetApp": definition.targetApp.appName
+ ]
+ )
+ }
+
+ private static func verifyVisibleText(
+ intent: TaskIntent,
+ definition: LocalAppTaskDefinition,
+ observation: LocalAppTaskObservation?
+ ) -> LocalAppTaskVerificationResult {
+ guard let entityName = definition.verificationEntityName,
+ let expected = intent.normalizedEntities[entityName]
+ else {
+ return blocked(
+ summary: "No verification entity is configured for this task",
+ metadata: ["reason": "missingVerificationEntity"]
+ )
+ }
+
+ guard let observation else {
+ return blocked(
+ summary: "Visible app result has not been observed yet",
+ metadata: [
+ "reason": "missingObservation",
+ "expectedEntityName": entityName,
+ "expectedEntityValue": expected
+ ]
+ )
+ }
+
+ let visibleTextKey = definition.metadata["verificationTextKey"] ?? entityName
+ guard let visibleText = observation.visibleText[visibleTextKey] else {
+ return blocked(
+ confidence: observation.confidence,
+ summary: "Verification text is not available yet",
+ metadata: [
+ "reason": "missingVisibleText",
+ "visibleTextKey": visibleTextKey,
+ "expectedEntityValue": expected
+ ]
+ )
+ }
+
+ if normalized(visibleText).contains(normalized(expected)) {
+ return verified(
+ confidence: max(observation.confidence, 0.8),
+ summary: "Visible app result matches the requested entity",
+ metadata: [
+ "visibleText": visibleText,
+ "expectedEntityName": entityName,
+ "expectedEntityValue": expected
+ ]
+ )
+ }
+
+ return blocked(
+ confidence: observation.confidence,
+ summary: "Visible app result does not match the requested entity",
+ metadata: [
+ "reason": "resultMismatch",
+ "visibleText": visibleText,
+ "expectedEntityName": entityName,
+ "expectedEntityValue": expected
+ ]
+ )
+ }
+
+ private static func verified(
+ confidence: Double,
+ summary: String,
+ metadata: [String: String]
+ ) -> LocalAppTaskVerificationResult {
+ LocalAppTaskVerificationResult(
+ status: .verified,
+ terminalState: .completed,
+ confidence: confidence,
+ summary: summary,
+ metadata: metadata
+ )
+ }
+
+ private static func blocked(
+ confidence: Double = 0,
+ summary: String,
+ metadata: [String: String]
+ ) -> LocalAppTaskVerificationResult {
+ LocalAppTaskVerificationResult(
+ status: .blocked,
+ terminalState: .needsUserReview,
+ confidence: confidence,
+ summary: summary,
+ metadata: metadata
+ )
+ }
+
+ private static func modeName(for definition: LocalAppTaskDefinition) -> String {
+ definition.metadata["verificationMode"] ?? mode(for: definition).rawValue
+ }
+
+ private static func normalized(_ value: String) -> String {
+ LocalAppTaskIntentParser.normalizedPhrase(value)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalItemResolutionCache.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalItemResolutionCache.swift
new file mode 100644
index 00000000..e71f9ecf
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalItemResolutionCache.swift
@@ -0,0 +1,739 @@
+import AppKit
+import DonkeyContracts
+import Foundation
+
+public struct LocalItemResolutionCacheEntry: Codable, Equatable, Sendable {
+ public var id: String
+ public var query: String
+ public var normalizedQuery: String
+ public var displayName: String
+ public var normalizedDisplayName: String
+ public var kind: String
+ public var path: String?
+ public var bundleIdentifier: String?
+ public var isAvailable: Bool
+ public var source: String
+ public var match: String
+ public var firstResolvedAt: String
+ public var lastResolvedAt: String
+ public var useCount: Int
+ public var metadata: [String: String]
+ public var searchText: String
+}
+
+public struct LocalItemResolutionCacheSearchResult: Equatable, Sendable {
+ public var entry: LocalItemResolutionCacheEntry
+ public var score: Int
+}
+
+public struct LocalItemResolutionCachePrewarmOptions: Sendable {
+ public var applicationRoots: [URL]
+ public var fileRoots: [URL]
+ public var maxItemsPerRoot: Int
+
+ public init(
+ applicationRoots: [URL],
+ fileRoots: [URL],
+ maxItemsPerRoot: Int = 600
+ ) {
+ self.applicationRoots = applicationRoots
+ self.fileRoots = fileRoots
+ self.maxItemsPerRoot = max(0, maxItemsPerRoot)
+ }
+
+ public static func defaults() -> LocalItemResolutionCachePrewarmOptions {
+ let homeDirectory = FileManager.default.homeDirectoryForCurrentUser
+ return LocalItemResolutionCachePrewarmOptions(
+ applicationRoots: [
+ URL(fileURLWithPath: "/Applications", isDirectory: true),
+ URL(fileURLWithPath: "/Applications/Utilities", isDirectory: true),
+ URL(fileURLWithPath: "/System/Applications", isDirectory: true),
+ URL(fileURLWithPath: "/System/Applications/Utilities", isDirectory: true),
+ homeDirectory.appendingPathComponent("Applications", isDirectory: true)
+ ],
+ fileRoots: [
+ homeDirectory.appendingPathComponent("Desktop", isDirectory: true),
+ homeDirectory.appendingPathComponent("Documents", isDirectory: true),
+ homeDirectory.appendingPathComponent("Downloads", isDirectory: true)
+ ]
+ )
+ }
+}
+
+public final class LocalItemResolutionCache: @unchecked Sendable {
+ public static let shared = LocalItemResolutionCache()
+
+ public static var defaultStoreURL: URL {
+ let applicationSupport = FileManager.default.urls(
+ for: .applicationSupportDirectory,
+ in: .userDomainMask
+ ).first ?? FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Application Support", isDirectory: true)
+
+ return applicationSupport
+ .appendingPathComponent("Donkey", isDirectory: true)
+ .appendingPathComponent("LocalItemResolutionCache", isDirectory: true)
+ .appendingPathComponent("local-item-cache.jsonl")
+ }
+
+ private let storeURL: URL
+ private let lock = NSLock()
+ private var entriesByID: [String: LocalItemResolutionCacheEntry]
+ private var isPrewarming = false
+
+ public init(storeURL: URL = LocalItemResolutionCache.defaultStoreURL) {
+ self.storeURL = storeURL
+ self.entriesByID = Self.loadEntries(from: storeURL)
+ }
+
+ public func prewarmDefaultLocalItemsInBackground(
+ options: LocalItemResolutionCachePrewarmOptions = .defaults()
+ ) {
+ lock.lock()
+ guard !isPrewarming else {
+ lock.unlock()
+ return
+ }
+ isPrewarming = true
+ lock.unlock()
+
+ Task.detached(priority: .utility) { [self] in
+ prewarmDefaultLocalItems(options: options)
+ finishPrewarming()
+ }
+ }
+
+ public func prewarmDefaultLocalItems(
+ options: LocalItemResolutionCachePrewarmOptions = .defaults()
+ ) {
+ guard options.maxItemsPerRoot > 0 else { return }
+
+ var entries: [LocalItemResolutionCacheEntry] = []
+ entries.append(contentsOf: prewarmEntries(
+ roots: options.applicationRoots,
+ allowedKinds: [.application],
+ maxItemsPerRoot: options.maxItemsPerRoot
+ ))
+ entries.append(contentsOf: prewarmEntries(
+ roots: options.fileRoots,
+ allowedKinds: [.folder, .file, .other],
+ maxItemsPerRoot: options.maxItemsPerRoot
+ ))
+ upsert(entries)
+ }
+
+ public func prewarmTaskDefinitions(_ definitions: [LocalAppTaskDefinition]) {
+ upsert(definitions.map(Self.entry(taskDefinition:)))
+ }
+
+ public func taskDefinitions() -> [LocalAppTaskDefinition] {
+ snapshotEntries()
+ .filter { $0.kind == Self.taskDefinitionKind && $0.isAvailable }
+ .compactMap(Self.taskDefinition(from:))
+ .sorted { lhs, rhs in
+ if lhs.taskType == rhs.taskType {
+ return lhs.targetApp.appName < rhs.targetApp.appName
+ }
+ return lhs.taskType < rhs.taskType
+ }
+ }
+
+ public func record(
+ availability: LocalAppAvailability,
+ query: String,
+ source: String
+ ) {
+ upsert([Self.entry(availability: availability, query: query, source: source)])
+ }
+
+ public func search(
+ query: String,
+ limit: Int = 5
+ ) -> [LocalItemResolutionCacheSearchResult] {
+ let lookupQuery = Self.lookupQuery(from: query)
+ guard !lookupQuery.isEmpty, limit > 0 else { return [] }
+
+ let snapshot = snapshotEntries()
+ guard !snapshot.isEmpty else { return [] }
+
+ let grepIDs = grepCandidateIDs(for: lookupQuery)
+ let grepCandidates: [LocalItemResolutionCacheEntry]
+ if let grepIDs, !grepIDs.isEmpty {
+ grepCandidates = snapshot.filter { grepIDs.contains($0.id) }
+ } else {
+ grepCandidates = snapshot
+ }
+
+ let scored = Self.scoredResults(
+ entries: grepCandidates,
+ query: lookupQuery
+ )
+ if !scored.isEmpty {
+ return Array(scored.prefix(limit))
+ }
+
+ return Array(Self.scoredResults(entries: snapshot, query: lookupQuery).prefix(limit))
+ }
+
+ public func contextSnippets(
+ for query: String,
+ limit: Int = 4
+ ) -> [String] {
+ search(query: query, limit: limit).map { result in
+ let entry = result.entry
+ let status = entry.isAvailable ? "available" : "missing"
+ let path = entry.path.map { " path=\($0)" } ?? ""
+ let bundleIdentifier = entry.bundleIdentifier.map { " bundleIdentifier=\($0)" } ?? ""
+ let metadata = Self.snippetMetadata(entry.metadata)
+ return "local_resolution_cache: query=\"\(entry.query)\" status=\(status) name=\"\(entry.displayName)\" kind=\(entry.kind)\(path)\(bundleIdentifier) source=\(entry.source) match=\(entry.match) score=\(result.score)\(metadata)"
+ }
+ }
+
+ func cachedAvailability(
+ named itemName: String,
+ preferredKind: LocalItemKind?
+ ) -> LocalAppAvailability? {
+ let requestedName = LocalAppLookup.cleanedLookupName(itemName)
+ guard !requestedName.isEmpty else { return nil }
+
+ guard let result = search(query: requestedName, limit: 8).first(where: { result in
+ guard result.entry.isAvailable else { return false }
+ guard result.entry.kind != Self.taskDefinitionKind else { return false }
+ if let preferredKind {
+ return result.entry.kind == preferredKind.rawValue
+ }
+ return true
+ }) else {
+ return nil
+ }
+
+ let entry = result.entry
+ let appURL = existingURL(for: entry)
+ guard appURL != nil || entry.bundleIdentifier != nil else { return nil }
+
+ var metadata = entry.metadata
+ metadata["provider"] = "local-resolution-cache"
+ metadata["cache.id"] = entry.id
+ metadata["cache.source"] = entry.source
+ metadata["cache.match"] = entry.match
+ metadata["cache.score"] = String(result.score)
+ metadata["requestedItemName"] = requestedName
+ metadata["itemKind"] = entry.kind
+ metadata["itemURL"] = appURL?.path ?? entry.path ?? ""
+ metadata["bundleIdentifier"] = entry.bundleIdentifier ?? metadata["bundleIdentifier"] ?? ""
+ metadata["match"] = "cache"
+
+ var targetMetadata = [
+ "localItem.kind": entry.kind,
+ "localItem.path": appURL?.path ?? entry.path ?? ""
+ ]
+ if let defaultApplication = metadata["defaultApplication"], !defaultApplication.isEmpty {
+ targetMetadata["localItem.defaultApplication"] = defaultApplication
+ }
+
+ markUsed(entryID: entry.id)
+
+ return LocalAppAvailability(
+ target: LocalAppTarget(
+ appName: entry.displayName,
+ bundleIdentifier: entry.bundleIdentifier,
+ titleContains: entry.displayName,
+ metadata: targetMetadata
+ ),
+ isInstalled: true,
+ appURL: appURL,
+ metadata: metadata
+ )
+ }
+
+ private func prewarmEntries(
+ roots: [URL],
+ allowedKinds: Set<LocalItemKind>,
+ maxItemsPerRoot: Int
+ ) -> [LocalItemResolutionCacheEntry] {
+ var entries: [LocalItemResolutionCacheEntry] = []
+ for root in roots where FileManager.default.fileExists(atPath: root.path) {
+ guard let enumerator = FileManager.default.enumerator(
+ at: root,
+ includingPropertiesForKeys: [.isDirectoryKey, .contentModificationDateKey],
+ options: [.skipsHiddenFiles, .skipsPackageDescendants]
+ ) else {
+ continue
+ }
+
+ var rootCount = 0
+ for case let itemURL as URL in enumerator {
+ let kind = LocalItemKind(url: itemURL)
+ guard allowedKinds.contains(kind) else { continue }
+
+ entries.append(Self.entry(
+ url: itemURL,
+ query: Self.displayName(for: itemURL, kind: kind),
+ kind: kind,
+ source: "prewarm",
+ match: "prewarm",
+ metadata: [
+ "prewarm.root": root.path,
+ "parentDirectory": itemURL.deletingLastPathComponent().lastPathComponent,
+ "fileExtension": itemURL.pathExtension
+ ]
+ ))
+ rootCount += 1
+ if rootCount >= maxItemsPerRoot { break }
+ }
+ }
+ return entries
+ }
+
+ private func upsert(_ entries: [LocalItemResolutionCacheEntry]) {
+ guard !entries.isEmpty else { return }
+
+ lock.lock()
+ for entry in entries {
+ if var existing = entriesByID[entry.id] {
+ existing.query = entry.query
+ existing.normalizedQuery = entry.normalizedQuery
+ existing.displayName = entry.displayName
+ existing.normalizedDisplayName = entry.normalizedDisplayName
+ existing.kind = entry.kind
+ existing.path = entry.path
+ existing.bundleIdentifier = entry.bundleIdentifier
+ existing.isAvailable = entry.isAvailable
+ existing.source = entry.source
+ existing.match = entry.match
+ existing.lastResolvedAt = entry.lastResolvedAt
+ existing.useCount += max(1, entry.useCount)
+ existing.metadata = existing.metadata.merging(entry.metadata) { _, new in new }
+ existing.searchText = entry.searchText
+ entriesByID[entry.id] = existing
+ } else {
+ entriesByID[entry.id] = entry
+ }
+ }
+ persistLocked()
+ lock.unlock()
+ }
+
+ private func markUsed(entryID: String) {
+ lock.lock()
+ if var entry = entriesByID[entryID] {
+ entry.useCount += 1
+ entry.lastResolvedAt = Self.timestamp()
+ entriesByID[entryID] = entry
+ persistLocked()
+ }
+ lock.unlock()
+ }
+
+ private func snapshotEntries() -> [LocalItemResolutionCacheEntry] {
+ lock.lock()
+ let entries = Array(entriesByID.values)
+ lock.unlock()
+ return entries
+ }
+
+ private func persistLocked() {
+ do {
+ try FileManager.default.createDirectory(
+ at: storeURL.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.sortedKeys]
+ let text = try entriesByID.values
+ .sorted { lhs, rhs in
+ if lhs.kind == rhs.kind {
+ return lhs.normalizedDisplayName < rhs.normalizedDisplayName
+ }
+ return lhs.kind < rhs.kind
+ }
+ .map { entry in
+ let data = try encoder.encode(entry)
+ return String(decoding: data, as: UTF8.self)
+ }
+ .joined(separator: "\n")
+ try (text + "\n").write(to: storeURL, atomically: true, encoding: .utf8)
+ } catch {
+ return
+ }
+ }
+
+ private func grepCandidateIDs(for query: String) -> Set<String>? {
+ guard FileManager.default.fileExists(atPath: storeURL.path) else { return nil }
+
+ let token = query
+ .components(separatedBy: .whitespacesAndNewlines)
+ .filter { !$0.isEmpty }
+ .max(by: { $0.count < $1.count })
+ ?? query
+ guard !token.isEmpty else { return nil }
+
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/grep")
+ process.arguments = ["-i", "-F", token, storeURL.path]
+
+ let output = Pipe()
+ process.standardOutput = output
+ process.standardError = Pipe()
+
+ do {
+ try process.run()
+ } catch {
+ return nil
+ }
+ process.waitUntilExit()
+
+ let data = output.fileHandleForReading.readDataToEndOfFile()
+ guard let text = String(data: data, encoding: .utf8) else { return nil }
+
+ let decoder = JSONDecoder()
+ return Set(text.split(whereSeparator: \.isNewline).compactMap { line in
+ try? decoder.decode(LocalItemResolutionCacheEntry.self, from: Data(line.utf8)).id
+ })
+ }
+
+ private func existingURL(for entry: LocalItemResolutionCacheEntry) -> URL? {
+ if let path = entry.path {
+ let url = URL(fileURLWithPath: path)
+ if FileManager.default.fileExists(atPath: url.path) {
+ return url
+ }
+ }
+
+ guard let bundleIdentifier = entry.bundleIdentifier else { return nil }
+ return NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier)
+ }
+
+ private func finishPrewarming() {
+ lock.lock()
+ isPrewarming = false
+ lock.unlock()
+ }
+
+ private static func scoredResults(
+ entries: [LocalItemResolutionCacheEntry],
+ query: String
+ ) -> [LocalItemResolutionCacheSearchResult] {
+ let tokens = Set(query.split(separator: " ").map(String.init))
+ return entries
+ .compactMap { entry -> LocalItemResolutionCacheSearchResult? in
+ guard let score = score(entry: entry, query: query, tokens: tokens) else {
+ return nil
+ }
+ return LocalItemResolutionCacheSearchResult(entry: entry, score: score)
+ }
+ .sorted { lhs, rhs in
+ if lhs.score == rhs.score {
+ if lhs.entry.isAvailable == rhs.entry.isAvailable {
+ return lhs.entry.useCount > rhs.entry.useCount
+ }
+ return lhs.entry.isAvailable && !rhs.entry.isAvailable
+ }
+ return lhs.score < rhs.score
+ }
+ }
+
+ private static func score(
+ entry: LocalItemResolutionCacheEntry,
+ query: String,
+ tokens: Set<String>
+ ) -> Int? {
+ let normalizedDisplayName = entry.normalizedDisplayName
+ let normalizedQuery = entry.normalizedQuery
+ let searchText = LocalAppLookup.normalized(entry.searchText)
+
+ if normalizedDisplayName == query || normalizedQuery == query {
+ return entry.isAvailable ? 0 : 30
+ }
+ if normalizedDisplayName.hasPrefix(query) {
+ return entry.isAvailable ? 4 : 34
+ }
+ if normalizedDisplayName.contains(" \(query)") || normalizedDisplayName.contains(query) {
+ return entry.isAvailable ? 8 : 38
+ }
+
+ let matchedTokenCount = tokens.filter { searchText.contains($0) }.count
+ guard matchedTokenCount > 0 else { return nil }
+
+ let missingPenalty = entry.isAvailable ? 0 : 40
+ return missingPenalty + 60 - min(30, matchedTokenCount * 10) + max(0, normalizedDisplayName.count - query.count)
+ }
+
+ private static func entry(
+ availability: LocalAppAvailability,
+ query: String,
+ source: String
+ ) -> LocalItemResolutionCacheEntry {
+ let kind = availability.metadata["itemKind"]
+ ?? availability.target.metadata["localItem.kind"]
+ ?? (availability.target.bundleIdentifier == nil ? "unknown" : LocalItemKind.application.rawValue)
+ let path = availability.metadata["itemURL"]
+ ?? availability.target.metadata["localItem.path"]
+ ?? availability.appURL?.path
+ let bundleIdentifier = availability.metadata["bundleIdentifier"]
+ ?? availability.target.bundleIdentifier
+ let displayName = availability.target.appName
+ let match = availability.metadata["match"]
+ ?? availability.metadata["reason"]
+ ?? (availability.isInstalled ? "resolved" : "missing")
+
+ var metadata = availability.metadata
+ metadata["recordedQuery"] = query
+
+ return LocalItemResolutionCacheEntry(
+ id: id(
+ kind: kind,
+ path: path,
+ bundleIdentifier: bundleIdentifier,
+ displayName: displayName,
+ query: query,
+ isAvailable: availability.isInstalled
+ ),
+ query: query,
+ normalizedQuery: lookupQuery(from: query),
+ displayName: displayName,
+ normalizedDisplayName: LocalAppLookup.normalized(displayName),
+ kind: kind,
+ path: path?.isEmpty == false ? path : nil,
+ bundleIdentifier: bundleIdentifier?.isEmpty == false ? bundleIdentifier : nil,
+ isAvailable: availability.isInstalled,
+ source: source,
+ match: match,
+ firstResolvedAt: timestamp(),
+ lastResolvedAt: timestamp(),
+ useCount: 1,
+ metadata: metadata,
+ searchText: searchText(
+ query: query,
+ displayName: displayName,
+ kind: kind,
+ path: path,
+ bundleIdentifier: bundleIdentifier,
+ metadata: metadata
+ )
+ )
+ }
+
+ private static func entry(
+ url: URL,
+ query: String,
+ kind: LocalItemKind,
+ source: String,
+ match: String,
+ metadata: [String: String]
+ ) -> LocalItemResolutionCacheEntry {
+ let displayName = displayName(for: url, kind: kind)
+ let bundleIdentifier = kind == .application ? Bundle(url: url)?.bundleIdentifier : nil
+ var entryMetadata = metadata
+ entryMetadata["itemKind"] = kind.rawValue
+ entryMetadata["itemURL"] = url.path
+ entryMetadata["bundleIdentifier"] = bundleIdentifier ?? ""
+
+ return LocalItemResolutionCacheEntry(
+ id: id(
+ kind: kind.rawValue,
+ path: url.path,
+ bundleIdentifier: bundleIdentifier,
+ displayName: displayName,
+ query: query,
+ isAvailable: true
+ ),
+ query: query,
+ normalizedQuery: lookupQuery(from: query),
+ displayName: displayName,
+ normalizedDisplayName: LocalAppLookup.normalized(displayName),
+ kind: kind.rawValue,
+ path: url.path,
+ bundleIdentifier: bundleIdentifier,
+ isAvailable: true,
+ source: source,
+ match: match,
+ firstResolvedAt: timestamp(),
+ lastResolvedAt: timestamp(),
+ useCount: 1,
+ metadata: entryMetadata,
+ searchText: searchText(
+ query: query,
+ displayName: displayName,
+ kind: kind.rawValue,
+ path: url.path,
+ bundleIdentifier: bundleIdentifier,
+ metadata: entryMetadata
+ )
+ )
+ }
+
+ private static func entry(taskDefinition definition: LocalAppTaskDefinition) -> LocalItemResolutionCacheEntry {
+ let entityText = definition.entityRules
+ .map(\.name)
+ .joined(separator: " ")
+ let workflowText = definition.workflowSteps
+ .flatMap { step in [step.id, step.role.rawValue, step.summary] + step.metadata.flatMap { [$0.key, $0.value] } }
+ .joined(separator: " ")
+ var metadata = definition.metadata
+ metadata["taskType"] = definition.taskType
+ metadata["targetApp"] = definition.targetApp.appName
+ metadata["bundleIdentifier"] = definition.targetApp.bundleIdentifier ?? ""
+ metadata["entityNames"] = definition.entityRules.map(\.name).joined(separator: ",")
+ metadata["observationStrategies"] = definition.observationStrategies.map(\.rawValue).joined(separator: ",")
+ metadata["verificationEntityName"] = definition.verificationEntityName ?? ""
+
+ if let encodedDefinition = encodedTaskDefinition(definition) {
+ metadata[Self.taskDefinitionJSONMetadataKey] = encodedDefinition
+ }
+
+ return LocalItemResolutionCacheEntry(
+ id: "task-definition:\(definition.taskType)",
+ query: definition.taskType,
+ normalizedQuery: lookupQuery(from: definition.taskType),
+ displayName: Self.displayTitle(for: definition),
+ normalizedDisplayName: LocalAppLookup.normalized(Self.displayTitle(for: definition)),
+ kind: Self.taskDefinitionKind,
+ path: nil,
+ bundleIdentifier: definition.targetApp.bundleIdentifier,
+ isAvailable: true,
+ source: "task-definition-prewarm",
+ match: "capability",
+ firstResolvedAt: timestamp(),
+ lastResolvedAt: timestamp(),
+ useCount: 1,
+ metadata: metadata,
+ searchText: searchText(
+ query: definition.taskType,
+ displayName: Self.displayTitle(for: definition),
+ kind: Self.taskDefinitionKind,
+ path: nil,
+ bundleIdentifier: definition.targetApp.bundleIdentifier,
+ metadata: metadata.merging([
+ "taskText": "\(definition.taskType) \(entityText) \(workflowText)",
+ "targetAppTitle": definition.targetApp.titleContains ?? definition.targetApp.appName
+ ]) { current, _ in current }
+ )
+ )
+ }
+
+ private static func encodedTaskDefinition(_ definition: LocalAppTaskDefinition) -> String? {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.sortedKeys]
+ guard let data = try? encoder.encode(definition) else { return nil }
+ return String(data: data, encoding: .utf8)
+ }
+
+ private static func taskDefinition(from entry: LocalItemResolutionCacheEntry) -> LocalAppTaskDefinition? {
+ guard let encodedDefinition = entry.metadata[taskDefinitionJSONMetadataKey],
+ let data = encodedDefinition.data(using: .utf8)
+ else {
+ return nil
+ }
+ return try? JSONDecoder().decode(LocalAppTaskDefinition.self, from: data)
+ }
+
+ private static func loadEntries(from storeURL: URL) -> [String: LocalItemResolutionCacheEntry] {
+ guard let text = try? String(contentsOf: storeURL, encoding: .utf8) else { return [:] }
+
+ let decoder = JSONDecoder()
+ let entries = text
+ .split(whereSeparator: \.isNewline)
+ .compactMap { line in
+ try? decoder.decode(LocalItemResolutionCacheEntry.self, from: Data(line.utf8))
+ }
+ return Dictionary(uniqueKeysWithValues: entries.map { ($0.id, $0) })
+ }
+
+ private static func id(
+ kind: String,
+ path: String?,
+ bundleIdentifier: String?,
+ displayName: String,
+ query: String,
+ isAvailable: Bool
+ ) -> String {
+ if !isAvailable {
+ return "missing:\(lookupQuery(from: query))"
+ }
+ if let bundleIdentifier, !bundleIdentifier.isEmpty {
+ return "\(kind):bundle:\(bundleIdentifier)"
+ }
+ if let path, !path.isEmpty {
+ return "\(kind):path:\(path)"
+ }
+ return "\(kind):name:\(LocalAppLookup.normalized(displayName))"
+ }
+
+ private static func searchText(
+ query: String,
+ displayName: String,
+ kind: String,
+ path: String?,
+ bundleIdentifier: String?,
+ metadata: [String: String]
+ ) -> String {
+ (
+ [
+ query,
+ displayName,
+ LocalAppLookup.normalized(displayName),
+ kind,
+ path ?? "",
+ bundleIdentifier ?? ""
+ ] + metadata
+ .filter { $0.key != Self.taskDefinitionJSONMetadataKey }
+ .sorted { $0.key < $1.key }
+ .flatMap { [$0.key, $0.value] }
+ )
+ .filter { !$0.isEmpty }
+ .joined(separator: " ")
+ }
+
+ private static func snippetMetadata(_ metadata: [String: String]) -> String {
+ let allowedKeys = [
+ "taskType",
+ "targetApp",
+ "itemKind",
+ "defaultApplication",
+ "entityNames",
+ "verificationMode",
+ "automationBackend",
+ "appleScript.action",
+ "screenshotFallback"
+ ]
+ let pairs = allowedKeys.compactMap { key -> String? in
+ guard let value = metadata[key], !value.isEmpty else { return nil }
+ return "\(key)=\(value)"
+ }
+ guard !pairs.isEmpty else { return "" }
+ return " metadata={\(pairs.joined(separator: ","))}"
+ }
+
+ private static func lookupQuery(from query: String) -> String {
+ LocalAppLookup.cleanedLookupName(query)
+ }
+
+ private static let taskDefinitionKind = "taskDefinition"
+ private static let taskDefinitionJSONMetadataKey = "taskDefinitionJSON"
+
+ private static func displayName(for url: URL, kind: LocalItemKind) -> String {
+ if kind == .application,
+ let bundle = Bundle(url: url) {
+ return bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
+ ?? bundle.object(forInfoDictionaryKey: "CFBundleName") as? String
+ ?? url.deletingPathExtension().lastPathComponent
+ }
+
+ return url.lastPathComponent
+ }
+
+ private static func displayTitle(for definition: LocalAppTaskDefinition) -> String {
+ if let displayTitle = definition.metadata["displayTitle"], !displayTitle.isEmpty {
+ return displayTitle
+ }
+ return definition.taskType
+ .split(separator: "_")
+ .map { word in word.prefix(1).uppercased() + word.dropFirst() }
+ .joined(separator: " ")
+ }
+
+ private static func timestamp() -> String {
+ ISO8601DateFormatter().string(from: Date())
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
index 5bcf3a7a..45c50284 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
@@ -303,59 +303,13 @@ public struct MacAccessibilityNativeDialogDetector: Sendable {
public func safetyAssessment(
for snapshot: MacAccessibilitySnapshot
) -> WindowTargetSafetyAssessment? {
- guard let dialogText = dialogTexts(in: snapshot.root).first else {
+ guard dialogTexts(in: snapshot.root).first != nil else {
return nil
}
- var reasons: [WindowTargetSafetyReason] = [.systemSurface]
- let haystack = dialogText.lowercased()
-
- if containsAny(haystack, [
- "permission",
- "privacy",
- "accessibility",
- "screen recording",
- "allow",
- "deny"
- ]) {
- reasons.append(.permissionSurface)
- }
-
- if containsAny(haystack, [
- "sign in",
- "signin",
- "sign-in",
- "log in",
- "login",
- "authentication",
- "unlock"
- ]) {
- reasons.append(.loginSurface)
- }
-
- if containsAny(haystack, [
- "password",
- "passcode",
- "credential",
- "keychain"
- ]) {
- reasons.append(.passwordSurface)
- }
-
- if containsAny(haystack, [
- "payment",
- "checkout",
- "billing",
- "credit card",
- "apple pay",
- "purchase"
- ]) {
- reasons.append(.paymentSurface)
- }
-
return WindowTargetSafetyAssessment(
status: .blocked,
- reasons: reasons.uniqued(),
+ reasons: [.systemSurface],
summary: "Native macOS dialog detected in Accessibility tree"
)
}
@@ -369,7 +323,7 @@ public struct MacAccessibilityNativeDialogDetector: Sendable {
.filter { !$0.isEmpty }
.joined(separator: " ")
- if isDialogRole(node.role) || isDialogText(combined) {
+ if isDialogRole(node.role) {
return [combined]
}
@@ -384,19 +338,6 @@ public struct MacAccessibilityNativeDialogDetector: Sendable {
|| role == "AXPopover"
}
- private func isDialogText(_ text: String) -> Bool {
- let normalized = text.lowercased()
- return normalized.contains("system dialog")
- || normalized.contains("permission")
- || normalized.contains("wants to access")
- || normalized.contains("would like to access")
- || normalized.contains("screen recording")
- || normalized.contains("accessibility")
- }
-
- private func containsAny(_ value: String, _ needles: [String]) -> Bool {
- needles.contains { value.contains($0) }
- }
}
final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilitySnapshotCapturing {
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift
new file mode 100644
index 00000000..4762a226
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift
@@ -0,0 +1,279 @@
+import DonkeyContracts
+import Foundation
+
+public struct AppleScriptExecutionResult: Equatable, Sendable {
+ public var succeeded: Bool
+ public var output: String
+ public var error: String?
+
+ public init(
+ succeeded: Bool,
+ output: String = "",
+ error: String? = nil
+ ) {
+ self.succeeded = succeeded
+ self.output = output
+ self.error = error
+ }
+}
+
+public protocol AppleScriptRunning: Sendable {
+ func run(_ script: String) async -> AppleScriptExecutionResult
+}
+
+public struct NSAppleScriptRunner: AppleScriptRunning {
+ public init() {}
+
+ public func run(_ script: String) async -> AppleScriptExecutionResult {
+ await MainActor.run {
+ var error: NSDictionary?
+ guard let appleScript = NSAppleScript(source: script) else {
+ return AppleScriptExecutionResult(
+ succeeded: false,
+ error: "AppleScript source could not be compiled"
+ )
+ }
+
+ let descriptor = appleScript.executeAndReturnError(&error)
+ if let error {
+ return AppleScriptExecutionResult(
+ succeeded: false,
+ error: String(describing: error)
+ )
+ }
+
+ return AppleScriptExecutionResult(
+ succeeded: true,
+ output: descriptor.stringValue ?? ""
+ )
+ }
+ }
+}
+
+public struct MacAppleScriptActionEngineInputBackend: ActionEngineInputBackend {
+ private let runner: any AppleScriptRunning
+
+ public init(runner: any AppleScriptRunning = NSAppleScriptRunner()) {
+ self.runner = runner
+ }
+
+ public func execute(_ command: ActionEngineCommand) async -> ActionEngineInputBackendResult {
+ guard command.kind == .controller else {
+ return result(
+ command: command,
+ executed: false,
+ metadata: [
+ "liveInputBackend": "mac-apple-script",
+ "reason": "unsupportedCommandKind"
+ ]
+ )
+ }
+
+ guard command.metadata["automationBackend"] == "appleScript" else {
+ return result(
+ command: command,
+ executed: false,
+ metadata: [
+ "liveInputBackend": "mac-apple-script",
+ "reason": "missingAppleScriptBackendMarker"
+ ]
+ )
+ }
+
+ guard let generatedScript = AppleScriptActionScriptGenerator.script(for: command) else {
+ return result(
+ command: command,
+ executed: false,
+ metadata: [
+ "liveInputBackend": "mac-apple-script",
+ "reason": "unsupportedAppleScriptAction",
+ "appleScript.action": command.metadata["appleScript.action"] ?? ""
+ ]
+ )
+ }
+
+ let execution = await runner.run(generatedScript.source)
+ let output = execution.output.trimmingCharacters(in: .whitespacesAndNewlines)
+ let acceptedOutputs = Self.acceptedOutputs(for: command)
+ let executed = execution.succeeded && (
+ acceptedOutputs.isEmpty || acceptedOutputs.contains(output)
+ )
+
+ return result(
+ command: command,
+ executed: executed,
+ metadata: [
+ "liveInputBackend": "mac-apple-script",
+ "appleScript.action": generatedScript.action,
+ "appleScript.scriptKind": generatedScript.kind,
+ "appleScript.output": output,
+ "appleScript.error": execution.error ?? "",
+ "appleScript.query": command.metadata["appleScript.query"] ?? command.key ?? ""
+ ]
+ )
+ }
+
+ private func result(
+ command: ActionEngineCommand,
+ executed: Bool,
+ metadata: [String: String]
+ ) -> ActionEngineInputBackendResult {
+ ActionEngineInputBackendResult(
+ executed: executed,
+ completedAt: Self.now(),
+ metadata: metadata
+ )
+ }
+
+ static func musicPlaybackScript(query: String) -> String {
+ AppleScriptActionScriptGenerator.musicPlaybackScript(query: query)
+ }
+
+ private static func acceptedOutputs(for command: ActionEngineCommand) -> Set<String> {
+ if let explicitOutputs = command.metadata["appleScript.successOutputs"] {
+ return Set(explicitOutputs
+ .split(separator: ",")
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty })
+ }
+
+ if command.metadata["appleScript.action"] == "music.playMediaQuery" {
+ return [
+ "played-library-track",
+ "searched-ui-first-result"
+ ]
+ }
+
+ return []
+ }
+
+ private static func now() -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(),
+ monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)
+ )
+ }
+}
+
+struct AppleScriptActionScript: Equatable, Sendable {
+ var action: String
+ var kind: String
+ var source: String
+}
+
+enum AppleScriptActionScriptGenerator {
+ static func script(for command: ActionEngineCommand) -> AppleScriptActionScript? {
+ let action = command.metadata["appleScript.action"] ?? "generated"
+ let query = command.metadata["appleScript.query"]
+ ?? command.metadata["appleScript.entityValue"]
+ ?? command.key
+ ?? ""
+
+ if let source = nonEmpty(command.metadata["appleScript.source"]) {
+ return AppleScriptActionScript(
+ action: action,
+ kind: "source",
+ source: source
+ )
+ }
+
+ if let template = nonEmpty(command.metadata["appleScript.template"]) {
+ return AppleScriptActionScript(
+ action: action,
+ kind: "template",
+ source: renderTemplate(
+ template,
+ command: command,
+ query: query
+ )
+ )
+ }
+
+ if action == "music.playMediaQuery",
+ !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ return AppleScriptActionScript(
+ action: action,
+ kind: "builtInAction",
+ source: musicPlaybackScript(query: query)
+ )
+ }
+
+ return nil
+ }
+
+ static func musicPlaybackScript(query: String) -> String {
+ let escapedQuery = appleScriptStringLiteral(query)
+ return """
+ set donkeyQuery to \(escapedQuery)
+ tell application "Music"
+ activate
+ delay 0.1
+ try
+ set donkeyMatches to search library playlist 1 for donkeyQuery only songs
+ if (count of donkeyMatches) > 0 then
+ play item 1 of donkeyMatches
+ return "played-library-track"
+ end if
+ end try
+ end tell
+ try
+ tell application "System Events"
+ tell process "Music"
+ set frontmost to true
+ keystroke "f" using command down
+ delay 0.12
+ keystroke donkeyQuery
+ delay 0.12
+ key code 36
+ delay 0.25
+ key code 36
+ end tell
+ end tell
+ return "searched-ui-first-result"
+ on error donkeyFallbackError
+ return "ui-search-error:" & donkeyFallbackError
+ end try
+ """
+ }
+
+ private static func renderTemplate(
+ _ template: String,
+ command: ActionEngineCommand,
+ query: String
+ ) -> String {
+ let targetApp = command.metadata["targetApp"] ?? ""
+ let bundleIdentifier = command.metadata["bundleIdentifier"] ?? ""
+ let replacements = [
+ "{query}": appleScriptStringLiteral(query),
+ "{queryLiteral}": appleScriptStringLiteral(query),
+ "{rawQuery}": query,
+ "{entityValue}": appleScriptStringLiteral(command.metadata["appleScript.entityValue"] ?? query),
+ "{rawEntityValue}": command.metadata["appleScript.entityValue"] ?? query,
+ "{targetApp}": appleScriptStringLiteral(targetApp),
+ "{rawTargetApp}": targetApp,
+ "{bundleIdentifier}": appleScriptStringLiteral(bundleIdentifier),
+ "{rawBundleIdentifier}": bundleIdentifier
+ ]
+ return replacements.reduce(template) { partial, item in
+ partial.replacingOccurrences(of: item.key, with: item.value)
+ }
+ }
+
+ private static func nonEmpty(_ value: String?) -> String? {
+ guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !trimmed.isEmpty
+ else {
+ return nil
+ }
+ return value
+ }
+
+ private static func appleScriptStringLiteral(_ value: String) -> String {
+ let escaped = value
+ .replacingOccurrences(of: "\\", with: "\\\\")
+ .replacingOccurrences(of: "\"", with: "\\\"")
+ .replacingOccurrences(of: "\r", with: " ")
+ .replacingOccurrences(of: "\n", with: " ")
+ return "\"\(escaped)\""
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index ca960dc5..a3046ac1 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -351,7 +351,7 @@ struct AIHarnessAdapterTests {
let result = await adapter.parseTaskIntent(
TaskIntentAdapterRequest(
command: "show me the weather for SF",
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
sourceTraceID: "trace-intent"
)
)
@@ -401,7 +401,7 @@ struct AIHarnessAdapterTests {
let result = await adapter.parseTaskIntent(
TaskIntentAdapterRequest(
command: "play cold play",
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
sourceTraceID: "trace-local-llm"
)
)
@@ -427,7 +427,7 @@ struct AIHarnessAdapterTests {
)
let resolver = LocalModelTaskIntentResolver(
catalog: LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])
),
adapter: OllamaTaskIntentAdapter(
@@ -461,10 +461,59 @@ struct AIHarnessAdapterTests {
}
@Test
- func localModelTaskIntentResolverFallsBackToDeterministicParserWhenRuntimeUnavailable() async {
+ func localModelTaskIntentResolverResolvesDynamicLocalItemLookup() async {
+ let httpClient = FakeAIHTTPClient(
+ data: ollamaResponseData(
+ response: """
+ {"taskType":"app_open","targetAppName":"Figma","entities":{"appName":"figma"},"normalizedEntities":{"appName":"Figma"},"confidence":0.94,"needsConfirmation":false,"metadata":{}}
+ """
+ ),
+ statusCode: 200
+ )
let resolver = LocalModelTaskIntentResolver(
catalog: LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(
+ installedBundleIdentifiers: ["com.figma.Desktop"],
+ installedApplicationNames: ["Figma": "com.figma.Desktop"]
+ )
+ ),
+ adapter: OllamaTaskIntentAdapter(
+ router: AIModelRouter(
+ registry: AIModelRegistry(
+ entries: [
+ entry(
+ id: "local-intent",
+ role: .taskIntent,
+ provider: .ollama,
+ modelID: "qwen3:8b",
+ endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,
+ promptVersion: "task-intent-v1"
+ )
+ ]
+ )
+ ),
+ httpClient: httpClient
+ )
+ )
+
+ let result = await resolver.resolve(
+ command: "open figma",
+ sourceTraceID: "trace-resolve-local-item"
+ )
+
+ #expect(result.resolution.status == .resolved)
+ #expect(result.resolution.definition?.taskType == "app_open")
+ #expect(result.resolution.intent?.targetApp.appName == "Figma")
+ #expect(result.resolution.intent?.normalizedEntities["appName"] == "Figma")
+ #expect(result.resolution.metadata["lookupProvider"] == "static")
+ }
+
+ @Test
+ func localModelTaskIntentResolverDoesNotParseCommandTextWhenRuntimeUnavailable() async {
+ let resolver = LocalModelTaskIntentResolver(
+ catalog: LocalAppTaskCatalog(
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])
),
adapter: UnavailableTaskIntentAdapter()
@@ -475,18 +524,19 @@ struct AIHarnessAdapterTests {
sourceTraceID: "trace-resolve-fallback"
)
- #expect(result.resolution.status == .resolved)
- #expect(result.resolution.intent?.parserSource == .deterministic)
- #expect(result.resolution.intent?.normalizedEntities["city"] == "San Francisco")
- #expect(result.trace.validationStatus == "deterministicFallback")
- #expect(result.trace.metadata["fallback.reason"] == "localModelIntentUnavailable")
+ #expect(result.resolution.status == .needsConfirmation)
+ #expect(result.resolution.intent == nil)
+ #expect(result.resolution.metadata["reason"] == "localModelIntentUnavailable")
+ #expect(result.resolution.metadata["modelCallStatus"] == "providerOutage")
+ #expect(result.trace.validationStatus == "notValidated")
+ #expect(result.trace.metadata["fallback.reason"] == nil)
}
@Test
func localModelTaskIntentResolverAsksForDetailsInsteadOfUnsupportedWhenRuntimeUnavailable() async {
let resolver = LocalModelTaskIntentResolver(
catalog: LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])
),
adapter: UnavailableTaskIntentAdapter()
@@ -514,7 +564,7 @@ struct AIHarnessAdapterTests {
)
let resolver = LocalModelTaskIntentResolver(
catalog: LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])
),
adapter: OllamaTaskIntentAdapter(
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift
index d51c7256..9a242981 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift
@@ -5,22 +5,66 @@ import Testing
@Suite
struct AppHarnessTurnRouterTests {
@Test
- func greetingRoutesToConversationWithoutTaskExecution() {
+ func greetingDefersToModelIntentClassifierWithoutWordScanning() {
let result = router().route(
request: AppHarnessTurnRequest(
- turn: AppHarnessTurn(text: "hi", source: .typedPrompt)
+ turn: AppHarnessTurn(text: "hi there", source: .typedPrompt)
),
traceID: "trace-chat"
)
- #expect(result.outcome.decision.kind == .respond)
+ #expect(result.outcome.decision.kind == .runLocalTask)
#expect(result.outcome.decision.traceID == "trace-chat")
- #expect(result.outcome.resolution == nil)
- #expect(result.outcome.assistantResponse?.contains("local app task") == true)
+ #expect(result.outcome.metadata["router"] == "modelIntent")
+ #expect(result.outcome.resolution?.status == .unsupportedCommand)
+ #expect(result.outcome.resolution?.metadata["reason"] == "modelIntentRequired")
+ #expect(result.outcome.assistantResponse == nil)
+ }
+
+ @Test
+ func simpleArithmeticRoutesToLocalAnswerWithoutCommandWords() {
+ let result = router().route(
+ request: AppHarnessTurnRequest(
+ turn: AppHarnessTurn(text: "What is 2+2?", source: .typedPrompt)
+ ),
+ traceID: "trace-math"
+ )
+
+ #expect(result.outcome.decision.kind == .respond)
+ #expect(result.outcome.metadata["router"] == "simpleArithmetic")
+ #expect(result.outcome.assistantResponse == "2 + 2 = 4.")
+ }
+
+ @Test
+ func openMusicDefersToModelIntentRouting() {
+ let result = router().route(
+ request: AppHarnessTurnRequest(
+ turn: AppHarnessTurn(text: "open music", source: .typedPrompt)
+ ),
+ traceID: "trace-open-music"
+ )
+
+ #expect(result.outcome.decision.kind == .runLocalTask)
+ #expect(result.outcome.metadata["router"] == "modelIntent")
+ #expect(result.outcome.resolution?.status == .unsupportedCommand)
}
@Test
- func actionableWeatherRequestRoutesThroughCatalog() {
+ func missingAppOpenDefersToModelIntentRouting() {
+ let result = router().route(
+ request: AppHarnessTurnRequest(
+ turn: AppHarnessTurn(text: "open Imaginary App", source: .typedPrompt)
+ ),
+ traceID: "trace-missing-app"
+ )
+
+ #expect(result.outcome.decision.kind == .runLocalTask)
+ #expect(result.outcome.metadata["router"] == "modelIntent")
+ #expect(result.outcome.resolution?.status == .unsupportedCommand)
+ }
+
+ @Test
+ func actionableWeatherRequestDefersToModelIntentRouting() {
let result = router().route(
request: AppHarnessTurnRequest(
turn: AppHarnessTurn(text: "show me the weather for SF", source: .typedPrompt)
@@ -29,9 +73,9 @@ struct AppHarnessTurnRouterTests {
)
#expect(result.outcome.decision.kind == .runLocalTask)
- #expect(result.outcome.decision.taskIntentID == result.outcome.resolution?.intent?.intentID)
- #expect(result.outcome.resolution?.status == .resolved)
- #expect(result.outcome.resolution?.intent?.normalizedEntities["city"] == "San Francisco")
+ #expect(result.outcome.metadata["router"] == "modelIntent")
+ #expect(result.outcome.resolution?.status == .unsupportedCommand)
+ #expect(result.outcome.resolution?.metadata["reason"] == "modelIntentRequired")
}
@Test
@@ -45,12 +89,12 @@ struct AppHarnessTurnRouterTests {
#expect(result.contextPacket.currentTurn.source == .voiceTranscript)
#expect(result.outcome.decision.kind == .runLocalTask)
- #expect(result.outcome.resolution?.status == .resolved)
- #expect(result.outcome.resolution?.intent?.normalizedEntities["city"] == "San Francisco")
+ #expect(result.outcome.metadata["router"] == "modelIntent")
+ #expect(result.outcome.resolution?.status == .unsupportedCommand)
}
@Test
- func ambiguousWeatherRequestAsksForSpecificMissingDetail() {
+ func ambiguousWeatherRequestAlsoRequiresModelIntent() {
let result = router().route(
request: AppHarnessTurnRequest(
turn: AppHarnessTurn(text: "show weather", source: .typedPrompt)
@@ -58,10 +102,10 @@ struct AppHarnessTurnRouterTests {
traceID: "trace-clarify"
)
- #expect(result.outcome.decision.kind == .askClarification)
- #expect(result.outcome.decision.missingDetail == "city")
- #expect(result.outcome.missingDetail == "city")
- #expect(result.outcome.assistantResponse == "Which city should I use?")
+ #expect(result.outcome.decision.kind == .runLocalTask)
+ #expect(result.outcome.metadata["router"] == "modelIntent")
+ #expect(result.outcome.resolution?.status == .unsupportedCommand)
+ #expect(result.outcome.resolution?.metadata["reason"] == "modelIntentRequired")
}
@Test
@@ -141,7 +185,7 @@ struct AppHarnessTurnRouterTests {
}
@Test
- func contextCompactionDropsTransientCorrectionsBeforeDurableEvents() {
+ func contextCompactionDoesNotInferTransientCorrectionsFromText() {
let limits = AppHarnessContextPacketLimits(
maxRecentEvents: 2,
maxAssets: 0,
@@ -178,9 +222,9 @@ struct AppHarnessTurnRouterTests {
)
#expect(result.contextPacket.recentEvents.map(\.sequence) == [2, 3])
- #expect(result.contextPacket.metadata["events.droppedTransientCorrectionCount"] == "1")
+ #expect(result.contextPacket.metadata["events.droppedTransientCorrectionCount"] == "0")
#expect(result.contextPacket.compactionRecords.contains {
- $0.itemKind == .transientCorrection && $0.droppedCount == 1
+ $0.itemKind == .transientCorrection && $0.droppedCount == 0
})
}
@@ -189,7 +233,7 @@ struct AppHarnessTurnRouterTests {
) -> AppHarnessTurnRouter {
AppHarnessTurnRouter(
catalog: LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
availabilityProvider: StaticLocalAppAvailabilityProvider(
installedBundleIdentifiers: [
"com.apple.weather",
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
index 30bdc977..0d36d203 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
@@ -6,24 +6,23 @@ import Testing
@Suite
struct LocalAppTaskTests {
@Test
- func deterministicParserBuildsGenericTaskIntentWithAliasExpansion() throws {
- let intent = try #require(parser().parse("show me the weather for SF"))
+ func structuredWeatherIntentCarriesModelSelectedEntities() throws {
+ let intent = weatherIntent(rawCity: "SF", city: "San Francisco")
#expect(intent.taskType == "weather_lookup")
#expect(intent.targetApp.appName == "Weather")
#expect(intent.targetApp.bundleIdentifier == "com.apple.weather")
- #expect(intent.entities["city"] == "sf")
+ #expect(intent.entities["city"] == "SF")
#expect(intent.normalizedEntities["city"] == "San Francisco")
- #expect(intent.confidence == 0.96)
- #expect(intent.parserSource == .deterministic)
+ #expect(intent.confidence == 0.93)
+ #expect(intent.parserSource == .localModel)
#expect(intent.needsConfirmation == false)
#expect(intent.metadata["catalogEntry"] == "built-in-weather-lookup")
- #expect(intent.metadata["entityAliasExpanded"] == "true")
}
@Test
- func deterministicParserBuildsMediaPlaybackIntentWithoutWeatherSpecificCode() throws {
- let intent = try #require(parser().parse("play cold play"))
+ func structuredMediaPlaybackIntentCarriesModelSelectedEntities() throws {
+ let intent = mediaPlaybackIntent(rawQuery: "cold play", query: "Coldplay")
#expect(intent.taskType == "media_playback")
#expect(intent.targetApp.appName == "Music")
@@ -34,8 +33,76 @@ struct LocalAppTaskTests {
}
@Test
- func deterministicParserBuildsDocumentFormFillIntentAsReviewOnlyTask() throws {
- let intent = try #require(parser().parse("fill out this PDF using this data"))
+ func catalogResolvesGenericAppOpenIntentFromModelSelectedLocalItem() throws {
+ let catalog = LocalAppTaskCatalog(
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(
+ installedBundleIdentifiers: ["com.figma.Desktop"],
+ installedApplicationNames: ["Figma": "com.figma.Desktop"],
+ installedLocalItemNames: ["Quarterly Plan.pdf": "file"]
+ )
+ )
+ let resolution = catalog.resolve(intent: TaskIntent(
+ intentID: "app_open-figma",
+ taskType: "app_open",
+ targetApp: LocalAppTarget(appName: "Local Item", metadata: ["dynamicTarget": "true"]),
+ entities: ["appName": "figma"],
+ normalizedEntities: ["appName": "Figma"],
+ confidence: 0.91,
+ parserSource: .localModel,
+ metadata: ["requestedItemName": "figma"]
+ ))
+ let intent = try #require(resolution.intent)
+
+ #expect(resolution.status == .resolved)
+ #expect(intent.taskType == "app_open")
+ #expect(intent.targetApp.appName == "Figma")
+ #expect(intent.targetApp.bundleIdentifier == "com.figma.Desktop")
+ #expect(intent.normalizedEntities["appName"] == "Figma")
+ #expect(intent.metadata["catalogEntry"] == "generic-app-open")
+
+ let fileResolution = catalog.resolve(intent: TaskIntent(
+ intentID: "app_open-quarterly-plan",
+ taskType: "app_open",
+ targetApp: LocalAppTarget(appName: "Local Item", metadata: ["dynamicTarget": "true"]),
+ entities: ["appName": "quarterly plan.pdf"],
+ normalizedEntities: ["appName": "Quarterly Plan.pdf"],
+ confidence: 0.88,
+ parserSource: .localModel,
+ metadata: ["requestedItemName": "quarterly plan.pdf"]
+ ))
+ #expect(fileResolution.status == .resolved)
+ let fileDefinition = try #require(fileResolution.definition)
+ #expect(LocalAppTaskVerificationPolicy.mode(for: fileDefinition) == .openedLocalItem)
+ #expect(fileResolution.metadata["itemKind"] == "file")
+ }
+
+ @Test
+ func lowConfidenceModelIntentAsksForConfirmationBeforeLookupExecution() {
+ let catalog = LocalAppTaskCatalog(
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(
+ installedBundleIdentifiers: ["com.figma.Desktop"],
+ installedApplicationNames: ["Figma": "com.figma.Desktop"]
+ )
+ )
+ let resolution = catalog.resolve(intent: TaskIntent(
+ intentID: "app_open-uncertain",
+ taskType: "app_open",
+ targetApp: LocalAppTarget(appName: "Local Item", metadata: ["dynamicTarget": "true"]),
+ entities: ["appName": "figma"],
+ normalizedEntities: ["appName": "Figma"],
+ confidence: 0.4,
+ parserSource: .localModel
+ ))
+
+ #expect(resolution.status == .needsConfirmation)
+ #expect(resolution.metadata["reason"] == "lowConfidenceIntent")
+ }
+
+ @Test
+ func structuredDocumentFormFillIntentBuildsReviewOnlyTask() throws {
+ let intent = documentFormFillIntent()
#expect(intent.taskType == "document_form_fill")
#expect(intent.targetApp.appName == "Preview")
@@ -51,8 +118,8 @@ struct LocalAppTaskTests {
}
@Test
- func deterministicParserRequestsConfirmationForMissingRequiredEntity() throws {
- let intent = try #require(parser().parse("show me the weather"))
+ func modelIntentCanRequestConfirmationForMissingRequiredEntity() throws {
+ let intent = weatherIntent(rawCity: "", city: "", needsConfirmation: true)
#expect(intent.taskType == "weather_lookup")
#expect(intent.intentID == "weather_lookup-needs-city")
@@ -61,13 +128,16 @@ struct LocalAppTaskTests {
}
@Test
- func deterministicParserIgnoresUnsupportedCommands() {
- #expect(parser().parse("open my calendar") == nil)
+ func catalogResolveCommandDoesNotParseWordsFromUserText() {
+ let resolution = catalog().resolve(command: "open my calendar")
+
+ #expect(resolution.status == .unsupportedCommand)
+ #expect(resolution.metadata["reason"] == "modelIntentRequired")
}
@Test
func genericAdapterBuildsLocalNavigationRequestForTargetApp() throws {
- let intent = try #require(parser().parse("weather in San Francisco"))
+ let intent = weatherIntent(rawCity: "San Francisco", city: "San Francisco")
let request = try #require(adapter().localNavigationFrameRequest(
for: intent,
traceID: "trace-local-app-task",
@@ -83,7 +153,7 @@ struct LocalAppTaskTests {
@Test
func genericAdapterProjectsDryRunStepsAndGuardedKeyboardTemplates() throws {
- let intent = try #require(parser().parse("show me the weather for SF"))
+ let intent = weatherIntent(rawCity: "SF", city: "San Francisco")
let localAdapter = adapter()
let plan = localAdapter.dryRunPlan(for: intent)
@@ -119,7 +189,7 @@ struct LocalAppTaskTests {
@Test
func genericAdapterVerifiesObservedVisibleText() throws {
- let intent = try #require(parser().parse("weather for SF"))
+ let intent = weatherIntent(rawCity: "SF", city: "San Francisco")
let localAdapter = adapter()
let plan = localAdapter.dryRunPlan(
for: intent,
@@ -140,9 +210,87 @@ struct LocalAppTaskTests {
}
@Test
- func catalogResolvesCommandAgainstAvailableInstalledAppDefinition() throws {
+ func appOpenAdapterVerifiesFocusedApp() throws {
+ let catalog = LocalAppTaskCatalog(
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Music"])
+ )
+ let resolution = catalog.resolve(intent: TaskIntent(
+ intentID: "app_open-music",
+ taskType: "app_open",
+ targetApp: LocalAppTarget(appName: "Local Item", metadata: ["dynamicTarget": "true"]),
+ entities: ["appName": "music"],
+ normalizedEntities: ["appName": "Music"],
+ confidence: 0.9,
+ parserSource: .localModel
+ ))
+ let intent = try #require(resolution.intent)
+ let definition = try #require(resolution.definition)
+ let localAdapter = LocalAppTaskAdapter(definition: definition)
+ let plan = localAdapter.dryRunPlan(
+ for: intent,
+ observation: LocalAppTaskObservation(
+ appIsRunning: true,
+ appIsFocused: true,
+ confidence: 0.72
+ )
+ )
+
+ #expect(plan.terminalState == .completed)
+ #expect(plan.verificationConfidence == 0.8)
+ #expect(plan.steps.first(where: { $0.role == .verifyResult })?.status == .verified)
+ }
+
+ @Test
+ func mediaPlaybackAdapterPlaysFirstSearchResultAndDoesNotRequireVisibleText() throws {
+ let intent = mediaPlaybackIntent(rawQuery: "justin bieber", query: "justin bieber")
+ let localAdapter = LocalAppTaskAdapter(definition: BuiltInLocalAppTaskDefinitions.mediaPlayback)
+ let plan = localAdapter.dryRunPlan(
+ for: intent,
+ observation: LocalAppTaskObservation(
+ appIsRunning: true,
+ appIsFocused: true,
+ availableControls: ["search": true],
+ visibleText: [:],
+ confidence: 0.68
+ )
+ )
+
+ #expect(plan.terminalState == .completed)
+ #expect(plan.metadata["defaultOSInputBackend"] == "mac-apple-script")
+ #expect(plan.metadata["automationBackend"] == "appleScript")
+ #expect(plan.steps.map(\.role) == [
+ .parseIntent,
+ .launchOrFocusApp,
+ .observeApp,
+ .focusControl,
+ .enterText,
+ .submit,
+ .submit,
+ .verifyResult
+ ])
+ #expect(plan.steps.first(where: { $0.role == .verifyResult })?.summary == "Command was sent to Music")
+
+ let commands = localAdapter.guardedKeyboardCommandTemplates(
+ for: intent,
+ issuedAt: timestamp(100)
+ )
+ #expect(commands.map(\.key) == ["Command+F", "justin bieber", "Return", "Return"])
+
+ let automationCommands = localAdapter.guardedAutomationCommandTemplates(
+ for: intent,
+ issuedAt: timestamp(100)
+ )
+ #expect(automationCommands.map(\.kind) == [.controller])
+ #expect(automationCommands.first?.key == "justin bieber")
+ #expect(automationCommands.first?.metadata["automationBackend"] == "appleScript")
+ #expect(automationCommands.first?.metadata["appleScript.action"] == "music.playMediaQuery")
+ }
+
+ @Test
+ func catalogResolvesStructuredIntentAgainstAvailableInstalledAppDefinition() throws {
let catalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: [
"com.apple.weather",
"com.apple.Music",
@@ -150,7 +298,7 @@ struct LocalAppTaskTests {
])
)
- let resolution = catalog.resolve(command: "show me the weather for SF")
+ let resolution = catalog.resolve(intent: weatherIntent(rawCity: "SF", city: "San Francisco"))
#expect(resolution.status == .resolved)
#expect(resolution.intent?.normalizedEntities["city"] == "San Francisco")
@@ -163,11 +311,11 @@ struct LocalAppTaskTests {
let plan = catalog.adapter(for: definition).dryRunPlan(for: intent)
#expect(plan.steps.map(\.role).contains(.verifyResult))
- let mediaResolution = catalog.resolve(command: "play Coldplay")
+ let mediaResolution = catalog.resolve(intent: mediaPlaybackIntent(rawQuery: "Coldplay", query: "Coldplay"))
#expect(mediaResolution.status == .resolved)
#expect(mediaResolution.definition?.taskType == "media_playback")
- let documentResolution = catalog.resolve(command: "fill out this PDF using this data")
+ let documentResolution = catalog.resolve(intent: documentFormFillIntent())
#expect(documentResolution.status == .resolved)
#expect(documentResolution.definition?.taskType == "document_form_fill")
}
@@ -175,17 +323,27 @@ struct LocalAppTaskTests {
@Test
func catalogSeparatesUnsupportedMissingEntityAndUnavailableApp() {
let availableCatalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
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 unavailableAppResolution = availableCatalog.resolve(intent: TaskIntent(
+ intentID: "app_open-missing",
+ taskType: "app_open",
+ targetApp: LocalAppTarget(appName: "Local Item", metadata: ["dynamicTarget": "true"]),
+ entities: ["appName": "an app that does not exist"],
+ normalizedEntities: ["appName": "An App That Does Not Exist"],
+ confidence: 0.86,
+ parserSource: .localModel
+ ))
+ #expect(unavailableAppResolution.status == .appUnavailable)
+ #expect(unavailableAppResolution.metadata["reason"] == "targetAppUnavailable")
+ #expect(availableCatalog.resolve(intent: weatherIntent(rawCity: "", city: "", needsConfirmation: true)).status == .needsConfirmation)
let unavailableCatalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: [])
)
- #expect(unavailableCatalog.resolve(command: "show me the weather for SF").status == .appUnavailable)
+ #expect(unavailableCatalog.resolve(intent: weatherIntent(rawCity: "SF", city: "San Francisco")).status == .appUnavailable)
}
@Test
@@ -198,12 +356,10 @@ struct LocalAppTaskTests {
let definition = LocalAppTaskDefinition(
taskType: "notes_capture",
targetApp: LocalAppTarget(appName: "Notes", bundleIdentifier: "com.apple.Notes"),
- triggerTerms: ["note", "remember"],
+ triggerTerms: [],
entityRules: [
LocalAppTaskEntityRule(
- name: "note",
- markers: ["note", "remember"],
- metadata: ["capture": "afterTrigger"]
+ name: "note"
)
],
workflowSteps: [
@@ -219,21 +375,52 @@ struct LocalAppTaskTests {
let fileURL = directoryURL.appendingPathComponent("notes.json")
try JSONEncoder().encode(definition).write(to: fileURL)
- let definitions = try LocalAppTaskDefinitionLoader().mergedWithBuiltIns(from: directoryURL)
+ let cacheURL = temporaryCacheURL()
+ defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }
+ let cache = LocalItemResolutionCache(storeURL: cacheURL)
+ let definitions = try LocalAppTaskDefinitionLoader(cache: cache).cachedDefinitions(from: directoryURL)
let loaded = try #require(definitions.first(where: { $0.taskType == "notes_capture" }))
#expect(loaded.targetApp.bundleIdentifier == "com.apple.Notes")
#expect(loaded.metadata["source"] == "test-json")
+ #expect(cache.taskDefinitions().map(\.taskType).contains("notes_capture"))
let catalog = LocalAppTaskCatalog(
taskDefinitions: definitions,
availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Notes"])
)
- #expect(catalog.resolve(command: "remember buy milk").status == .resolved)
+ #expect(catalog.resolve(intent: TaskIntent(
+ intentID: "notes_capture-buy-milk",
+ taskType: "notes_capture",
+ targetApp: LocalAppTarget(appName: "Notes", bundleIdentifier: "com.apple.Notes"),
+ entities: ["note": "buy milk"],
+ normalizedEntities: ["note": "buy milk"],
+ confidence: 0.9,
+ parserSource: .localModel
+ )).status == .resolved)
+ }
+
+ @Test
+ func defaultLocalCatalogLoadsRuntimeDefinitionsFromCache() {
+ let cacheURL = temporaryCacheURL()
+ defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }
+ let cache = LocalItemResolutionCache(storeURL: cacheURL)
+ let loader = LocalAppTaskDefinitionLoader(cache: cache)
+
+ let catalog = LocalAppTaskCatalog.defaultLocal(
+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: []),
+ loader: loader
+ )
+
+ #expect(catalog.taskDefinitions.map(\.taskType) == ["app_open"])
+ #expect(cache.taskDefinitions().map(\.taskType) == ["app_open"])
+ #expect(catalog.taskDefinitions.contains { $0.targetApp.appName == "Weather" } == false)
+ #expect(catalog.taskDefinitions.contains { $0.targetApp.appName == "Music" } == false)
+ #expect(catalog.taskDefinitions.contains { $0.targetApp.appName == "Preview" } == false)
}
@Test
func documentFormFillPlannerMapsStructuredDataToObservedFieldsForReview() throws {
- let intent = try #require(parser().parse("fill out this PDF using this data"))
+ let intent = documentFormFillIntent()
let context = LocalAppTaskContext(
focusedAppName: "Preview",
focusedBundleIdentifier: "com.apple.Preview",
@@ -262,7 +449,7 @@ struct LocalAppTaskTests {
@Test
func documentFormFillApprovalBuildsOnlyApprovedAccessibilityCommands() throws {
- let intent = try #require(parser().parse("fill out this PDF using this data"))
+ let intent = documentFormFillIntent()
let context = LocalAppTaskContext(
focusedWindowTitle: "W-9.pdf",
structuredData: [
@@ -356,7 +543,7 @@ struct LocalAppTaskTests {
@Test @MainActor
func liveRunnerReturnsReviewPlanForDocumentFormFillWithoutExecutingInput() async throws {
let catalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Preview"])
)
let context = LocalAppTaskContext(
@@ -372,10 +559,13 @@ struct LocalAppTaskTests {
catalog: catalog,
contextProvider: StaticLocalAppTaskContextProvider(context: context)
)
+ let intent = documentFormFillIntent()
let result = await runner.run(
command: "fill out this PDF using this data",
- traceID: "trace-document-fill"
+ traceID: "trace-document-fill",
+ resolution: catalog.resolve(intent: intent),
+ metadata: ["intentParser": "test-model"]
)
#expect(result.status == .needsUserReview)
@@ -406,7 +596,7 @@ struct LocalAppTaskTests {
)
)
let catalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])
)
let runner = LocalAppTaskLiveRunner(
@@ -420,8 +610,14 @@ struct LocalAppTaskTests {
},
permissionPolicy: ToolCallPolicy(deniedCapabilities: [])
)
+ let intent = weatherIntent(rawCity: "SF", city: "San Francisco")
- let result = await runner.run(command: "show me the weather for SF", traceID: "trace-live-task")
+ let result = await runner.run(
+ command: "show me the weather for SF",
+ traceID: "trace-live-task",
+ resolution: catalog.resolve(intent: intent),
+ metadata: ["intentParser": "test-model"]
+ )
#expect(result.status == .completed)
#expect(result.finalPlan?.terminalState == .completed)
@@ -439,6 +635,57 @@ struct LocalAppTaskTests {
#expect(result.metadata["workflow.verify.status"] == "completed")
}
+ @Test @MainActor
+ func liveRunnerUsesAppleScriptAutomationForMediaPlayback() async throws {
+ let backend = RecordingLocalAppTaskInputBackend()
+ let controller = FakeLocalAppTaskAppController(
+ launchObservation: LocalAppTaskObservation(
+ appIsRunning: true,
+ appIsFocused: true,
+ availableControls: ["search": true],
+ confidence: 0.5
+ ),
+ finalObservation: LocalAppTaskObservation(
+ appIsRunning: true,
+ appIsFocused: true,
+ availableControls: ["search": true],
+ visibleText: [:],
+ confidence: 0.72
+ )
+ )
+ let catalog = LocalAppTaskCatalog(
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Music"])
+ )
+ let runner = LocalAppTaskLiveRunner(
+ catalog: catalog,
+ appController: controller,
+ actionEngineFactory: { _ in
+ ActionEngineGuardrail(
+ configuration: ActionEngineConfiguration(liveInputEnabled: true),
+ inputBackend: backend
+ )
+ },
+ permissionPolicy: ToolCallPolicy(deniedCapabilities: [])
+ )
+ let intent = mediaPlaybackIntent(rawQuery: "justin bieber", query: "justin bieber")
+
+ let result = await runner.run(
+ command: "play justin bieber",
+ traceID: "trace-live-media",
+ resolution: catalog.resolve(intent: intent),
+ metadata: ["intentParser": "test-model"]
+ )
+
+ #expect(result.status == .completed)
+ #expect(result.actionTraces.map(\.command.kind) == [.controller])
+ #expect(await backend.executedKeys() == ["justin bieber"])
+ #expect(result.metadata["automation.backend"] == "appleScript")
+ #expect(result.metadata["automation.action"] == "music.playMediaQuery")
+ #expect(result.workflowProgress.state(for: .execute)?.status == .completed)
+ #expect(result.workflowProgress.state(for: .verify)?.status == .completed)
+ }
+
@Test @MainActor
func liveRunnerPublishesCoordinatorEventsForGuardedRun() async throws {
let backend = RecordingLocalAppTaskInputBackend()
@@ -459,7 +706,7 @@ struct LocalAppTaskTests {
)
let coordinator = RunCoordinator()
let catalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])
)
let runner = LocalAppTaskLiveRunner(
@@ -474,8 +721,14 @@ struct LocalAppTaskTests {
permissionPolicy: ToolCallPolicy(deniedCapabilities: []),
coordinator: coordinator
)
+ let intent = weatherIntent(rawCity: "SF", city: "San Francisco")
- let result = await runner.run(command: "show me the weather for SF", traceID: "trace-live-task-events")
+ let result = await runner.run(
+ command: "show me the weather for SF",
+ traceID: "trace-live-task-events",
+ resolution: catalog.resolve(intent: intent),
+ metadata: ["intentParser": "test-model"]
+ )
let events = await coordinator.events()
#expect(result.status == .completed)
@@ -512,6 +765,34 @@ struct LocalAppTaskTests {
),
verificationKey: "city"
) == true)
+
+ var neverFallback = definition
+ neverFallback.metadata["screenshotFallback"] = "never"
+ #expect(LocalAppTaskObservationFallbackPolicy.shouldUseScreenshotUnderstanding(
+ definition: neverFallback,
+ accessibilityObservation: LocalAppTaskObservation(
+ appIsRunning: true,
+ appIsFocused: true,
+ availableControls: [:],
+ visibleText: [:],
+ confidence: 0.4
+ ),
+ verificationKey: "city"
+ ) == false)
+
+ var controlFallback = definition
+ controlFallback.metadata["screenshotFallback"] = "missingControls"
+ #expect(LocalAppTaskObservationFallbackPolicy.shouldUseScreenshotUnderstanding(
+ definition: controlFallback,
+ accessibilityObservation: LocalAppTaskObservation(
+ appIsRunning: true,
+ appIsFocused: true,
+ availableControls: [:],
+ visibleText: ["city": "San Francisco"],
+ confidence: 0.7
+ ),
+ verificationKey: "city"
+ ) == true)
}
@Test @MainActor
@@ -566,20 +847,95 @@ struct LocalAppTaskTests {
#expect(controller.launchCount == 1)
}
- private func parser() -> LocalAppTaskIntentParser {
- LocalAppTaskIntentParser(taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults)
+ private func catalog() -> LocalAppTaskCatalog {
+ LocalAppTaskCatalog(
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: [])
+ )
+ }
+
+ private func weatherIntent(
+ rawCity: String,
+ city: String,
+ confidence: Double = 0.93,
+ needsConfirmation: Bool = false
+ ) -> TaskIntent {
+ let definition = BuiltInLocalAppTaskDefinitions.weatherLookup
+ return TaskIntent(
+ intentID: needsConfirmation ? "weather_lookup-needs-city" : "weather_lookup-\(slug(city))",
+ taskType: definition.taskType,
+ targetApp: definition.targetApp,
+ entities: rawCity.isEmpty ? [:] : ["city": rawCity],
+ normalizedEntities: city.isEmpty ? [:] : ["city": city],
+ confidence: confidence,
+ parserSource: .localModel,
+ needsConfirmation: needsConfirmation,
+ metadata: definition.metadata.merging(
+ needsConfirmation ? ["missingEntity": "city"] : [:]
+ ) { current, _ in current }
+ )
+ }
+
+ private func mediaPlaybackIntent(
+ rawQuery: String,
+ query: String,
+ confidence: Double = 0.93
+ ) -> TaskIntent {
+ let definition = BuiltInLocalAppTaskDefinitions.mediaPlayback
+ return TaskIntent(
+ intentID: "media_playback-\(slug(query))",
+ taskType: definition.taskType,
+ targetApp: definition.targetApp,
+ entities: ["query": rawQuery],
+ normalizedEntities: ["query": query],
+ confidence: confidence,
+ parserSource: .localModel,
+ metadata: definition.metadata
+ )
+ }
+
+ private func documentFormFillIntent(confidence: Double = 0.9) -> TaskIntent {
+ let definition = BuiltInLocalAppTaskDefinitions.documentFormFill
+ return TaskIntent(
+ intentID: "document_form_fill-current-pdf",
+ taskType: definition.taskType,
+ targetApp: definition.targetApp,
+ entities: [
+ "document": "this PDF",
+ "dataSource": "this data"
+ ],
+ normalizedEntities: [
+ "document": "current PDF",
+ "dataSource": "provided data"
+ ],
+ confidence: confidence,
+ parserSource: .localModel,
+ metadata: definition.metadata
+ )
}
private func adapter() -> LocalAppTaskAdapter {
LocalAppTaskAdapter(definition: BuiltInLocalAppTaskDefinitions.weatherLookup)
}
+ private func slug(_ value: String) -> String {
+ LocalAppTaskIntentParser.normalizedPhrase(value)
+ .split(separator: " ")
+ .joined(separator: "-")
+ }
+
private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
RunTraceTimestamp(
wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
monotonicUptimeNanoseconds: milliseconds * 1_000_000
)
}
+
+ private func temporaryCacheURL() -> URL {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-task-cache-\(UUID().uuidString)", isDirectory: true)
+ .appendingPathComponent("cache.jsonl")
+ }
}
@MainActor
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalItemResolutionCacheTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalItemResolutionCacheTests.swift
new file mode 100644
index 00000000..8e9dd554
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalItemResolutionCacheTests.swift
@@ -0,0 +1,113 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct LocalItemResolutionCacheTests {
+ @Test
+ func cacheRecordsResolvedAndMissingLookupsAsSearchableMemory() throws {
+ let cacheURL = temporaryCacheURL()
+ defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }
+ let cache = LocalItemResolutionCache(storeURL: cacheURL)
+
+ cache.record(
+ availability: LocalAppAvailability(
+ target: LocalAppTarget(
+ appName: "Figma",
+ bundleIdentifier: "com.figma.Desktop",
+ titleContains: "Figma",
+ metadata: [
+ "localItem.kind": "application",
+ "localItem.path": "/Applications/Figma.app"
+ ]
+ ),
+ isInstalled: true,
+ appURL: URL(fileURLWithPath: "/Applications/Figma.app"),
+ metadata: [
+ "provider": "test",
+ "itemKind": "application",
+ "itemURL": "/Applications/Figma.app",
+ "bundleIdentifier": "com.figma.Desktop",
+ "match": "exact"
+ ]
+ ),
+ query: "figma",
+ source: "unit"
+ )
+ cache.record(
+ availability: LocalAppAvailability(
+ target: LocalAppTarget(appName: "Ghost Tool"),
+ isInstalled: false,
+ metadata: [
+ "provider": "test",
+ "reason": "localItemUnavailable",
+ "requestedItemName": "ghost tool"
+ ]
+ ),
+ query: "ghost tool",
+ source: "unit-missing"
+ )
+
+ let figmaResult = try #require(cache.search(query: "open figma").first)
+ #expect(figmaResult.entry.displayName == "Figma")
+ #expect(figmaResult.entry.isAvailable)
+
+ let missingSnippet = try #require(cache.contextSnippets(for: "launch ghost tool").first)
+ #expect(missingSnippet.contains("local_resolution_cache:"))
+ #expect(missingSnippet.contains("status=missing"))
+ #expect(missingSnippet.contains("Ghost Tool"))
+ }
+
+ @Test
+ func cachePrewarmsFilesFromConfiguredDirectories() throws {
+ let rootURL = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-cache-test-\(UUID().uuidString)", isDirectory: true)
+ let cacheURL = temporaryCacheURL()
+ defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }
+ try FileManager.default.createDirectory(at: rootURL, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: rootURL) }
+
+ let fileURL = rootURL.appendingPathComponent("Roadmap Notes.md")
+ try "next steps".write(to: fileURL, atomically: true, encoding: .utf8)
+
+ let cache = LocalItemResolutionCache(storeURL: cacheURL)
+ cache.prewarmDefaultLocalItems(
+ options: LocalItemResolutionCachePrewarmOptions(
+ applicationRoots: [],
+ fileRoots: [rootURL],
+ maxItemsPerRoot: 10
+ )
+ )
+
+ let result = try #require(cache.search(query: "attach roadmap notes").first)
+ #expect(result.entry.displayName == "Roadmap Notes.md")
+ #expect(result.entry.kind == "file")
+ #expect(result.entry.path == fileURL.path)
+ #expect(result.entry.source == "prewarm")
+ }
+
+ @Test
+ func cachePrewarmsTaskDefinitionsAsSearchableCapabilities() throws {
+ let cacheURL = temporaryCacheURL()
+ defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }
+ let cache = LocalItemResolutionCache(storeURL: cacheURL)
+
+ cache.prewarmTaskDefinitions(BuiltInLocalAppTaskDefinitions.benchmarkFixtures)
+
+ let result = try #require(cache.search(query: "media playback", limit: 4).first { result in
+ result.entry.kind == "taskDefinition"
+ })
+ #expect(result.entry.displayName == "media playback")
+ #expect(result.entry.metadata["taskType"] == "media_playback")
+ #expect(result.entry.metadata["appleScript.action"] == "music.playMediaQuery")
+ #expect(cache.taskDefinitions().contains { $0.taskType == "media_playback" })
+ #expect(cache.cachedAvailability(named: "media playback", preferredKind: nil) == nil)
+ }
+
+ private func temporaryCacheURL() -> URL {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-resolution-cache-\(UUID().uuidString)", isDirectory: true)
+ .appendingPathComponent("cache.jsonl")
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MacAppleScriptActionEngineInputBackendTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MacAppleScriptActionEngineInputBackendTests.swift
new file mode 100644
index 00000000..10a4c8dc
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MacAppleScriptActionEngineInputBackendTests.swift
@@ -0,0 +1,147 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct MacAppleScriptActionEngineInputBackendTests {
+ @Test
+ func musicPlaybackCommandRunsEscapedAppleScript() async throws {
+ let runner = RecordingAppleScriptRunner(
+ result: AppleScriptExecutionResult(
+ succeeded: true,
+ output: "searched-ui-first-result"
+ )
+ )
+ let backend = MacAppleScriptActionEngineInputBackend(runner: runner)
+ let result = await backend.execute(
+ ActionEngineCommand(
+ id: "play-media",
+ traceID: "trace-media",
+ targetID: "local-app-task-media-playback",
+ kind: .controller,
+ issuedAt: timestamp(100),
+ key: "Justin \"JB\" Bieber",
+ metadata: [
+ "automationBackend": "appleScript",
+ "appleScript.action": "music.playMediaQuery",
+ "appleScript.query": "Justin \"JB\" Bieber"
+ ]
+ )
+ )
+
+ let scripts = await runner.scripts()
+ #expect(result.executed)
+ #expect(result.metadata["liveInputBackend"] == "mac-apple-script")
+ #expect(result.metadata["appleScript.output"] == "searched-ui-first-result")
+ #expect(scripts.count == 1)
+ #expect(scripts.first?.contains(#"set donkeyQuery to "Justin \"JB\" Bieber""#) == true)
+ #expect(scripts.first?.contains("tell application \"Music\"") == true)
+ #expect(scripts.first?.contains("tell application \"System Events\"") == true)
+ }
+
+ @Test
+ func unsupportedAppleScriptCommandDoesNotExecute() async {
+ let runner = RecordingAppleScriptRunner(
+ result: AppleScriptExecutionResult(succeeded: true, output: "searched-ui-first-result")
+ )
+ let backend = MacAppleScriptActionEngineInputBackend(runner: runner)
+ let result = await backend.execute(
+ ActionEngineCommand(
+ id: "bad-command",
+ traceID: "trace-media",
+ targetID: "local-app-task-media-playback",
+ kind: .key,
+ issuedAt: timestamp(100),
+ key: "Return",
+ metadata: ["automationBackend": "appleScript"]
+ )
+ )
+
+ #expect(result.executed == false)
+ #expect(result.metadata["reason"] == "unsupportedCommandKind")
+ let scripts = await runner.scripts()
+ #expect(scripts.isEmpty)
+ }
+
+ @Test
+ func generatedAppleScriptSourceRunsWithoutBuiltinAction() async throws {
+ let runner = RecordingAppleScriptRunner(
+ result: AppleScriptExecutionResult(succeeded: true, output: "ok")
+ )
+ let backend = MacAppleScriptActionEngineInputBackend(runner: runner)
+ let result = await backend.execute(
+ ActionEngineCommand(
+ id: "generated-command",
+ traceID: "trace-generated",
+ targetID: "local-app-task-generated",
+ kind: .controller,
+ issuedAt: timestamp(100),
+ metadata: [
+ "automationBackend": "appleScript",
+ "appleScript.action": "generated.test",
+ "appleScript.source": #"return "ok""#
+ ]
+ )
+ )
+
+ #expect(result.executed)
+ #expect(result.metadata["appleScript.scriptKind"] == "source")
+ let scripts = await runner.scripts()
+ #expect(scripts == [#"return "ok""#])
+ }
+
+ @Test
+ func generatedAppleScriptTemplateEscapesEntityValues() async throws {
+ let runner = RecordingAppleScriptRunner(
+ result: AppleScriptExecutionResult(succeeded: true, output: "ok")
+ )
+ let backend = MacAppleScriptActionEngineInputBackend(runner: runner)
+ let result = await backend.execute(
+ ActionEngineCommand(
+ id: "template-command",
+ traceID: "trace-template",
+ targetID: "local-app-task-template",
+ kind: .controller,
+ issuedAt: timestamp(100),
+ key: #"A "quoted" value"#,
+ metadata: [
+ "automationBackend": "appleScript",
+ "appleScript.action": "generated.template",
+ "appleScript.query": #"A "quoted" value"#,
+ "appleScript.template": "set q to {query}\nreturn \"ok\""
+ ]
+ )
+ )
+
+ #expect(result.executed)
+ #expect(result.metadata["appleScript.scriptKind"] == "template")
+ let scripts = await runner.scripts()
+ #expect(scripts.first == #"set q to "A \"quoted\" value""# + "\nreturn \"ok\"")
+ }
+
+ private func timestamp(_ milliseconds: UInt64) -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(timeIntervalSince1970: Double(milliseconds) / 1_000),
+ monotonicUptimeNanoseconds: milliseconds * 1_000_000
+ )
+ }
+}
+
+private actor RecordingAppleScriptRunner: AppleScriptRunning {
+ private let result: AppleScriptExecutionResult
+ private var recordedScripts: [String] = []
+
+ init(result: AppleScriptExecutionResult) {
+ self.result = result
+ }
+
+ func run(_ script: String) async -> AppleScriptExecutionResult {
+ recordedScripts.append(script)
+ return result
+ }
+
+ func scripts() -> [String] {
+ recordedScripts
+ }
+}
diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.md
index 5f1e6b1e..88ff6a41 100644
--- a/docs/guides/agent-harness.md
+++ b/docs/guides/agent-harness.md
@@ -119,16 +119,18 @@ The harness loop looks like this:
The harness should make conversation feel continuous even when execution happens
inside the thread. The user should not need to know whether a turn was answered
-by a chat response, a local model classifier, deterministic parsing, or a
+by a chat response, a local model classifier, a typed runtime artifact, or a
guarded runtime path.
Model calls live behind typed harness boundaries. Voice transcription is a local
model call before intake and produces a transcript turn. The local LLM call,
-provider LLM call, memory helpers, and deterministic fallback each consume the
-bounded context packet and return typed decisions or helper artifacts.
+provider LLM call, memory helpers, and explicit metadata helpers each consume
+the bounded context packet and return typed decisions or helper artifacts.
Observation models such as screenshot segmentation and UI understanding run
inside the local-task branch and produce observation evidence, not direct input
-actions.
+actions. Any semantic user-intent distinction, including whether a turn is an
+instructional visual-coaching request, belongs behind one of these typed model
+or catalog boundaries.
Routing outcomes carry a structured `AppHarnessDecision`. The decision names the
next supported harness action:
@@ -136,6 +138,50 @@ respond, ask for clarification, open review, run a local task, or no-op. This
keeps model-assisted routing in a typed decision space instead of treating free
text as an implicit action signal.
+## Intent Classification Rules
+
+User intent must not be inferred with ad hoc phrase, prefix, suffix, substring,
+or regex checks against natural-language command text. Donkey has local LLMs,
+task definitions, runtime catalogs, and cache context for this job. Use them.
+The fast classifier may know typed capability buckets such as task ids,
+capability ids, cache entry kinds, and model output statuses. It must not
+recover those buckets by reading natural-language words out of the user's
+prompt.
+
+Allowed deterministic checks are narrow primitives whose correctness does not
+depend on open-ended language semantics: empty input, numeric-only arithmetic
+expression extraction, exact schema validation, explicit metadata flags, and
+bounded normalization of lookup text after a typed decision has already selected
+a lookup path. These checks must stay generic and must not encode app-specific
+or workflow-specific user phrasing.
+
+Disallowed checks include code that decides a user's semantic intent from
+phrases like "show me how", "within", "play", "open", or app names outside a
+declared task definition or model output. If behavior depends on what the user
+means, add or reuse a typed classifier/resolver and test it with structured
+model output. Do not patch another string list.
+
+Do not look for words inside user command strings to decide what the user wants.
+This includes local deterministic parser fallbacks, command trigger arrays,
+prefix/suffix tests, and conversation/greeting/help classifiers. A typed model
+or explicit runtime artifact must produce the intent first. Exact string checks
+remain acceptable for non-semantic technical validation such as JSON schema
+fields, CLI arguments, AppleScript syntax/output validation, filesystem paths,
+accessibility constants, colors, and safety metadata.
+
+Generic local-item lookup must follow the same rule. Do not add static command
+verb, lookup prefix, or lookup suffix arrays to guess that text means "open this
+app/file/folder." A typed model or catalog artifact selects the local-item
+lookup capability and extracts the requested item name; after that, the runtime
+may normalize that item name and resolve it through the cache, Spotlight, and
+bounded filesystem lookup.
+
+Instructional visual coaching is the canonical example. The harness may show an
+animated guide cursor only after a model-backed resolver returns a structured
+guide decision with cursor steps. It must not use hardcoded prompt prefixes to
+decide that a turn is a coaching request, and it must not parse app names or
+goals out of text with local string slicing.
+
## Context Engineering
The harness builds context deliberately for each job. It should never dump raw,
@@ -164,23 +210,27 @@ kind.
## Routing Outcomes
-Conversation is a first-class outcome. Greetings, "what can you do?", small
-talk, and explanatory questions should stay in the task thread and get an
-assistant response. These turns may update memory or teach the user about
-available capabilities, but they should not create a failed local-app run.
-
-Clarification is for actionable intent with missing required information. If
-the user says "play music", the harness should ask what to play. If the user
-says "fill this out" without a document or data source, it should ask for the
-missing input or invite an upload. The prompt should name the missing detail
-rather than using generic copy like "Need more detail".
-
-Action execution is for validated, supported tasks. The local-model classifier
-and deterministic fallback can produce a `TaskIntent`, but execution may only
-continue after catalog validation confirms the target app/task, required
-entities, app availability, and safety policy. Built-in examples such as
-weather lookup, media playback, and document form-fill are benchmark definitions
-inside this generic path, not separate architectures.
+Conversation is a first-class outcome. Turns that do not produce a typed local
+task intent stay in the task thread and get an assistant response instead of a
+failed local-app run. Conversation classification may be model-backed or derived
+from explicit runtime/model statuses, but it must not use greeting/help/small
+talk phrase lists.
+
+Clarification is for typed actionable intent with missing required information.
+When the model returns a supported task but marks a required entity as missing,
+the harness should ask for that exact entity or invite an upload. The prompt
+should name the missing detail rather than using generic copy like "Need more
+detail".
+
+Action execution is for validated, supported tasks. The fast turn classifier can
+answer narrow non-semantic turns such as numeric arithmetic; otherwise the local
+model classifier or explicit runtime metadata produces a `TaskIntent`. Execution
+may only continue after catalog validation confirms the target app/task,
+required entities, app availability, and safety policy. Weather lookup, media
+playback, and document form-fill are benchmark fixtures for tests and replay
+evaluation, not runtime defaults. Runtime defaults come from the local
+resolution cache, which is seeded with generic capabilities and enriched by
+model-generated or user-reviewed task definition files.
Review is required when the harness can propose work but should not perform it
blindly. Document form-fill is the main supported example: Donkey can inspect
@@ -206,13 +256,37 @@ model can be told about this state, but the runner owns it.
Live input remains guarded. The action engine checks permission policy, target
focus, rate limits, hold duration, and backend evidence before issuing input.
-The macOS keyboard and Accessibility backends are intentionally narrow. They
-exist for validated local-app workflows, not arbitrary UI automation.
+The macOS AppleScript, keyboard, and Accessibility backends are intentionally
+narrow. They exist for validated local-app workflows, not arbitrary UI
+automation. Prefer app-native AppleScript for scriptable app tasks before
+falling back to Accessibility or keyboard input. AppleScript commands may be
+generated from task metadata or compact model-provided source/templates, but
+they still run only after catalog validation and through the guarded controller
+backend.
+
+App automation scripts must be generated artifacts, not product code fixtures.
+Do not add hardcoded app-specific AppleScript bodies, UI-scripting sequences, or
+workflow scripts to Swift as static strings. The harness may keep generic
+rendering/execution utilities such as string escaping, template interpolation,
+schema validation, AppleScript syntax/language validation, and guarded backend
+dispatch. The actual app-control script for a task must come from a typed
+model/script-generation step, cached resolution metadata, or a user-reviewed
+task definition, and it must be logged with the model/schema/action metadata
+that produced it.
+
+If an app task needs AppleScript, the supported shape is: classify the task,
+resolve the target app and entities, ask the model or task-definition layer for
+a bounded script or template, validate that it matches the resolved task and
+allowed backend, then execute it through the AppleScript backend. Adding a
+`musicPlaybackScript`, `openFooScript`, or similar app-named helper is a harness
+bug, even if the script happens to work on one machine.
Observation prefers Accessibility and app/window metadata. Bounded screenshots
and local UI understanding are fallback observation context only; they do not
emit direct input actions. Captured screenshots, Accessibility snapshots, and
manual capture artifacts are trace evidence, not a general live vision loop.
+Verification and screenshot fallback behavior should be derived from task
+metadata and runtime item metadata, not one-off branches for individual apps.
The fast local path must keep working without remote model calls. Local sidecars
can classify actionable turns, transcribe voice, segment screenshots, or
diff --git a/scripts/local-runtime-runners/donkey_runtime_runner.py b/scripts/local-runtime-runners/donkey_runtime_runner.py
index e3f2fe9d..f1368200 100644
--- a/scripts/local-runtime-runners/donkey_runtime_runner.py
+++ b/scripts/local-runtime-runners/donkey_runtime_runner.py
@@ -472,6 +472,14 @@ def run_local_llm(request: dict[str, Any]) -> dict[str, Any]:
prompt = task_followup_prompt(command, candidates)
schema = task_followup_schema(candidates)
max_tokens = 96
+ elif schema_id == "pointer_coach_cursor_guide_v1":
+ prompt = pointer_coach_cursor_guide_prompt(
+ command,
+ request.get("runtimeCapabilities", []),
+ request.get("cacheSnippets", []),
+ )
+ schema = pointer_coach_cursor_guide_schema()
+ max_tokens = 240
else:
task_definitions = request.get("taskDefinitions", [])
prompt = task_intent_prompt(command, task_definitions)
@@ -570,6 +578,72 @@ def task_followup_schema(candidates: list[dict[str, Any]]) -> dict[str, Any]:
}
+def pointer_coach_cursor_guide_prompt(
+ command: str,
+ runtime_capabilities: list[Any],
+ cache_snippets: list[Any],
+) -> str:
+ capabilities = "\n".join(str(item) for item in runtime_capabilities if str(item).strip())
+ cache = "\n".join(str(item) for item in cache_snippets if str(item).strip())
+ return "\n".join(
+ [
+ "Classify whether the user's request should be answered by visual coaching with an on-screen cursor guide.",
+ "Use semantic intent, not command wording. Visual coaching is for teaching or demonstrating where/how to do something inside an app.",
+ "If the request is an executable local task, app/file open request, arithmetic/chat answer, or missing-detail clarification, set shouldShowGuide=false.",
+ "If shouldShowGuide=true, generate two to five cursor steps with short labels. Coordinates are normalized screen positions from 0 to 1.",
+ "The guide must explain and point only. It must not claim to click, type, submit, or perform the user's task.",
+ "Do not include reasoning outside JSON.",
+ f"User request: {command}",
+ "Known executable runtime capabilities:",
+ capabilities,
+ "Relevant local cache snippets:",
+ cache,
+ ]
+ )
+
+
+def pointer_coach_cursor_guide_schema() -> dict[str, Any]:
+ return {
+ "type": "object",
+ "additionalProperties": False,
+ "required": [
+ "shouldShowGuide",
+ "title",
+ "goal",
+ "targetApp",
+ "confidence",
+ "reason",
+ "steps",
+ "metadata",
+ ],
+ "properties": {
+ "shouldShowGuide": {"type": "boolean"},
+ "title": {"type": "string"},
+ "goal": {"type": "string"},
+ "targetApp": {"type": "string"},
+ "confidence": {"type": "number", "minimum": 0, "maximum": 1},
+ "reason": {"type": "string"},
+ "steps": {
+ "type": "array",
+ "maxItems": 5,
+ "items": {
+ "type": "object",
+ "additionalProperties": False,
+ "required": ["label", "x", "y"],
+ "properties": {
+ "label": {"type": "string"},
+ "x": {"type": "number", "minimum": 0, "maximum": 1},
+ "y": {"type": "number", "minimum": 0, "maximum": 1},
+ "travelDuration": {"type": "number", "minimum": 0.1, "maximum": 2.0},
+ "holdDuration": {"type": "number", "minimum": 0.4, "maximum": 4.0},
+ },
+ },
+ },
+ "metadata": {"type": "object", "additionalProperties": {"type": "string"}},
+ },
+ }
+
+
def task_intent_prompt(command: str, task_definitions: list[dict[str, Any]]) -> str:
task_lines: list[str] = []
for definition in task_definitions:
@@ -593,6 +667,7 @@ def task_intent_prompt(command: str, task_definitions: list[dict[str, Any]]) ->
f"bundle={target.get('bundleIdentifier', 'unknown')}",
f"capability={workflow}",
f"entities={'; '.join(entity_parts)}",
+ f"dynamic_target={(definition.get('metadata') or {}).get('dynamicTarget', 'false')}",
]
)
)
@@ -605,6 +680,7 @@ def task_intent_prompt(command: str, task_definitions: list[dict[str, Any]]) ->
"Use only the provided task definitions. Do not invent apps, task types, entities, or actions.",
"If no capability fits, return the closest supported task with confidence below 0.55.",
"If a required entity is missing, set needsConfirmation=true and include missingEntity in metadata.",
+ "For dynamic local-item capabilities, extract the requested local app/file/folder name into entities.appName and normalizedEntities.appName. Use targetAppName for the resolved item name when you know it.",
f"Command: {command}",
"Supported task capabilities:",
"\n".join(task_lines),
@@ -621,6 +697,14 @@ def task_intent_schema(task_definitions: list[dict[str, Any]]) -> dict[str, Any]
if (item.get("targetApp") or {}).get("appName")
}
)
+ allows_dynamic_targets = any(
+ (item.get("metadata") or {}).get("dynamicTarget") == "true"
+ for item in task_definitions
+ )
+ target_app_name_schema: dict[str, Any] = {"type": "string"}
+ if not allows_dynamic_targets:
+ target_app_name_schema["enum"] = app_names
+
return {
"type": "object",
"additionalProperties": False,
@@ -635,7 +719,7 @@ def task_intent_schema(task_definitions: list[dict[str, Any]]) -> dict[str, Any]
],
"properties": {
"taskType": {"type": "string", "enum": task_types},
- "targetAppName": {"type": "string", "enum": app_names},
+ "targetAppName": target_app_name_schema,
"entities": {"type": "object", "additionalProperties": {"type": "string"}},
"normalizedEntities": {"type": "object", "additionalProperties": {"type": "string"}},
"confidence": {"type": "number", "minimum": 0, "maximum": 1},