Skip to content

Open source CapCut alternative.

TypeScript

Add typed local app action planning

David Le21236c755f60
diff --git a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift
index 06098394..9773e22d 100644
--- a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift
@@ -5,12 +5,14 @@ import Foundation
public struct TaskIntentAdapterRequest: Equatable, Sendable {
public var command: String
public var taskDefinitions: [LocalAppTaskDefinition]
+ public var contextSnippets: [String]
public var sourceTraceID: String
public var routeRequest: AIModelRouteRequest
public init(
command: String,
taskDefinitions: [LocalAppTaskDefinition],
+ contextSnippets: [String] = [],
sourceTraceID: String,
routeRequest: AIModelRouteRequest = AIModelRouteRequest(
jobType: .taskIntent,
@@ -20,6 +22,7 @@ public struct TaskIntentAdapterRequest: Equatable, Sendable {
) {
self.command = command
self.taskDefinitions = taskDefinitions
+ self.contextSnippets = contextSnippets
self.sourceTraceID = sourceTraceID
self.routeRequest = routeRequest
}
@@ -79,6 +82,7 @@ public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {
let input = LocalLLMTaskIntentSidecarRequest(
command: request.command,
taskDefinitions: request.taskDefinitions,
+ contextSnippets: request.contextSnippets,
sourceTraceID: request.sourceTraceID,
modelID: entry.modelID,
metadata: [
@@ -203,6 +207,7 @@ public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {
private struct LocalLLMTaskIntentSidecarRequest: Codable, Equatable, Sendable {
var command: String
var taskDefinitions: [LocalAppTaskDefinition]
+ var contextSnippets: [String]
var sourceTraceID: String
var modelID: String
var metadata: [String: String]
@@ -325,7 +330,7 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
),
"options": [
"num_ctx": 2048,
- "num_predict": 128,
+ "num_predict": 256,
"temperature": 0,
"top_p": 0.8
],
@@ -350,6 +355,13 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
]
.compactMap(\.self)
.joined(separator: " | ")
+ let modelPlan = definition.metadata["modelPlanned"] == "true"
+ ? [
+ "model_plan=true",
+ "allowed_tools=\(definition.metadata["plan.allowedTools"] ?? "")",
+ "action_plan_required=true"
+ ].joined(separator: " | ")
+ : ""
return [
"task_type=\(definition.taskType)",
@@ -357,23 +369,34 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
"bundle=\(definition.targetApp.bundleIdentifier ?? "unknown")",
"capability=\(workflow)",
"entities=\(entities)",
- automation
+ automation,
+ modelPlan
]
.filter { !$0.isEmpty }
.joined(separator: " | ")
}
.joined(separator: "\n")
+ let context = request.contextSnippets
+ .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
+ .prefix(8)
+ .joined(separator: "\n")
return [
"Classify the user's natural-language request into exactly one supported local app task intent, then return strict JSON.",
"Choose by capability and target app, not by exact wording. The user should not need to remember command phrases.",
"Do not include reasoning.",
- "Use only the provided task definitions. Do not invent apps, task types, entities, or actions.",
+ "Use only the provided task definitions. Do not invent task types, unsupported 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 dynamic local-item capabilities, app/file/folder names may come from the request, relevant local cache, or default-app inference; the catalog will verify availability before execution.",
+ "For local_app_interaction, select the most likely local app for the user's goal, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.",
+ "For local_app_interaction, fill actionPlan.tools with allowed tools only: app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",
+ "For local_app_interaction, set actionPlan.inputEntity to query when ui.setText should type the query, and set actionPlan.controlID/focusKey for the UI control strategy.",
+ "For every other task type, actionPlan.tools must be empty.",
"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)",
+ "Relevant local cache:",
+ context,
"Supported task capabilities:",
tasks
]
@@ -426,6 +449,39 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
}
}
+public struct FallbackTaskIntentParsingAdapter: TaskIntentParsingAdapter {
+ public var primary: any TaskIntentParsingAdapter
+ public var fallback: any TaskIntentParsingAdapter
+
+ public init(
+ primary: any TaskIntentParsingAdapter,
+ fallback: any TaskIntentParsingAdapter
+ ) {
+ self.primary = primary
+ self.fallback = fallback
+ }
+
+ public func parseTaskIntent(_ request: TaskIntentAdapterRequest) async -> TaskIntentAdapterResult {
+ let primaryResult = await primary.parseTaskIntent(request)
+ guard primaryResult.intent == nil,
+ [.invalidOutput, .providerOutage, .timeout].contains(primaryResult.trace.status)
+ else {
+ return primaryResult
+ }
+
+ let fallbackResult = await fallback.parseTaskIntent(request)
+ guard fallbackResult.intent != nil else {
+ return primaryResult
+ }
+
+ var trace = fallbackResult.trace
+ trace.metadata["fallback.primaryStatus"] = primaryResult.trace.status.rawValue
+ trace.metadata["fallback.primaryValidation"] = primaryResult.trace.validationStatus
+ trace.metadata["fallback.used"] = "true"
+ return TaskIntentAdapterResult(intent: fallbackResult.intent, trace: trace)
+ }
+}
+
public struct LocalModelTaskIntentResolver: Sendable {
public var catalog: LocalAppTaskCatalog
public var adapter: any TaskIntentParsingAdapter
@@ -433,7 +489,10 @@ public struct LocalModelTaskIntentResolver: Sendable {
public init(
catalog: LocalAppTaskCatalog,
adapter: any TaskIntentParsingAdapter = PriorityQueuedTaskIntentParsingAdapter(
- base: ProcessBackedLocalLLMTaskIntentAdapter()
+ base: FallbackTaskIntentParsingAdapter(
+ primary: ProcessBackedLocalLLMTaskIntentAdapter(),
+ fallback: OllamaTaskIntentAdapter()
+ )
)
) {
self.catalog = catalog
@@ -448,6 +507,7 @@ public struct LocalModelTaskIntentResolver: Sendable {
TaskIntentAdapterRequest(
command: command,
taskDefinitions: catalog.taskDefinitions,
+ contextSnippets: SQLiteAgentMemoryStore.shared?.contextSnippets(for: command) ?? [],
sourceTraceID: sourceTraceID
)
)
@@ -481,6 +541,34 @@ private enum TaskIntentWireCodec {
let targetAppNameSchema: [String: Any] = allowsDynamicTargets
? ["type": "string"]
: ["type": "string", "enum": Array(Set(taskDefinitions.map(\.targetApp.appName))).sorted()]
+ let actionPlanSchema: [String: Any] = [
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "tools",
+ "inputEntity",
+ "controlID",
+ "focusKey",
+ "verification"
+ ],
+ "properties": [
+ "tools": [
+ "type": "array",
+ "maxItems": 8,
+ "items": [
+ "type": "string",
+ "enum": LocalAppActionPlanTool.allCases.map(\.rawValue)
+ ]
+ ],
+ "inputEntity": ["type": "string"],
+ "controlID": ["type": "string"],
+ "focusKey": ["type": "string"],
+ "verification": [
+ "type": "string",
+ "enum": LocalAppActionPlanVerification.allCases.map(\.rawValue)
+ ]
+ ]
+ ]
return [
"type": "object",
@@ -492,6 +580,7 @@ private enum TaskIntentWireCodec {
"normalizedEntities",
"confidence",
"needsConfirmation",
+ "actionPlan",
"metadata"
],
"properties": [
@@ -507,6 +596,7 @@ private enum TaskIntentWireCodec {
],
"confidence": ["type": "number", "minimum": 0, "maximum": 1],
"needsConfirmation": ["type": "boolean"],
+ "actionPlan": actionPlanSchema,
"metadata": [
"type": "object",
"additionalProperties": ["type": "string"]
@@ -532,6 +622,9 @@ private enum TaskIntentWireCodec {
guard let definition = exactDefinition ?? dynamicDefinition else {
return nil
}
+ guard definition.metadata["modelPlanned"] == "true" || wire.actionPlan.tools.isEmpty else {
+ return nil
+ }
var entities = wire.entities
var normalizedEntities = normalizedEntities(from: wire, definition: definition)
@@ -554,6 +647,7 @@ private enum TaskIntentWireCodec {
}
let needsConfirmation = wire.needsConfirmation || missingRequiredEntity != nil
+ let actionPlan = wire.actionPlan.tools.isEmpty ? nil : wire.actionPlan
let primaryEntity = definition.verificationEntityName
.flatMap { normalizedEntities[$0] }
?? normalizedEntities.values.sorted().first
@@ -571,6 +665,7 @@ private enum TaskIntentWireCodec {
parserSource: .localModel,
needsConfirmation: needsConfirmation,
sourceModelCallID: sourceModelCallID,
+ actionPlan: actionPlan,
metadata: metadata
)
}
@@ -620,6 +715,7 @@ private struct TaskIntentWire: Decodable {
var normalizedEntities: [String: String]
var confidence: Double
var needsConfirmation: Bool
+ var actionPlan: LocalAppActionPlan
var metadata: [String: String]
}
diff --git a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift
index 47e6d743..5eedeeea 100644
--- a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift
@@ -25,6 +25,65 @@ public struct LocalAppTarget: Codable, Equatable, Sendable {
}
}
+public enum LocalAppActionPlanTool: String, Codable, CaseIterable, Equatable, Sendable {
+ case openOrFocusApp = "app.openOrFocus"
+ case observeApp = "app.observe"
+ case focusSearch = "ui.focusSearch"
+ case setText = "ui.setText"
+ case pressReturn = "ui.pressReturn"
+ case verifyCommand = "app.verifyCommand"
+ case verifyVisibleText = "app.verifyVisibleText"
+}
+
+public enum LocalAppActionPlanVerification: String, Codable, CaseIterable, Equatable, Sendable {
+ case commandAttempted
+ case visibleText
+}
+
+public struct LocalAppActionPlan: Codable, Equatable, Sendable {
+ public var tools: [LocalAppActionPlanTool]
+ public var inputEntity: String
+ public var controlID: String
+ public var focusKey: String
+ public var verification: LocalAppActionPlanVerification
+
+ public init(
+ tools: [LocalAppActionPlanTool],
+ inputEntity: String = "query",
+ controlID: String = "search",
+ focusKey: String = "Command+F",
+ verification: LocalAppActionPlanVerification = .commandAttempted
+ ) {
+ self.tools = tools
+ self.inputEntity = inputEntity
+ self.controlID = controlID
+ self.focusKey = focusKey
+ self.verification = verification
+ }
+
+ public static var defaultSearchSubmitPlan: LocalAppActionPlan {
+ LocalAppActionPlan(
+ tools: [
+ .openOrFocusApp,
+ .observeApp,
+ .focusSearch,
+ .setText,
+ .pressReturn,
+ .verifyCommand
+ ]
+ )
+ }
+
+ public var isExecutable: Bool {
+ tools.isEmpty == false
+ && tools.contains(where: { $0 == .setText || $0 == .pressReturn })
+ }
+
+ public var requiresTextInput: Bool {
+ tools.contains(.setText)
+ }
+}
+
public struct TaskIntent: Codable, Equatable, Sendable {
public var intentID: String
public var taskType: String
@@ -35,6 +94,7 @@ public struct TaskIntent: Codable, Equatable, Sendable {
public var parserSource: TaskIntentParserSource
public var needsConfirmation: Bool
public var sourceModelCallID: String?
+ public var actionPlan: LocalAppActionPlan?
public var metadata: [String: String]
public init(
@@ -47,6 +107,7 @@ public struct TaskIntent: Codable, Equatable, Sendable {
parserSource: TaskIntentParserSource,
needsConfirmation: Bool = false,
sourceModelCallID: String? = nil,
+ actionPlan: LocalAppActionPlan? = nil,
metadata: [String: String] = [:]
) {
self.intentID = intentID
@@ -58,6 +119,7 @@ public struct TaskIntent: Codable, Equatable, Sendable {
self.parserSource = parserSource
self.needsConfirmation = needsConfirmation
self.sourceModelCallID = sourceModelCallID
+ self.actionPlan = actionPlan
self.metadata = metadata
}
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
index 1b3d703e..a404ea36 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
@@ -666,6 +666,9 @@ public struct LocalAppTaskCatalog: Sendable {
if intent.taskType == Self.genericAppOpenTaskType {
return resolveGenericAppOpen(intent: intent)
}
+ if intent.taskType == Self.genericLocalAppInteractionTaskType {
+ return resolveGenericLocalAppInteraction(intent: intent)
+ }
guard let definition = taskDefinitions.first(where: { supports(intent: intent, definition: $0) }) else {
return LocalAppTaskCatalogResolution(
@@ -780,10 +783,124 @@ public struct LocalAppTaskCatalog: Sendable {
)
}
+ private func resolveGenericLocalAppInteraction(intent: TaskIntent) -> LocalAppTaskCatalogResolution {
+ let requestedAppName = intent.metadata["requestedItemName"]
+ ?? intent.normalizedEntities["appName"]
+ ?? intent.entities["appName"]
+ ?? intent.targetApp.appName
+ let cleanedRequestedAppName = LocalAppLookup.cleanedLookupName(requestedAppName)
+ guard !cleanedRequestedAppName.isEmpty,
+ cleanedRequestedAppName != LocalAppLookup.cleanedLookupName(Self.genericLocalAppInteractionTarget.appName)
+ else {
+ return LocalAppTaskCatalogResolution(
+ status: .needsConfirmation,
+ intent: intent,
+ definition: Self.genericLocalAppInteractionDefinition,
+ metadata: [
+ "reason": "appName",
+ "taskType": Self.genericLocalAppInteractionTaskType
+ ]
+ )
+ }
+
+ guard let plan = intent.actionPlan else {
+ return LocalAppTaskCatalogResolution(
+ status: .needsConfirmation,
+ intent: intent,
+ definition: Self.genericLocalAppInteractionDefinition,
+ metadata: [
+ "reason": "missingActionPlan",
+ "taskType": Self.genericLocalAppInteractionTaskType,
+ "targetApp": cleanedRequestedAppName
+ ]
+ )
+ }
+ guard plan.isExecutable else {
+ return LocalAppTaskCatalogResolution(
+ status: .needsConfirmation,
+ intent: intent,
+ definition: Self.genericLocalAppInteractionDefinition,
+ metadata: [
+ "reason": "invalidActionPlan",
+ "taskType": Self.genericLocalAppInteractionTaskType,
+ "targetApp": cleanedRequestedAppName,
+ "plan.tools": plan.tools.map(\.rawValue).joined(separator: ",")
+ ]
+ )
+ }
+
+ let inputEntity = plan.inputEntity
+ if plan.requiresTextInput,
+ Self.entityValue(named: inputEntity, in: intent).isEmpty {
+ return LocalAppTaskCatalogResolution(
+ status: .needsConfirmation,
+ intent: intent,
+ definition: Self.genericLocalAppInteractionDefinition,
+ metadata: [
+ "reason": inputEntity,
+ "taskType": Self.genericLocalAppInteractionTaskType,
+ "targetApp": cleanedRequestedAppName
+ ]
+ )
+ }
+
+ let availability = availabilityProvider.availability(namedApp: cleanedRequestedAppName)
+ let target = availability.target
+ let definition = Self.genericLocalAppInteractionDefinition(
+ target: target,
+ plan: plan
+ )
+ 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"] ?? "",
+ "plan.tools": plan.tools.map(\.rawValue).joined(separator: ",")
+ ]
+ )
+ }
+
public static var genericLocalItemOpenDefinition: LocalAppTaskDefinition {
genericAppOpenDefinition(target: genericLocalItemTarget)
}
+ public static var genericLocalAppInteractionDefinition: LocalAppTaskDefinition {
+ genericLocalAppInteractionDefinition(
+ target: genericLocalAppInteractionTarget,
+ plan: .defaultSearchSubmitPlan
+ )
+ }
+
public static func genericAppOpenDefinition(target: LocalAppTarget) -> LocalAppTaskDefinition {
LocalAppTaskDefinition(
taskType: genericAppOpenTaskType,
@@ -821,6 +938,125 @@ public struct LocalAppTaskCatalog: Sendable {
)
}
+ public static func genericLocalAppInteractionDefinition(
+ target: LocalAppTarget,
+ plan: LocalAppActionPlan
+ ) -> LocalAppTaskDefinition {
+ let inputEntity = plan.inputEntity
+ var metadata: [String: String] = [
+ "catalogEntry": "generic-local-app-interaction",
+ "displayTitle": "local app interaction",
+ "taskLabelTemplate": "Use {appName}",
+ "verificationTextKey": inputEntity,
+ "domain": "app",
+ "dynamicTarget": target.metadata["dynamicTarget"] ?? "false",
+ "modelPlanned": "true",
+ "plan.tools": plan.tools.map(\.rawValue).joined(separator: ","),
+ "plan.inputEntity": inputEntity,
+ "plan.allowedTools": LocalAppActionPlanTool.allCases.map(\.rawValue).joined(separator: ",")
+ ]
+ metadata["verificationMode"] = plan.verification == .visibleText
+ ? "visibleText"
+ : "commandAttempted"
+
+ return LocalAppTaskDefinition(
+ taskType: genericLocalAppInteractionTaskType,
+ targetApp: target,
+ triggerTerms: [],
+ entityRules: [
+ LocalAppTaskEntityRule(
+ name: "appName",
+ required: true,
+ metadata: [
+ "dynamicLookupEntity": "true",
+ "description": "Requested local app selected by the model"
+ ]
+ ),
+ LocalAppTaskEntityRule(
+ name: "goal",
+ required: true,
+ metadata: ["description": "Short model-selected action goal"]
+ ),
+ LocalAppTaskEntityRule(
+ name: "query",
+ required: false,
+ metadata: ["description": "Text to enter when the model plan includes set_text"]
+ )
+ ],
+ workflowSteps: Self.workflowSteps(for: plan),
+ observationStrategies: [.accessibility, .windowMetadata, .screenshotForLocalModel],
+ verificationEntityName: inputEntity,
+ metadata: metadata
+ )
+ }
+
+ private static func workflowSteps(
+ for plan: LocalAppActionPlan
+ ) -> [LocalAppTaskWorkflowStepDefinition] {
+ var steps = BuiltInLocalAppTaskDefinitions.commonWorkflowPrefix
+ var submitIndex = 1
+ let inputEntity = plan.inputEntity
+ for tool in plan.tools {
+ switch tool {
+ case .openOrFocusApp, .observeApp:
+ continue
+ case .focusSearch:
+ steps.append(LocalAppTaskWorkflowStepDefinition(
+ id: "model-plan-focus-search",
+ role: .focusControl,
+ summary: "Focus the model-selected search control",
+ metadata: [
+ "controlID": plan.controlID,
+ "key": plan.focusKey,
+ "plan.tool": tool.rawValue
+ ]
+ ))
+ case .setText:
+ steps.append(LocalAppTaskWorkflowStepDefinition(
+ id: "model-plan-set-text",
+ role: .enterText,
+ summary: "Enter the model-selected text entity",
+ metadata: [
+ "controlID": plan.controlID,
+ "entityName": inputEntity,
+ "plan.tool": tool.rawValue
+ ]
+ ))
+ case .pressReturn:
+ steps.append(LocalAppTaskWorkflowStepDefinition(
+ id: "model-plan-press-return-\(submitIndex)",
+ role: .submit,
+ summary: "Submit the model-planned action",
+ metadata: [
+ "key": "Return",
+ "plan.tool": tool.rawValue
+ ]
+ ))
+ submitIndex += 1
+ case .verifyCommand, .verifyVisibleText:
+ steps.append(LocalAppTaskWorkflowStepDefinition(
+ id: "model-plan-verify",
+ role: .verifyResult,
+ summary: "Verify the model-planned action",
+ metadata: ["plan.tool": tool.rawValue]
+ ))
+ }
+ }
+ if steps.contains(where: { $0.role == .verifyResult }) == false {
+ steps.append(LocalAppTaskWorkflowStepDefinition(
+ id: "model-plan-verify",
+ role: .verifyResult,
+ summary: "Verify the model-planned action"
+ ))
+ }
+ return steps
+ }
+
+ private static func entityValue(named entityName: String, in intent: TaskIntent) -> String {
+ (intent.normalizedEntities[entityName] ?? intent.entities[entityName] ?? "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
private func slug(_ value: String) -> String {
LocalAppTaskIntentParser.normalizedPhrase(value)
.split(separator: " ")
@@ -828,6 +1064,7 @@ public struct LocalAppTaskCatalog: Sendable {
}
private static let genericAppOpenTaskType = "app_open"
+ private static let genericLocalAppInteractionTaskType = "local_app_interaction"
private static let minimumModelIntentConfidence = 0.55
private static var genericLocalItemTarget: LocalAppTarget {
LocalAppTarget(
@@ -839,6 +1076,16 @@ public struct LocalAppTaskCatalog: Sendable {
]
)
}
+ private static var genericLocalAppInteractionTarget: LocalAppTarget {
+ LocalAppTarget(
+ appName: "Local App",
+ titleContains: nil,
+ metadata: [
+ "dynamicTarget": "true",
+ "localItem.kind": LocalItemKind.application.rawValue
+ ]
+ )
+ }
}
public enum BuiltInLocalAppTaskDefinitions {
@@ -1056,6 +1303,7 @@ public enum BuiltInLocalAppTaskDefinitions {
public static var benchmarkFixtures: [LocalAppTaskDefinition] {
[
LocalAppTaskCatalog.genericLocalItemOpenDefinition,
+ LocalAppTaskCatalog.genericLocalAppInteractionDefinition,
weatherLookup,
mediaPlayback,
documentFormFill
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift
index 4fb259df..3820289c 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift
@@ -71,7 +71,8 @@ public struct LocalAppTaskDefinitionLoader: Sendable {
public static var runtimeSeedDefinitions: [LocalAppTaskDefinition] {
[
- LocalAppTaskCatalog.genericLocalItemOpenDefinition
+ LocalAppTaskCatalog.genericLocalItemOpenDefinition,
+ LocalAppTaskCatalog.genericLocalAppInteractionDefinition
]
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index 5a2bb911..06a8afa3 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -325,7 +325,7 @@ struct AIHarnessAdapterTests {
let httpClient = FakeAIHTTPClient(
data: ollamaResponseData(
response: """
- {"taskType":"weather_lookup","targetAppName":"Weather","entities":{"city":"SF"},"normalizedEntities":{"city":"San Francisco"},"confidence":0.93,"needsConfirmation":false,"metadata":{"source":"test"}}
+ {"taskType":"weather_lookup","targetAppName":"Weather","entities":{"city":"SF"},"normalizedEntities":{"city":"San Francisco"},"confidence":0.93,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{"source":"test"}}
"""
),
statusCode: 200
@@ -373,7 +373,7 @@ struct AIHarnessAdapterTests {
#expect(body["format"] as? [String: Any] != nil)
#expect(body["keep_alive"] as? String == "10m")
let options = try #require(body["options"] as? [String: Any])
- #expect(options["num_predict"] as? Int == 128)
+ #expect(options["num_predict"] as? Int == 256)
#expect(options["num_ctx"] as? Int == 2048)
#expect((body["prompt"] as? String)?.contains("Use only the provided task definitions") == true)
#expect((body["prompt"] as? String)?.contains("Choose by capability and target app") == true)
@@ -390,7 +390,7 @@ struct AIHarnessAdapterTests {
result: LocalJSONSidecarResult(
status: .completed,
outputData: Data("""
- {"outputText":"{\\"taskType\\":\\"media_playback\\",\\"targetAppName\\":\\"Music\\",\\"entities\\":{\\"query\\":\\"cold play\\"},\\"normalizedEntities\\":{\\"query\\":\\"Cold Play\\"},\\"confidence\\":0.91,\\"needsConfirmation\\":false,\\"metadata\\":{\\"source\\":\\"test\\"}}","metadata":{"local.provider":"ollama-sidecar"}}
+ {"outputText":"{\\"taskType\\":\\"media_playback\\",\\"targetAppName\\":\\"Music\\",\\"entities\\":{\\"query\\":\\"cold play\\"},\\"normalizedEntities\\":{\\"query\\":\\"Cold Play\\"},\\"confidence\\":0.91,\\"needsConfirmation\\":false,\\"actionPlan\\":{\\"tools\\":[],\\"inputEntity\\":\\"\\",\\"controlID\\":\\"\\",\\"focusKey\\":\\"\\",\\"verification\\":\\"commandAttempted\\"},\\"metadata\\":{\\"source\\":\\"test\\"}}","metadata":{"local.provider":"ollama-sidecar"}}
""".utf8),
latencyMS: 14,
metadata: ["sidecar.role": "taskIntent"]
@@ -415,12 +415,45 @@ struct AIHarnessAdapterTests {
#expect(result.trace.metadata["local.provider"] == "ollama-sidecar")
}
+ @Test
+ func processBackedLocalLLMTaskIntentAdapterDecodesGenericPlannedInteraction() async throws {
+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(
+ router: AIModelRouter(registry: .defaultHybridPlanner),
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: Data("""
+ {"outputText":"{\\"taskType\\":\\"local_app_interaction\\",\\"targetAppName\\":\\"Music\\",\\"entities\\":{\\"appName\\":\\"Music\\",\\"goal\\":\\"play media\\",\\"query\\":\\"justin bieber\\"},\\"normalizedEntities\\":{\\"appName\\":\\"Music\\",\\"goal\\":\\"play media\\",\\"query\\":\\"Justin Bieber\\"},\\"confidence\\":0.91,\\"needsConfirmation\\":false,\\"actionPlan\\":{\\"tools\\":[\\"app.openOrFocus\\",\\"app.observe\\",\\"ui.focusSearch\\",\\"ui.setText\\",\\"ui.pressReturn\\",\\"ui.pressReturn\\",\\"app.verifyCommand\\"],\\"inputEntity\\":\\"query\\",\\"controlID\\":\\"search\\",\\"focusKey\\":\\"Command+F\\",\\"verification\\":\\"commandAttempted\\"},\\"metadata\\":{}}","metadata":{"local.provider":"ollama-sidecar"}}
+ """.utf8),
+ latencyMS: 14,
+ metadata: ["sidecar.role": "taskIntent"]
+ )
+ )
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "play some justin bieber",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ contextSnippets: ["Music application com.apple.Music"],
+ sourceTraceID: "trace-local-app-plan"
+ )
+ )
+
+ #expect(result.intent?.taskType == "local_app_interaction")
+ #expect(result.intent?.targetApp.appName == "Music")
+ #expect(result.intent?.normalizedEntities["query"] == "Justin Bieber")
+ #expect(result.intent?.actionPlan?.tools.contains(.setText) == true)
+ #expect(result.intent?.actionPlan?.inputEntity == "query")
+ #expect(result.trace.status == .completed)
+ }
+
@Test
func localModelTaskIntentResolverValidatesAgainstCatalogAvailability() async {
let httpClient = FakeAIHTTPClient(
data: ollamaResponseData(
response: """
- {"taskType":"weather_lookup","targetAppName":"Weather","entities":{"city":"SF"},"normalizedEntities":{"city":"San Francisco"},"confidence":0.93,"needsConfirmation":false,"metadata":{}}
+ {"taskType":"weather_lookup","targetAppName":"Weather","entities":{"city":"SF"},"normalizedEntities":{"city":"San Francisco"},"confidence":0.93,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{}}
"""
),
statusCode: 200
@@ -465,7 +498,7 @@ struct AIHarnessAdapterTests {
let httpClient = FakeAIHTTPClient(
data: ollamaResponseData(
response: """
- {"taskType":"app_open","targetAppName":"Figma","entities":{"appName":"figma"},"normalizedEntities":{"appName":"Figma"},"confidence":0.94,"needsConfirmation":false,"metadata":{}}
+ {"taskType":"app_open","targetAppName":"Figma","entities":{"appName":"figma"},"normalizedEntities":{"appName":"Figma"},"confidence":0.94,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{}}
"""
),
statusCode: 200
@@ -557,7 +590,7 @@ struct AIHarnessAdapterTests {
let httpClient = FakeAIHTTPClient(
data: ollamaResponseData(
response: """
- {"taskType":"weather_lookup","targetAppName":"Weather","entities":{},"normalizedEntities":{},"confidence":0.2,"needsConfirmation":false,"metadata":{}}
+ {"taskType":"weather_lookup","targetAppName":"Weather","entities":{},"normalizedEntities":{},"confidence":0.2,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{}}
"""
),
statusCode: 200
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
index 559638c9..99033eee 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
@@ -287,6 +287,86 @@ struct LocalAppTaskTests {
#expect(automationCommands.first?.metadata["appleScript.action"] == "music.playMediaQuery")
}
+ @Test
+ func catalogResolvesGenericModelPlannedLocalAppInteraction() throws {
+ let catalog = LocalAppTaskCatalog(
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(
+ installedBundleIdentifiers: ["com.apple.Music"]
+ )
+ )
+
+ let resolution = catalog.resolve(intent: genericLocalAppInteractionIntent(
+ appName: "Music",
+ query: "Justin Bieber",
+ planTools: [
+ .openOrFocusApp,
+ .observeApp,
+ .focusSearch,
+ .setText,
+ .pressReturn,
+ .pressReturn,
+ .verifyCommand
+ ]
+ ))
+ 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,
+ availableControls: ["search": true],
+ confidence: 0.7
+ )
+ )
+
+ #expect(resolution.status == .resolved)
+ #expect(intent.taskType == "local_app_interaction")
+ #expect(intent.targetApp.appName == "Music")
+ #expect(intent.targetApp.bundleIdentifier == "com.apple.Music")
+ #expect(definition.metadata["modelPlanned"] == "true")
+ #expect(definition.metadata["plan.tools"] == "app.openOrFocus,app.observe,ui.focusSearch,ui.setText,ui.pressReturn,ui.pressReturn,app.verifyCommand")
+ #expect(plan.terminalState == .completed)
+ #expect(plan.steps.map(\.role) == [
+ .parseIntent,
+ .launchOrFocusApp,
+ .observeApp,
+ .focusControl,
+ .enterText,
+ .submit,
+ .submit,
+ .verifyResult
+ ])
+
+ let commands = localAdapter.guardedKeyboardCommandTemplates(
+ for: intent,
+ issuedAt: timestamp(100)
+ )
+ #expect(commands.map(\.key) == ["Command+F", "Justin Bieber", "Return", "Return"])
+ #expect(commands.first?.metadata["plan.tool"] == "ui.focusSearch")
+ }
+
+ @Test
+ func genericModelPlannedInteractionRequiresTypedActionPlanBeforeExecution() {
+ let catalog = LocalAppTaskCatalog(
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(
+ installedBundleIdentifiers: ["com.apple.Music"]
+ )
+ )
+
+ let resolution = catalog.resolve(intent: genericLocalAppInteractionIntent(
+ appName: "Music",
+ query: "Justin Bieber",
+ planTools: nil
+ ))
+
+ #expect(resolution.status == .needsConfirmation)
+ #expect(resolution.metadata["reason"] == "missingActionPlan")
+ }
+
@Test
func catalogResolvesStructuredIntentAgainstAvailableInstalledAppDefinition() throws {
let catalog = LocalAppTaskCatalog(
@@ -411,8 +491,8 @@ struct LocalAppTaskTests {
loader: loader
)
- #expect(catalog.taskDefinitions.map(\.taskType) == ["app_open"])
- #expect(store?.taskDefinitions().map(\.taskType) == ["app_open"])
+ #expect(catalog.taskDefinitions.map(\.taskType) == ["app_open", "local_app_interaction"])
+ #expect(store?.taskDefinitions().map(\.taskType) == ["app_open", "local_app_interaction"])
#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)
@@ -894,6 +974,44 @@ struct LocalAppTaskTests {
)
}
+ private func genericLocalAppInteractionIntent(
+ appName: String,
+ query: String,
+ planTools: [LocalAppActionPlanTool]?,
+ confidence: Double = 0.93
+ ) -> TaskIntent {
+ let actionPlan = planTools.map {
+ LocalAppActionPlan(
+ tools: $0,
+ inputEntity: "query",
+ controlID: "search",
+ focusKey: "Command+F",
+ verification: .commandAttempted
+ )
+ }
+ return TaskIntent(
+ intentID: "local_app_interaction-\(slug(query))",
+ taskType: "local_app_interaction",
+ targetApp: LocalAppTarget(appName: appName, titleContains: appName),
+ entities: [
+ "appName": appName,
+ "goal": "play media",
+ "query": query
+ ],
+ normalizedEntities: [
+ "appName": appName,
+ "goal": "play media",
+ "query": query
+ ],
+ confidence: confidence,
+ parserSource: .localModel,
+ actionPlan: actionPlan,
+ metadata: [
+ "requestedItemName": appName
+ ]
+ )
+ }
+
private func documentFormFillIntent(confidence: Double = 0.9) -> TaskIntent {
let definition = BuiltInLocalAppTaskDefinitions.documentFormFill
return TaskIntent(
diff --git a/scripts/local-runtime-runners/donkey_runtime_runner.py b/scripts/local-runtime-runners/donkey_runtime_runner.py
index f1368200..6da18a32 100644
--- a/scripts/local-runtime-runners/donkey_runtime_runner.py
+++ b/scripts/local-runtime-runners/donkey_runtime_runner.py
@@ -482,9 +482,9 @@ def run_local_llm(request: dict[str, Any]) -> dict[str, Any]:
max_tokens = 240
else:
task_definitions = request.get("taskDefinitions", [])
- prompt = task_intent_prompt(command, task_definitions)
+ prompt = task_intent_prompt(command, task_definitions, request.get("contextSnippets", []))
schema = task_intent_schema(task_definitions)
- max_tokens = 128
+ max_tokens = 256
body = {
"model": request.get("modelID") or MODEL_ID,
"prompt": prompt,
@@ -644,10 +644,15 @@ def pointer_coach_cursor_guide_schema() -> dict[str, Any]:
}
-def task_intent_prompt(command: str, task_definitions: list[dict[str, Any]]) -> str:
+def task_intent_prompt(
+ command: str,
+ task_definitions: list[dict[str, Any]],
+ context_snippets: list[Any] | None = None,
+) -> str:
task_lines: list[str] = []
for definition in task_definitions:
target = definition.get("targetApp", {})
+ definition_metadata = definition.get("metadata") or {}
entity_parts = []
for rule in definition.get("entityRules", []):
aliases = ",".join(sorted((rule.get("aliases") or {}).keys()))
@@ -659,29 +664,43 @@ def task_intent_prompt(command: str, task_definitions: list[dict[str, Any]]) ->
for step in definition.get("workflowSteps", [])
if step.get("role") != "parseIntent" and step.get("summary")
)
- task_lines.append(
- " | ".join(
+ model_plan = ""
+ if definition_metadata.get("modelPlanned") == "true":
+ model_plan = " | ".join(
[
- f"task_type={definition.get('taskType')}",
- f"app={target.get('appName')}",
- f"bundle={target.get('bundleIdentifier', 'unknown')}",
- f"capability={workflow}",
- f"entities={'; '.join(entity_parts)}",
- f"dynamic_target={(definition.get('metadata') or {}).get('dynamicTarget', 'false')}",
+ "model_plan=true",
+ f"allowed_tools={definition_metadata.get('plan.allowedTools', '')}",
+ "action_plan_required=true",
]
)
- )
+ parts = [
+ f"task_type={definition.get('taskType')}",
+ f"app={target.get('appName')}",
+ f"bundle={target.get('bundleIdentifier', 'unknown')}",
+ f"capability={workflow}",
+ f"entities={'; '.join(entity_parts)}",
+ f"dynamic_target={definition_metadata.get('dynamicTarget', 'false')}",
+ model_plan,
+ ]
+ task_lines.append(" | ".join(item for item in parts if item))
+ context = "\n".join(str(item) for item in (context_snippets or [])[:8] if str(item).strip())
return "\n".join(
[
"Classify the user's natural-language request into exactly one supported local app task intent, then return strict JSON.",
"Choose by capability and target app, not by exact wording. The user should not need to remember command phrases.",
"Do not include reasoning.",
- "Use only the provided task definitions. Do not invent apps, task types, entities, or actions.",
+ "Use only the provided task definitions. Do not invent task types, unsupported 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 dynamic local-item capabilities, app/file/folder names may come from the request, relevant local cache, or default-app inference; the catalog will verify availability before execution.",
+ "For local_app_interaction, select the most likely local app for the user's goal, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.",
+ "For local_app_interaction, fill actionPlan.tools with allowed tools only: app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",
+ "For local_app_interaction, set actionPlan.inputEntity to query when ui.setText should type the query, and set actionPlan.controlID/focusKey for the UI control strategy.",
+ "For every other task type, actionPlan.tools must be empty.",
f"Command: {command}",
+ "Relevant local cache:",
+ context,
"Supported task capabilities:",
"\n".join(task_lines),
]
@@ -704,6 +723,39 @@ def task_intent_schema(task_definitions: list[dict[str, Any]]) -> dict[str, Any]
target_app_name_schema: dict[str, Any] = {"type": "string"}
if not allows_dynamic_targets:
target_app_name_schema["enum"] = app_names
+ action_plan_schema = {
+ "type": "object",
+ "additionalProperties": False,
+ "required": [
+ "tools",
+ "inputEntity",
+ "controlID",
+ "focusKey",
+ "verification",
+ ],
+ "properties": {
+ "tools": {
+ "type": "array",
+ "maxItems": 8,
+ "items": {
+ "type": "string",
+ "enum": [
+ "app.openOrFocus",
+ "app.observe",
+ "ui.focusSearch",
+ "ui.setText",
+ "ui.pressReturn",
+ "app.verifyCommand",
+ "app.verifyVisibleText",
+ ],
+ },
+ },
+ "inputEntity": {"type": "string"},
+ "controlID": {"type": "string"},
+ "focusKey": {"type": "string"},
+ "verification": {"type": "string", "enum": ["commandAttempted", "visibleText"]},
+ },
+ }
return {
"type": "object",
@@ -715,6 +767,7 @@ def task_intent_schema(task_definitions: list[dict[str, Any]]) -> dict[str, Any]
"normalizedEntities",
"confidence",
"needsConfirmation",
+ "actionPlan",
"metadata",
],
"properties": {
@@ -724,6 +777,7 @@ def task_intent_schema(task_definitions: list[dict[str, Any]]) -> dict[str, Any]
"normalizedEntities": {"type": "object", "additionalProperties": {"type": "string"}},
"confidence": {"type": "number", "minimum": 0, "maximum": 1},
"needsConfirmation": {"type": "boolean"},
+ "actionPlan": action_plan_schema,
"metadata": {"type": "object", "additionalProperties": {"type": "string"}},
},
}