Open source CapCut alternative.
TypeScript
Ground local app selection in app finder catalog
David Leeb264e6ce3d5
diff --git a/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swiftindex ab07c7f8..fc49d4a7 100644--- a/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift@@ -6,6 +6,7 @@ public struct TaskIntentAdapterRequest: Equatable, Sendable {public var command: Stringpublic var taskDefinitions: [LocalAppTaskDefinition]public var contextSnippets: [String]+ public var appFinderCatalog: [LocalAppFinderCatalogEntry]public var sourceTraceID: Stringpublic var routeRequest: AIModelRouteRequest@@ -13,6 +14,7 @@ public struct TaskIntentAdapterRequest: Equatable, Sendable {command: String,taskDefinitions: [LocalAppTaskDefinition],contextSnippets: [String] = [],+ appFinderCatalog: [LocalAppFinderCatalogEntry] = [],sourceTraceID: String,routeRequest: AIModelRouteRequest = AIModelRouteRequest(jobType: .taskIntent,@@ -23,6 +25,7 @@ public struct TaskIntentAdapterRequest: Equatable, Sendable {self.command = commandself.taskDefinitions = taskDefinitionsself.contextSnippets = contextSnippets+ self.appFinderCatalog = appFinderCatalogself.sourceTraceID = sourceTraceIDself.routeRequest = routeRequest}@@ -83,6 +86,7 @@ public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {command: request.command,taskDefinitions: request.taskDefinitions,contextSnippets: request.contextSnippets,+ appFinderCatalog: request.appFinderCatalog,sourceTraceID: request.sourceTraceID,modelID: entry.modelID,cacheDirectory: LocalModelRuntimeExecutableResolver().modelCacheDirectoryPath(@@ -139,6 +143,7 @@ public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {response.outputText,definitions: request.taskDefinitions,originalCommand: request.command,+ appFinderCatalog: request.appFinderCatalog,sourceModelCallID: "model-call-\(request.sourceTraceID)",parserName: "local-llm-sidecar-v1") else {@@ -290,6 +295,7 @@ private struct LocalLLMTaskIntentSidecarRequest: Codable, Equatable, Sendable {var command: Stringvar taskDefinitions: [LocalAppTaskDefinition]var contextSnippets: [String]+ var appFinderCatalog: [LocalAppFinderCatalogEntry]var sourceTraceID: Stringvar modelID: Stringvar cacheDirectory: String?@@ -409,6 +415,7 @@ public struct LocalGenerateTaskIntentAdapter: TaskIntentParsingAdapter {outputText,definitions: request.taskDefinitions,originalCommand: request.command,+ appFinderCatalog: request.appFinderCatalog,sourceModelCallID: "model-call-\(request.sourceTraceID)",parserName: "local-generate-task-intent-v1")@@ -613,6 +620,7 @@ public struct LocalGenerateTaskIntentAdapter: TaskIntentParsingAdapter {.filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }.prefix(8).joined(separator: "\n")+ let appFinderCatalog = taskIntentAppFinderCatalogJSON(request.appFinderCatalog)return ["You are Donkey's local task-intent boundary. Return strict JSON only; do not include reasoning.",@@ -646,9 +654,15 @@ public struct LocalGenerateTaskIntentAdapter: TaskIntentParsingAdapter {"Example malformed request output shape: {\"taskType\":\"local_app_interaction\",\"targetAppName\":\"Notes\",\"entities\":{\"appName\":\"Notes\",\"goal\":\"unclear local writing request\"},\"normalizedEntities\":{\"appName\":\"Notes\",\"goal\":\"unclear local writing request\"},\"confidence\":0.2,\"needsConfirmation\":false,\"actionPlan\":{\"tools\":[],\"inputEntity\":\"query\",\"controlID\":\"\",\"focusKey\":\"\",\"verification\":\"commandAttempted\"},\"metadata\":{\"responseMode\":\"conversation\",\"assistantResponse\":\"I can help, but I need a clearer thing to write before opening an app.\"}}","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.",+ "App finder catalog entries are installed local apps with descriptions, support status, capabilities, and control profiles.",+ "When App finder catalog JSON is non-empty and you use local_app_interaction, choose the target app only from a catalog entry with supportStatus=supported and a matching capability.",+ "For local_app_interaction with an app finder choice, set targetAppName and entities.appName to the catalog appName, set metadata.appFinder.selectedAppID to the exact catalog appID, metadata.appFinder.selectedCapabilityID to the chosen capability id, and metadata.appFinder.controlProfile to one control profile from that capability.",+ "Never select catalog entries with supportStatus=candidate, unsupported, or denied for execution; if no supported app capability fits, choose conversation.","Command: \(request.command)","Relevant local cache:",context,+ "App finder catalog JSON:",+ appFinderCatalog,"Supported task capabilities:",tasks]@@ -781,6 +795,7 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {outputText,definitions: request.taskDefinitions,originalCommand: request.command,+ appFinderCatalog: request.appFinderCatalog,sourceModelCallID: "model-call-\(request.sourceTraceID)",parserName: "hosted-responses-v1",parserSource: .onlineModel@@ -869,10 +884,13 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {private func promptText(for request: TaskIntentAdapterRequest) -> String {let definitions = (try? JSONEncoder().encode(request.taskDefinitions)).flatMap { String(data: $0, encoding: .utf8) } ?? "[]"+ let appFinderCatalog = taskIntentAppFinderCatalogJSON(request.appFinderCatalog)return ["Command: \(request.command)","Relevant local cache:",request.contextSnippets.joined(separator: "\n"),+ "App finder catalog JSON:",+ appFinderCatalog,"Supported task definitions JSON:",definitions].joined(separator: "\n")@@ -886,6 +904,7 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {"If Command is conversation, a question, malformed, or lacks a real executable payload, return taskType \"none\", targetAppName \"none\", empty entities, confidence 0, needsConfirmation false, an empty actionPlan, and metadata.responseMode \"conversation\".","For supported actions, choose only a provided taskType and target app. Fill entities and normalizedEntities with the concrete values needed by required entity rules.","Use the generic local_app_interaction task type for executable local app requests that need a model-planned app workflow and do not have a more specific provided task type.",+ "When App finder catalog JSON is non-empty and you use local_app_interaction, choose the target app only from a catalog entry with supportStatus supported and a matching capability. Set metadata.appFinder.selectedAppID to the exact appID, metadata.appFinder.selectedCapabilityID to the capability id, and metadata.appFinder.controlProfile to one declared control profile. Never select candidate, unsupported, or denied entries for execution.","For local_app_interaction, select the most likely local app, set targetAppName and entities.appName to the human app name, 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.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.","When ui.setText is present, entities.query and normalizedEntities.query must be non-empty, actionPlan.inputEntity should usually be query, and actionPlan.controlID/focusKey should describe the guarded UI strategy.",@@ -1045,6 +1064,7 @@ public struct LocalModelTaskIntentResolver: Sendable {command: command,taskDefinitions: catalog.taskDefinitions,contextSnippets: contextSnippets,+ appFinderCatalog: catalog.appFinderCatalogEntries(),sourceTraceID: sourceTraceID)let result = await adapter.parseTaskIntent(request)@@ -1117,6 +1137,41 @@ private struct LocalGenerateModelTag: Decodable {var size: Int64?}+private func taskIntentAppFinderCatalogJSON(_ entries: [LocalAppFinderCatalogEntry]) -> String {+ let compactEntries = entries.map { entry -> [String: Any] in+ var value: [String: Any] = [+ "appID": entry.appID,+ "appName": entry.appName,+ "description": entry.description,+ "supportStatus": entry.supportStatus.rawValue+ ]+ if let bundleIdentifier = entry.bundleIdentifier, !bundleIdentifier.isEmpty {+ value["bundleIdentifier"] = bundleIdentifier+ }+ if entry.capabilities.isEmpty == false {+ value["capabilities"] = entry.capabilities.map { capability -> [String: Any] in+ [+ "id": capability.id,+ "summary": capability.summary,+ "controlProfiles": capability.controlProfiles,+ "requiredEntities": capability.requiredEntities+ ]+ }+ }+ if let denyReason = entry.denyReason, !denyReason.isEmpty {+ value["denyReason"] = denyReason+ }+ return value+ }+ guard compactEntries.isEmpty == false,+ let data = try? JSONSerialization.data(withJSONObject: compactEntries),+ let text = String(data: data, encoding: .utf8)+ else {+ return "[]"+ }+ return text+}+private enum TaskIntentWireCodec {static func jsonSchema(taskDefinitions: [LocalAppTaskDefinition]) -> [String: Any] {let allowsDynamicTargets = taskDefinitions.contains { definition in@@ -1193,6 +1248,7 @@ private enum TaskIntentWireCodec {_ outputText: String,definitions: [LocalAppTaskDefinition],originalCommand: String,+ appFinderCatalog: [LocalAppFinderCatalogEntry] = [],sourceModelCallID: String,parserName: String,parserSource: TaskIntentParserSource = .localModel@@ -1222,11 +1278,32 @@ private enum TaskIntentWireCodec {entities["appName"] = appNamenormalizedEntities["appName"] = appName}+ var metadata = wire.metadata.merging(definition.metadata) { current, _ in current }+ metadata["parser"] = parserName++ let appFinderSelection = validatedAppFinderSelection(+ wire: wire,+ definition: definition,+ appFinderCatalog: appFinderCatalog+ )+ if definition.metadata["modelPlanned"] == "true",+ appFinderCatalog.isEmpty == false,+ appFinderSelection == nil {+ return nil+ }+ if let appFinderSelection {+ entities["appName"] = appFinderSelection.entry.appName+ normalizedEntities["appName"] = appFinderSelection.entry.appName+ metadata["appFinder.selectedAppID"] = appFinderSelection.entry.appID+ metadata["appFinder.selectedCapabilityID"] = appFinderSelection.capability.id+ metadata["appFinder.controlProfile"] = appFinderSelection.controlProfile+ metadata["appFinder.supportStatus"] = appFinderSelection.entry.supportStatus.rawValue+ metadata["appFinder.validated"] = "true"+ }+let missingRequiredEntity = definition.entityRules.first { rule inrule.required && normalizedEntities[rule.name] == nil}- var metadata = wire.metadata.merging(definition.metadata) { current, _ in current }- metadata["parser"] = parserNameif definition.metadata["dynamicTarget"] == "true" {metadata["requestedItemName"] = normalizedEntities["appName"] ?? entities["appName"] ?? ""}@@ -1282,7 +1359,7 @@ private enum TaskIntentWireCodec {? "\(definition.taskType)-needs-\(missingRequiredEntity?.name ?? "confirmation")": "\(definition.taskType)-\(slug(primaryEntity))",taskType: definition.taskType,- targetApp: targetApp(from: wire, definition: definition),+ targetApp: targetApp(from: wire, definition: definition, appFinderEntry: appFinderSelection?.entry),entities: entities,normalizedEntities: normalizedEntities,confidence: confidence,@@ -1600,8 +1677,17 @@ private enum TaskIntentWireCodec {private static func targetApp(from wire: TaskIntentWire,- definition: LocalAppTaskDefinition+ definition: LocalAppTaskDefinition,+ appFinderEntry: LocalAppFinderCatalogEntry? = nil) -> LocalAppTarget {+ if let appFinderEntry {+ return LocalAppTarget(+ appName: appFinderEntry.appName,+ bundleIdentifier: appFinderEntry.bundleIdentifier,+ titleContains: appFinderEntry.appName,+ metadata: definition.targetApp.metadata+ )+ }guard definition.metadata["dynamicTarget"] == "true",wire.targetAppName != definition.targetApp.appName else {return definition.targetApp@@ -1615,6 +1701,105 @@ private enum TaskIntentWireCodec {)}+ private struct AppFinderSelection {+ var entry: LocalAppFinderCatalogEntry+ var capability: LocalAppFinderCapability+ var controlProfile: String+ }++ private static func validatedAppFinderSelection(+ wire: TaskIntentWire,+ definition: LocalAppTaskDefinition,+ appFinderCatalog: [LocalAppFinderCatalogEntry]+ ) -> AppFinderSelection? {+ guard definition.metadata["modelPlanned"] == "true",+ appFinderCatalog.isEmpty == false+ else {+ return nil+ }++ guard let entry = appFinderEntry(from: wire, in: appFinderCatalog),+ entry.supportStatus == .supported,+ entry.capabilities.isEmpty == false+ else {+ return nil+ }++ let requestedCapabilityID = appFinderMetadataValue(+ "appFinder.selectedCapabilityID",+ fallback: "selectedCapabilityID",+ in: wire+ )+ let capability = requestedCapabilityID.flatMap { capabilityID in+ entry.capabilities.first { $0.id == capabilityID }+ } ?? (entry.capabilities.count == 1 ? entry.capabilities[0] : nil)+ guard let capability else {+ return nil+ }++ let requestedControlProfile = appFinderMetadataValue(+ "appFinder.controlProfile",+ fallback: "controlProfile",+ in: wire+ )+ let controlProfile = requestedControlProfile.flatMap { profile in+ capability.controlProfiles.contains(profile) ? profile : nil+ } ?? capability.controlProfiles.first+ guard let controlProfile else {+ return nil+ }++ return AppFinderSelection(+ entry: entry,+ capability: capability,+ controlProfile: controlProfile+ )+ }++ private static func appFinderEntry(+ from wire: TaskIntentWire,+ in appFinderCatalog: [LocalAppFinderCatalogEntry]+ ) -> LocalAppFinderCatalogEntry? {+ let selectedAppID = appFinderMetadataValue(+ "appFinder.selectedAppID",+ fallback: "selectedAppID",+ in: wire+ )+ let appNameCandidates = [+ wire.targetAppName,+ wire.normalizedEntities["appName"],+ wire.entities["appName"]+ ]+ .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter { !$0.isEmpty }++ if let selectedAppID,+ let entry = appFinderCatalog.first(where: {+ $0.appID == selectedAppID || $0.bundleIdentifier == selectedAppID+ }) {+ return entry+ }++ return appFinderCatalog.first { entry in+ appNameCandidates.contains { candidate in+ LocalAppTaskIntentParser.normalizedPhrase(candidate)+ == LocalAppTaskIntentParser.normalizedPhrase(entry.appName)+ || candidate == entry.appID+ || candidate == entry.bundleIdentifier+ }+ }+ }++ private static func appFinderMetadataValue(+ _ key: String,+ fallback: String,+ in wire: TaskIntentWire+ ) -> String? {+ let value = wire.metadata[key] ?? wire.metadata[fallback]+ let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ return trimmed.isEmpty ? nil : trimmed+ }+private static func slug(_ value: String) -> String {LocalAppTaskIntentParser.normalizedPhrase(value).split(separator: " ")diff --git a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swiftindex 1bf59221..72b332e9 100644--- a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift@@ -25,6 +25,63 @@ public struct LocalAppTarget: Codable, Equatable, Sendable {}}+public enum LocalAppFinderSupportStatus: String, Codable, CaseIterable, Equatable, Sendable {+ case supported+ case candidate+ case unsupported+ case denied+}++public struct LocalAppFinderCapability: Codable, Equatable, Sendable {+ public var id: String+ public var summary: String+ public var controlProfiles: [String]+ public var requiredEntities: [String]++ public init(+ id: String,+ summary: String,+ controlProfiles: [String] = [],+ requiredEntities: [String] = []+ ) {+ self.id = id+ self.summary = summary+ self.controlProfiles = controlProfiles+ self.requiredEntities = requiredEntities+ }+}++public struct LocalAppFinderCatalogEntry: Codable, Equatable, Sendable {+ public var appID: String+ public var appName: String+ public var bundleIdentifier: String?+ public var description: String+ public var supportStatus: LocalAppFinderSupportStatus+ public var capabilities: [LocalAppFinderCapability]+ public var denyReason: String?+ public var metadata: [String: String]++ public init(+ appID: String,+ appName: String,+ bundleIdentifier: String? = nil,+ description: String,+ supportStatus: LocalAppFinderSupportStatus,+ capabilities: [LocalAppFinderCapability] = [],+ denyReason: String? = nil,+ metadata: [String: String] = [:]+ ) {+ self.appID = appID+ self.appName = appName+ self.bundleIdentifier = bundleIdentifier+ self.description = description+ self.supportStatus = supportStatus+ self.capabilities = capabilities+ self.denyReason = denyReason+ self.metadata = metadata+ }+}+public enum LocalAppActionPlanTool: String, Codable, CaseIterable, Equatable, Sendable {case openOrFocusApp = "app.openOrFocus"case observeApp = "app.observe"diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swiftindex 92616031..a96e9373 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift@@ -25,11 +25,22 @@ public protocol LocalAppAvailabilityProviding: Sendable {func availability(for target: LocalAppTarget) -> LocalAppAvailabilityfunc availability(namedApp appName: String) -> LocalAppAvailabilityfunc availability(namedLocalItem itemName: String) -> LocalAppAvailability+ func appFinderCatalogEntries() -> [LocalAppFinderCatalogEntry]+}++public extension LocalAppAvailabilityProviding {+ func appFinderCatalogEntries() -> [LocalAppFinderCatalogEntry] {+ []+ }}public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {public init() {}+ public func appFinderCatalogEntries() -> [LocalAppFinderCatalogEntry] {+ Self.cachedInstalledApplicationCatalogEntries+ }+public func availability(for target: LocalAppTarget) -> LocalAppAvailability {guard let bundleIdentifier = target.bundleIdentifier else {return availability(namedApp: target.appName)@@ -193,6 +204,68 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {.first}+ private static func installedApplicationCatalogEntries() -> [LocalAppFinderCatalogEntry] {+ let urls = spotlightApplicationURLs() + fallbackApplicationURLs()+ var entriesByID: [String: LocalAppFinderCatalogEntry] = [:]+ for url in urls {+ guard LocalItemKind(url: url) == .application else { continue }+ let bundle = Bundle(url: url)+ let appName = displayName(for: url, kind: .application)+ let bundleIdentifier = bundle?.bundleIdentifier+ let entry = LocalAppFinderCatalogBuilder.entry(+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ path: url.path+ )+ entriesByID[entry.appID] = entry+ }++ return entriesByID.values.sorted {+ if $0.appName == $1.appName {+ return $0.appID < $1.appID+ }+ return $0.appName.localizedCaseInsensitiveCompare($1.appName) == .orderedAscending+ }+ }++ private static let cachedInstalledApplicationCatalogEntries = installedApplicationCatalogEntries()++ private static func spotlightApplicationURLs() -> [URL] {+ let 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(300)+ .map { URL(fileURLWithPath: String($0)) }+ }++ private static func fallbackApplicationURLs() -> [URL] {+ var urls: [URL] = []+ for rootURL in applicationSearchRoots() {+ guard let enumerator = FileManager.default.enumerator(+ at: rootURL,+ includingPropertiesForKeys: [.isDirectoryKey],+ options: [.skipsHiddenFiles, .skipsPackageDescendants]+ ) else {+ continue+ }++ for case let itemURL as URL in enumerator {+ guard itemURL.pathExtension == "app" else { continue }+ urls.append(itemURL)+ if urls.count >= 300 { return urls }+ }+ }+ return urls+ }+private static func spotlightItems(named itemName: String,requested normalizedName: String,@@ -334,6 +407,18 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {]}+ private static func applicationSearchRoots() -> [URL] {+ let homeApplications = FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent("Applications", isDirectory: true)+ 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+ ]+ }+private static func runProcess(executableURL: URL,arguments: [String],@@ -382,6 +467,33 @@ public struct StaticLocalAppAvailabilityProvider: LocalAppAvailabilityProvidingself.installedLocalItemNames = installedLocalItemNames}+ public func appFinderCatalogEntries() -> [LocalAppFinderCatalogEntry] {+ var entriesByID: [String: LocalAppFinderCatalogEntry] = [:]+ for (appName, bundleIdentifier) in installedApplicationNames {+ let entry = LocalAppFinderCatalogBuilder.entry(+ appName: appName,+ bundleIdentifier: bundleIdentifier+ )+ entriesByID[entry.appID] = entry+ }+ for bundleIdentifier in installedBundleIdentifiers {+ let appName = installedApplicationNames.first { $0.value == bundleIdentifier }?.key+ ?? LocalAppFinderCatalogBuilder.inferredAppName(from: bundleIdentifier)+ let entry = LocalAppFinderCatalogBuilder.entry(+ appName: appName,+ bundleIdentifier: bundleIdentifier+ )+ entriesByID[entry.appID] = entry+ }++ return entriesByID.values.sorted {+ if $0.appName == $1.appName {+ return $0.appID < $1.appID+ }+ return $0.appName.localizedCaseInsensitiveCompare($1.appName) == .orderedAscending+ }+ }+public func availability(for target: LocalAppTarget) -> LocalAppAvailability {let bundleIdentifier = target.bundleIdentifier ?? ""guard !bundleIdentifier.isEmpty else {@@ -600,6 +712,265 @@ enum LocalAppLookup {}}+private enum LocalAppFinderCatalogBuilder {+ private struct Profile {+ var description: String+ var supportStatus: LocalAppFinderSupportStatus+ var capabilities: [LocalAppFinderCapability]+ var denyReason: String?+ }++ static func entry(+ appName: String,+ bundleIdentifier: String?,+ path: String? = nil+ ) -> LocalAppFinderCatalogEntry {+ let appID = bundleIdentifier?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false+ ? bundleIdentifier!+ : "app:\(LocalAppLookup.normalized(appName))"+ let profile = profile(appName: appName, bundleIdentifier: bundleIdentifier)+ let metadata: [String: String] = ["localItem.kind": LocalItemKind.application.rawValue]++ return LocalAppFinderCatalogEntry(+ appID: appID,+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ description: profile.description,+ supportStatus: profile.supportStatus,+ capabilities: profile.capabilities,+ denyReason: profile.denyReason,+ metadata: metadata+ )+ }++ static func inferredAppName(from bundleIdentifier: String) -> String {+ let normalizedKnownNames = profileNameByBundleID[bundleIdentifier]+ if let normalizedKnownNames {+ return normalizedKnownNames+ }+ return LocalAppLookup.titleCased(bundleIdentifier.split(separator: ".").last.map(String.init) ?? bundleIdentifier)+ }++ private static func profile(+ appName: String,+ bundleIdentifier: String?+ ) -> Profile {+ if let bundleIdentifier,+ let profile = profileByBundleID[bundleIdentifier] {+ return profile+ }+ let normalizedName = LocalAppLookup.normalized(appName)+ if let profile = profileByName[normalizedName] {+ return profile+ }++ return Profile(+ description: "Installed app; no declared executable workflow.",+ supportStatus: .candidate,+ capabilities: []+ )+ }++ private static func capability(+ _ id: String,+ _ summary: String,+ controlProfiles: [String],+ requiredEntities: [String]+ ) -> LocalAppFinderCapability {+ LocalAppFinderCapability(+ id: id,+ summary: summary,+ controlProfiles: controlProfiles,+ requiredEntities: requiredEntities+ )+ }++ private static let playMedia = capability(+ "play_media",+ "Search for and play a song, artist, album, podcast, or playlist.",+ controlProfiles: ["search_then_enter"],+ requiredEntities: ["query"]+ )+ private static let openURL = capability(+ "open_url",+ "Open a requested website or URL.",+ controlProfiles: ["address_bar_submit"],+ requiredEntities: ["query"]+ )+ private static let writeText = capability(+ "write_text",+ "Create a new text document or note and type the requested text.",+ controlProfiles: ["new_document_text"],+ requiredEntities: ["query"]+ )+ private static let createTable = capability(+ "create_table",+ "Create a compact table or spreadsheet from tab-separated text.",+ controlProfiles: ["new_document_text"],+ requiredEntities: ["query"]+ )++ private static let profileNameByBundleID: [String: String] = [+ "com.apple.Music": "Music",+ "com.spotify.client": "Spotify",+ "com.apple.Safari": "Safari",+ "com.google.Chrome": "Google Chrome",+ "company.thebrowser.Browser": "Arc",+ "com.apple.Notes": "Notes",+ "com.apple.TextEdit": "TextEdit",+ "com.apple.iWork.Numbers": "Numbers",+ "com.microsoft.Excel": "Microsoft Excel",+ "com.apple.Terminal": "Terminal",+ "com.googlecode.iterm2": "iTerm",+ "com.apple.keychainaccess": "Keychain Access",+ "com.apple.Passwords": "Passwords",+ "com.apple.systempreferences": "System Settings",+ "com.apple.ActivityMonitor": "Activity Monitor",+ "com.apple.Console": "Console"+ ]++ private static let profileByBundleID: [String: Profile] = [+ "com.apple.Music": Profile(+ description: "Apple Music library and playback app.",+ supportStatus: .supported,+ capabilities: [playMedia]+ ),+ "com.spotify.client": Profile(+ description: "Spotify music and podcast playback app.",+ supportStatus: .supported,+ capabilities: [playMedia]+ ),+ "com.apple.Safari": Profile(+ description: "Apple web browser for opening websites and URLs.",+ supportStatus: .supported,+ capabilities: [openURL]+ ),+ "com.google.Chrome": Profile(+ description: "Google web browser for opening websites and URLs.",+ supportStatus: .supported,+ capabilities: [openURL]+ ),+ "company.thebrowser.Browser": Profile(+ description: "Arc web browser for opening websites and URLs.",+ supportStatus: .supported,+ capabilities: [openURL]+ ),+ "com.apple.Notes": Profile(+ description: "Apple Notes app for creating and editing notes.",+ supportStatus: .supported,+ capabilities: [writeText]+ ),+ "com.apple.TextEdit": Profile(+ description: "Apple text editor for creating plain or rich text documents.",+ supportStatus: .supported,+ capabilities: [writeText]+ ),+ "com.apple.iWork.Numbers": Profile(+ description: "Apple spreadsheet app for creating tables and spreadsheets.",+ supportStatus: .supported,+ capabilities: [createTable]+ ),+ "com.microsoft.Excel": Profile(+ description: "Microsoft spreadsheet app for creating and editing workbooks.",+ supportStatus: .candidate,+ capabilities: [createTable]+ )+ ].merging(deniedProfilesByBundleID) { supported, _ in supported }++ private static let profileByName: [String: Profile] = [+ "music": Profile(+ description: "Apple Music library and playback app.",+ supportStatus: .supported,+ capabilities: [playMedia]+ ),+ "spotify": Profile(+ description: "Spotify music and podcast playback app.",+ supportStatus: .supported,+ capabilities: [playMedia]+ ),+ "safari": Profile(+ description: "Apple web browser for opening websites and URLs.",+ supportStatus: .supported,+ capabilities: [openURL]+ ),+ "google chrome": Profile(+ description: "Google web browser for opening websites and URLs.",+ supportStatus: .supported,+ capabilities: [openURL]+ ),+ "chrome": Profile(+ description: "Google web browser for opening websites and URLs.",+ supportStatus: .supported,+ capabilities: [openURL]+ ),+ "arc": Profile(+ description: "Arc web browser for opening websites and URLs.",+ supportStatus: .supported,+ capabilities: [openURL]+ ),+ "notes": Profile(+ description: "Apple Notes app for creating and editing notes.",+ supportStatus: .supported,+ capabilities: [writeText]+ ),+ "textedit": Profile(+ description: "Apple text editor for creating plain or rich text documents.",+ supportStatus: .supported,+ capabilities: [writeText]+ ),+ "numbers": Profile(+ description: "Apple spreadsheet app for creating tables and spreadsheets.",+ supportStatus: .supported,+ capabilities: [createTable]+ ),+ "microsoft excel": Profile(+ description: "Microsoft spreadsheet app for creating and editing workbooks.",+ supportStatus: .candidate,+ capabilities: [createTable]+ ),+ "excel": Profile(+ description: "Microsoft spreadsheet app for creating and editing workbooks.",+ supportStatus: .candidate,+ capabilities: [createTable]+ )+ ].merging(deniedProfilesByName) { supported, _ in supported }++ private static let deniedProfilesByBundleID: [String: Profile] = [+ "com.apple.Terminal": denied("Terminal is a shell app and is not selected for generic local-app automation."),+ "com.googlecode.iterm2": denied("iTerm is a shell app and is not selected for generic local-app automation."),+ "com.apple.keychainaccess": denied("Keychain Access can expose credentials and is denied for local-app automation."),+ "com.apple.Passwords": denied("Password manager apps are denied for local-app automation."),+ "com.apple.systempreferences": denied("System settings changes require a more specific reviewed capability."),+ "com.apple.ActivityMonitor": denied("Process-management tools are denied for generic local-app automation."),+ "com.apple.Console": denied("System log tools are denied for generic local-app automation.")+ ]++ private static let deniedProfilesByName: [String: Profile] = [+ "terminal": denied("Shell apps are denied for generic local-app automation."),+ "iterm": denied("Shell apps are denied for generic local-app automation."),+ "iterm2": denied("Shell apps are denied for generic local-app automation."),+ "keychain access": denied("Credential tools are denied for local-app automation."),+ "passwords": denied("Password manager apps are denied for local-app automation."),+ "1password": denied("Password manager apps are denied for local-app automation."),+ "bitwarden": denied("Password manager apps are denied for local-app automation."),+ "lastpass": denied("Password manager apps are denied for local-app automation."),+ "dashlane": denied("Password manager apps are denied for local-app automation."),+ "system settings": denied("System settings changes require a more specific reviewed capability."),+ "system preferences": denied("System settings changes require a more specific reviewed capability."),+ "activity monitor": denied("Process-management tools are denied for generic local-app automation."),+ "console": denied("System log tools are denied for generic local-app automation.")+ ]++ private static func denied(_ reason: String) -> Profile {+ Profile(+ description: reason,+ supportStatus: .denied,+ capabilities: [],+ denyReason: reason+ )+ }+}+public enum LocalAppTaskCatalogResolutionStatus: String, Equatable, Sendable {case resolvedcase needsConfirmation@@ -725,6 +1096,10 @@ public struct LocalAppTaskCatalog: Sendable {LocalAppTaskAdapter(definition: definition)}+ public func appFinderCatalogEntries() -> [LocalAppFinderCatalogEntry] {+ availabilityProvider.appFinderCatalogEntries()+ }+private func supports(intent: TaskIntent,definition: LocalAppTaskDefinitiondiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex f6e45a7d..2485c5fc 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -610,6 +610,117 @@ struct AIHarnessAdapterTests {#expect(result.trace.status == .completed)}+ @Test+ func taskIntentDecoderGroundsGenericInteractionInAppFinderCatalog() async throws {+ let appFinderCatalog = StaticLocalAppAvailabilityProvider(+ installedBundleIdentifiers: ["com.apple.Music"]+ ).appFinderCatalogEntries()+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(+ router: AIModelRouter(registry: .defaultHybridPlanner),+ sidecarRunner: FakeSidecarRunner(+ result: LocalJSONSidecarResult(+ status: .completed,+ outputData: try localLLMSidecarOutputData(+ 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","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{"appFinder.selectedAppID":"com.apple.Music","appFinder.selectedCapabilityID":"play_media","appFinder.controlProfile":"search_then_enter"}}+ """,+ metadata: ["local.provider": "donkey-local-llm-sidecar"]+ ),+ latencyMS: 14,+ metadata: ["sidecar.role": "taskIntent"]+ )+ )+ )++ let result = await adapter.parseTaskIntent(+ TaskIntentAdapterRequest(+ command: "play some justin bieber",+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,+ appFinderCatalog: appFinderCatalog,+ sourceTraceID: "trace-app-finder-grounded"+ )+ )++ #expect(result.intent?.taskType == "local_app_interaction")+ #expect(result.intent?.targetApp.appName == "Music")+ #expect(result.intent?.targetApp.bundleIdentifier == "com.apple.Music")+ #expect(result.intent?.metadata["appFinder.validated"] == "true")+ #expect(result.intent?.metadata["appFinder.selectedCapabilityID"] == "play_media")+ #expect(result.trace.status == .completed)+ }++ @Test+ func taskIntentDecoderRejectsGenericInteractionOutsideAppFinderCatalog() async throws {+ let appFinderCatalog = StaticLocalAppAvailabilityProvider(+ installedBundleIdentifiers: ["com.apple.Music"]+ ).appFinderCatalogEntries()+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(+ router: AIModelRouter(registry: .defaultHybridPlanner),+ sidecarRunner: FakeSidecarRunner(+ result: LocalJSONSidecarResult(+ status: .completed,+ outputData: try localLLMSidecarOutputData(+ outputText: """+ {"taskType":"local_app_interaction","targetAppName":"GarageBand","entities":{"appName":"GarageBand","goal":"play media","query":"justin bieber"},"normalizedEntities":{"appName":"GarageBand","goal":"play media","query":"Justin Bieber"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{"appFinder.selectedAppID":"com.apple.garageband10","appFinder.selectedCapabilityID":"play_media","appFinder.controlProfile":"search_then_enter"}}+ """,+ metadata: ["local.provider": "donkey-local-llm-sidecar"]+ ),+ latencyMS: 14,+ metadata: ["sidecar.role": "taskIntent"]+ )+ )+ )++ let result = await adapter.parseTaskIntent(+ TaskIntentAdapterRequest(+ command: "play some justin bieber",+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,+ appFinderCatalog: appFinderCatalog,+ sourceTraceID: "trace-app-finder-reject-outside-catalog"+ )+ )++ #expect(result.intent == nil)+ #expect(result.trace.status == .invalidOutput)+ #expect(result.trace.validationStatus == "invalid")+ }++ @Test+ func taskIntentDecoderRejectsDeniedAppFinderSelection() async throws {+ let appFinderCatalog = StaticLocalAppAvailabilityProvider(+ installedBundleIdentifiers: ["com.apple.Terminal"]+ ).appFinderCatalogEntries()+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(+ router: AIModelRouter(registry: .defaultHybridPlanner),+ sidecarRunner: FakeSidecarRunner(+ result: LocalJSONSidecarResult(+ status: .completed,+ outputData: try localLLMSidecarOutputData(+ outputText: """+ {"taskType":"local_app_interaction","targetAppName":"Terminal","entities":{"appName":"Terminal","goal":"run command","query":"ls"},"normalizedEntities":{"appName":"Terminal","goal":"run command","query":"ls"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusTextEntry","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"editor","focusKey":"","verification":"commandAttempted"},"metadata":{"appFinder.selectedAppID":"com.apple.Terminal","appFinder.selectedCapabilityID":"run_command","appFinder.controlProfile":"text_entry_submit"}}+ """,+ metadata: ["local.provider": "donkey-local-llm-sidecar"]+ ),+ latencyMS: 14,+ metadata: ["sidecar.role": "taskIntent"]+ )+ )+ )++ let result = await adapter.parseTaskIntent(+ TaskIntentAdapterRequest(+ command: "run ls in terminal",+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,+ appFinderCatalog: appFinderCatalog,+ sourceTraceID: "trace-app-finder-reject-denied"+ )+ )++ #expect(result.intent == nil)+ #expect(result.trace.status == .invalidOutput)+ #expect(result.trace.validationStatus == "invalid")+ }+@Testfunc processBackedLocalLLMTaskIntentAdapterTreatsSidecarErrorPayloadAsProviderOutage() async {let adapter = ProcessBackedLocalLLMTaskIntentAdapter(@@ -646,7 +757,9 @@ struct AIHarnessAdapterTests {func localModelTaskIntentResolverPassesContextSnippetsSeparatelyFromCommand() async {let recorder = TaskIntentRequestRecorder()let resolver = LocalModelTaskIntentResolver(- catalog: LocalAppTaskCatalog.defaultLocal(),+ catalog: LocalAppTaskCatalog.defaultLocal(+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Music"])+ ),adapter: RecordingTaskIntentAdapter(recorder: recorder))@@ -665,6 +778,7 @@ struct AIHarnessAdapterTests {"Existing task title: play some justin bieber","Recent thread: assistant could not find a supported action"])+ #expect(request?.appFinderCatalog.first?.appID == "com.apple.Music")}@Testdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swiftindex 076518d6..a6195ef4 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift@@ -348,6 +348,31 @@ struct LocalAppTaskTests {#expect(commands.first?.metadata["plan.tool"] == "ui.focusSearch")}+ @Test+ func staticProviderBuildsAppFinderCatalogWithSupportAndDenyMetadata() throws {+ let provider = StaticLocalAppAvailabilityProvider(+ installedBundleIdentifiers: [+ "com.apple.Music",+ "com.apple.Terminal",+ "com.example.DraftPad"+ ],+ installedApplicationNames: ["DraftPad": "com.example.DraftPad"]+ )+ let entries = provider.appFinderCatalogEntries()+ let music = try #require(entries.first { $0.appID == "com.apple.Music" })+ let terminal = try #require(entries.first { $0.appID == "com.apple.Terminal" })+ let draftPad = try #require(entries.first { $0.appID == "com.example.DraftPad" })++ #expect(music.supportStatus == .supported)+ #expect(music.capabilities.map(\.id) == ["play_media"])+ #expect(music.capabilities.first?.controlProfiles == ["search_then_enter"])+ #expect(terminal.supportStatus == .denied)+ #expect(terminal.capabilities.isEmpty)+ #expect(terminal.denyReason?.contains("shell") == true)+ #expect(draftPad.supportStatus == .candidate)+ #expect(draftPad.capabilities.isEmpty)+ }+@Testfunc catalogResolvesGenericModelPlannedTextEntryCreation() throws {let catalog = LocalAppTaskCatalog(diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 4f6f0e5b..8aeae0bd 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -201,8 +201,9 @@ what can be acted on, and what policies apply.A useful context packet includes the current turn, a bounded summary of recentthread events, relevant assets, active action state, selected app/window facts-when available, task definitions and supported capabilities, permission policy,-safety state, and trace ids. The packet should be shaped for the consumer:+when available, task definitions, app-finder catalog entries, supported+capabilities, permission policy, safety state, and trace ids. The packet should+be shaped for the consumer:conversation response, intent classification, planner hint, review-plancreation, memory retrieval, observation, and recovery do not need the samefields. Query-matched memory for natural-language prompt text should not bediff --git a/docs/guides/decision-system.md b/docs/guides/decision-system.mdindex f8c28358..5b9637d7 100644--- a/docs/guides/decision-system.md+++ b/docs/guides/decision-system.md@@ -23,11 +23,13 @@ For local app work, the model receives:- the current command- supported runtime task definitions+- an app-finder catalog of installed apps with descriptions, support status,+ declared capabilities, and control profiles when available- safety and execution expectations encoded in task metadata-The model returns strict JSON, not free-form instructions. The result is decoded into a `TaskIntent`. If the intent names an existing task definition, the catalog validates that definition. If it names the generic local-app interaction capability, the catalog resolves the requested app from local memory and app lookup, then materializes a transient task definition from the typed `actionPlan`.+The model returns strict JSON, not free-form instructions. The result is decoded into a `TaskIntent`. If the intent names an existing task definition, the catalog validates that definition. If it names the generic local-app interaction capability, the model must ground the selected app in the app-finder catalog when one was supplied. The catalog then resolves the requested app from local memory and app lookup, and materializes a transient task definition from the typed `actionPlan`.-For dynamic local-item and local-app interaction capabilities, the app or item name comes from the typed model output. Catalog and memory matching happen after that typed output exists, so lookup is scoped to structured fields such as `targetAppName`, `entities.appName`, or a resolved target id. That inference is not execution authority; the catalog still resolves and verifies the target before any action runs.+For dynamic local-item capabilities, the app or item name comes from the typed model output. For dynamic local-app interactions, the app name is accepted only when it can be matched to a supplied app-finder catalog entry with `supportStatus=supported` and a selected declared capability. Catalog and memory matching happen after typed output exists, so lookup is scoped to structured fields such as `targetAppName`, `entities.appName`, `metadata.appFinder.selectedAppID`, or a resolved target id. That inference is not execution authority; the catalog still resolves and verifies the target before any action runs.The `TaskIntent` wire format always includes an `actionPlan` object. Non-planned task types must return an empty `actionPlan.tools` array; non-empty action plans are accepted only for task definitions that explicitly opt into model-planned local-app interaction.@@ -45,6 +47,17 @@ For this capability the model must provide:- `actionPlan.inputEntity`, usually `query` when `ui.setText` is present- `actionPlan.controlID`, `actionPlan.focusKey`, and `actionPlan.verification` for the guarded UI strategy+When an app-finder catalog is present, the model must also provide:++- `metadata.appFinder.selectedAppID`+- `metadata.appFinder.selectedCapabilityID`+- `metadata.appFinder.controlProfile`++The selected app id must exist in the catalog, the catalog entry must be+`supported`, and the selected capability/control profile must be declared on+that entry. Catalog entries marked `candidate`, `unsupported`, or `denied` are+not executable targets.+The supported plan tools are intentionally small:```text@@ -67,6 +80,7 @@ The model may choose tools, entities, target app, and confidence. Website navigaThe catalog resolves dynamic targets through the agent memory store, Spotlight/app lookup, and bounded filesystem lookup. A planned action only proceeds when:- model confidence is high enough+- app-finder metadata matches a supported app/capability when a catalog was supplied- the target app or item is available- required entities are present- every planned tool is in the allowlist@@ -95,6 +109,6 @@ Weather, Music, and document form-fill fixtures remain useful for tests and repl- Prompt command handling starts in `apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift`.- Harness routing and context packet assembly live in `apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift`.-- Task-intent parsing protocol and the hosted Responses adapter live in `apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift`.+- Task-intent parsing, app-finder prompt context, and the hosted Responses adapter live in `apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift`.- Catalog validation and generic local-app interaction materialization live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift`.- Guarded execution lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift` and the action-engine backends.diff --git a/scripts/local-runtime-runners/donkey_runtime_runner.py b/scripts/local-runtime-runners/donkey_runtime_runner.pyindex 687b22a4..8e99a27b 100644--- a/scripts/local-runtime-runners/donkey_runtime_runner.py+++ b/scripts/local-runtime-runners/donkey_runtime_runner.py@@ -617,7 +617,12 @@ def local_llm_prompt_and_limit(request: dict[str, Any]) -> tuple[str, int]:), 320task_definitions = request.get("taskDefinitions", [])return json_prompt(- task_intent_prompt(command, task_definitions, request.get("contextSnippets", [])),+ task_intent_prompt(+ command,+ task_definitions,+ request.get("contextSnippets", []),+ request.get("appFinderCatalog", []),+ ),task_intent_schema(task_definitions),), 640@@ -656,7 +661,11 @@ def repair_invalid_task_intent_with_compact_model(command = str(request.get("command") or "")task_definitions = request.get("taskDefinitions", [])- compact_prompt_text = compact_task_intent_prompt(command, task_definitions)+ compact_prompt_text = compact_task_intent_prompt(+ command,+ task_definitions,+ request.get("appFinderCatalog", []),+ )try:response = llm(compact_prompt_text,@@ -692,7 +701,11 @@ def repair_invalid_task_intent_with_compact_model(def compact_task_intent_output(llm: Any, request: dict[str, Any]) -> tuple[str, dict[str, str]]:command = str(request.get("command") or "")task_definitions = request.get("taskDefinitions", [])- compact_prompt_text = compact_task_intent_prompt(command, task_definitions)+ compact_prompt_text = compact_task_intent_prompt(+ command,+ task_definitions,+ request.get("appFinderCatalog", []),+ )try:response = llm(compact_prompt_text,@@ -751,14 +764,24 @@ def task_intent_payload_looks_valid(intent: Any) -> bool:return all(key in action_plan for key in action_required) and isinstance(action_plan.get("tools"), list)-def compact_task_intent_prompt(command: str, task_definitions: list[dict[str, Any]]) -> str:+def compact_task_intent_prompt(+ command: str,+ task_definitions: list[dict[str, Any]],+ app_finder_catalog: list[dict[str, Any]] | None = None,+) -> str:known_apps = ["Music", "Safari", "Notes", "Numbers"]+ catalog_apps = [+ str(entry.get("appName") or "").strip()+ for entry in (app_finder_catalog or [])+ if str(entry.get("supportStatus") or "") == "supported"+ and str(entry.get("appName") or "").strip()+ ]discovered_apps = [str((definition.get("targetApp") or {}).get("appName") or "").strip()for definition in task_definitionsif str((definition.get("targetApp") or {}).get("appName") or "").strip()]- app_names = ordered_unique(known_apps + discovered_apps + ["Local App"])+ app_names = ordered_unique(catalog_apps + known_apps + discovered_apps + ["Local App"])return "\n".join(["<|im_start|>system",@@ -792,6 +815,39 @@ def ordered_unique(values: list[str]) -> list[str]:return result+def compact_app_finder_catalog(entries: list[dict[str, Any]] | None) -> list[dict[str, Any]]:+ compact: list[dict[str, Any]] = []+ for entry in entries or []:+ if not isinstance(entry, dict):+ continue+ item: dict[str, Any] = {+ "appID": str(entry.get("appID") or ""),+ "appName": str(entry.get("appName") or ""),+ "description": str(entry.get("description") or ""),+ "supportStatus": str(entry.get("supportStatus") or ""),+ }+ bundle_identifier = str(entry.get("bundleIdentifier") or "")+ if bundle_identifier:+ item["bundleIdentifier"] = bundle_identifier+ capabilities = entry.get("capabilities")+ if isinstance(capabilities, list) and capabilities:+ item["capabilities"] = [+ {+ "id": str(capability.get("id") or ""),+ "summary": str(capability.get("summary") or ""),+ "controlProfiles": capability.get("controlProfiles") or [],+ "requiredEntities": capability.get("requiredEntities") or [],+ }+ for capability in capabilities+ if isinstance(capability, dict)+ ]+ deny_reason = str(entry.get("denyReason") or "")+ if deny_reason:+ item["denyReason"] = deny_reason+ compact.append(item)+ return compact++def materialize_compact_task_intent(compact_text: str,*,@@ -1283,6 +1339,7 @@ def task_intent_prompt(command: str,task_definitions: list[dict[str, Any]],context_snippets: list[Any] | None = None,+ app_finder_catalog: list[dict[str, Any]] | None = None,) -> str:task_lines: list[str] = []for definition in task_definitions:@@ -1319,6 +1376,10 @@ def task_intent_prompt(]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())+ app_finder_catalog_json = json.dumps(+ compact_app_finder_catalog(app_finder_catalog),+ separators=(",", ":"),+ )return "\n".join([@@ -1353,9 +1414,15 @@ def task_intent_prompt("Table output shape: targetAppName=Numbers, entities.appName=Numbers, entities.goal=create requested table, entities.query=<tab-separated rows for the requested table>, actionPlan.tools=[app.openOrFocus, app.observe, ui.newDocument, ui.setText, app.verifyCommand], inputEntity=query, controlID=editor.",'Example malformed request output shape: {"taskType":"local_app_interaction","targetAppName":"Notes","entities":{"appName":"Notes","goal":"unclear local writing request"},"normalizedEntities":{"appName":"Notes","goal":"unclear local writing request"},"confidence":0.2,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"query","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{"responseMode":"conversation","assistantResponse":"I can help, but I need a clearer thing to write before opening an app."}}',"For every other task type, actionPlan.tools must be empty.",+ "App finder catalog entries are installed local apps with descriptions, support status, capabilities, and control profiles.",+ "When App finder catalog JSON is non-empty and you use local_app_interaction, choose the target app only from a catalog entry with supportStatus=supported and a matching capability.",+ "For local_app_interaction with an app finder choice, set targetAppName and entities.appName to the catalog appName, set metadata.appFinder.selectedAppID to the exact catalog appID, metadata.appFinder.selectedCapabilityID to the chosen capability id, and metadata.appFinder.controlProfile to one control profile from that capability.",+ "Never select catalog entries with supportStatus=candidate, unsupported, or denied for execution; if no supported app capability fits, choose conversation.",f"Command: {command}","Relevant local cache:",context,+ "App finder catalog JSON:",+ app_finder_catalog_json,"Supported task capabilities:","\n".join(task_lines),]