Open source CapCut alternative.
TypeScript
Add dynamic local app catalog refresh
David Le33614c2cab5d
diff --git a/apps/Donkey/Package.swift b/apps/Donkey/Package.swiftindex e87ce4dd..4c5e2f88 100644--- a/apps/Donkey/Package.swift+++ b/apps/Donkey/Package.swift@@ -31,6 +31,9 @@ let package = Package(.target(name: "DonkeyRuntime",dependencies: ["DonkeyContracts"],+ resources: [+ .process("Resources")+ ],linkerSettings: [.linkedLibrary("sqlite3")]diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swiftindex 56d3a4d6..3f740191 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift@@ -28,6 +28,7 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkprivate let voiceTranscriber: LocalVoiceTranscriptionAdapterprivate var updateChecker: any DonkeyUpdateCheckingprivate let documentReviewController: DocumentFormFillReviewWindowController+ private let appCatalogRefreshLoop: LocalAppDynamicCatalogRefreshLoopprivate var activeTaskIDs: Set<String> = []private var lastActiveTaskID: String?private static let notchTaskDisplayLimit = 12@@ -52,6 +53,9 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkself.voiceTranscriber = voiceTranscriberself.updateChecker = updateCheckerself.documentReviewController = documentReviewController+ self.appCatalogRefreshLoop = LocalAppDynamicCatalogRefreshLoop(+ profileGenerator: HostedLocalAppCatalogProfileGenerator()+ )let restoredTasks = Self.restoredTasks(from: taskStore.loadRecentTasks(limit: Self.notchTaskDisplayLimit))notchTasks = restoredTasksnotchAccentIndex = restoredTasks.first.map { PointerPromptAccentPalette.normalizedIndex($0.accentIndex) }@@ -73,6 +77,7 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink}updateChecker.start()SQLiteAgentMemoryStore.shared?.prewarmDefaultLocalItemsInBackground()+ appCatalogRefreshLoop.start()checkForUpdates()}diff --git a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swiftindex 8e464c75..4c9c3939 100644--- a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift+++ b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift@@ -11,6 +11,7 @@ public enum AIModelRole: String, Codable, Equatable, Sendable {case taskIntentcase voiceTranscriptioncase plannerHint+ case localAppCatalogProfilecase traceSummarycase recovery}@@ -127,6 +128,27 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {"lastVerifiedAt": "2026-05-23","docsSource": "Donkey backend inference API"]+ ),+ AIModelRegistryEntry(+ id: "backend-local-app-catalog-profile-default",+ role: .localAppCatalogProfile,+ provider: .donkeyBackend,+ modelID: AIModelRegistryEntry.backendSelectedModelID,+ endpoint: URL(string: "donkey://backend/api/inference/responses")!,+ capabilities: [.textInput, .structuredOutputs],+ timeoutMS: 20_000,+ promptVersion: "local-app-catalog-profile-v1",+ evalStatus: .candidate,+ docsURL: URL(string: "donkey://docs/guides/backend-apis")!,+ rollbackID: nil,+ metadata: [+ "hosted": "true",+ "backendProxy": "true",+ "modelSelection": "backendDefault",+ "privacy.store": "false",+ "lastVerifiedAt": "2026-05-25",+ "docsSource": "Donkey backend inference API"+ ])])@@ -138,6 +160,7 @@ public enum AIModelJobType: String, Codable, Equatable, Sendable {case taskIntentcase voiceTranscriptioncase plannerHint+ case localAppCatalogProfilecase traceSummarycase recovery}@@ -241,6 +264,8 @@ public struct AIModelRouter: Sendable {return .voiceTranscriptioncase .plannerHint:return .plannerHint+ case .localAppCatalogProfile:+ return .localAppCatalogProfilecase .traceSummary:return .traceSummarycase .recovery:diff --git a/apps/Donkey/Sources/DonkeyAI/HostedLocalAppCatalogProfileGenerator.swift b/apps/Donkey/Sources/DonkeyAI/HostedLocalAppCatalogProfileGenerator.swiftnew file mode 100644index 00000000..8e2f9471--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/HostedLocalAppCatalogProfileGenerator.swift@@ -0,0 +1,393 @@+import DonkeyContracts+import DonkeyRuntime+import Foundation++public struct HostedLocalAppCatalogProfileGenerator: LocalAppCatalogProfileGenerating {+ public static let schemaID = "local_app_catalog_profile_v1"++ public var router: AIModelRouter+ public var configuration: DonkeyBackendInferenceConfiguration?+ public var httpClient: any AIHTTPClient+ public var environment: [String: String]++ public init(+ router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),+ configuration: DonkeyBackendInferenceConfiguration? = nil,+ httpClient: any AIHTTPClient = URLSessionAIHTTPClient(),+ environment: [String: String] = ProcessInfo.processInfo.environment+ ) {+ self.router = router+ self.configuration = configuration+ self.httpClient = httpClient+ self.environment = environment+ }++ public func generateProfiles(+ for applications: [LocalApplicationCatalogCandidate],+ existingProfiles: [LocalAppFinderCatalogEntry],+ sourceTraceID: String+ ) async -> LocalAppCatalogProfileGenerationResult {+ guard !applications.isEmpty else {+ return LocalAppCatalogProfileGenerationResult(+ generatedEntries: [],+ attemptedApplicationIDs: [],+ metadata: ["reason": "noNewApplications"]+ )+ }++ let entry: AIModelRegistryEntry+ do {+ entry = try router.route(AIModelRouteRequest(+ jobType: .localAppCatalogProfile,+ privacyMode: .privacySensitive,+ latencyTolerance: .background+ ).limitingProviders([.donkeyBackend]))+ } catch {+ return LocalAppCatalogProfileGenerationResult(+ generatedEntries: [],+ attemptedApplicationIDs: [],+ metadata: [+ "status": "routingFailed",+ "error": String(describing: error)+ ]+ )+ }++ let backend: DonkeyBackendInferenceClient+ do {+ backend = DonkeyBackendInferenceClient(+ configuration: try configuration ?? DonkeyBackendInferenceConfiguration.fromEnvironment(environment),+ httpClient: httpClient+ )+ } catch {+ return LocalAppCatalogProfileGenerationResult(+ generatedEntries: [],+ attemptedApplicationIDs: [],+ metadata: [+ "status": "missingCredentials",+ "credential": DonkeyBackendInferenceConfiguration.baseURLConfigurationDescription,+ "error": String(describing: error)+ ]+ )+ }++ do {+ let response = try await backend.createResponse(responseRequest(+ entry: entry,+ applications: applications,+ existingProfiles: existingProfiles,+ sourceTraceID: sourceTraceID+ ))+ guard let outputText = Self.outputText(from: response),+ let data = outputText.data(using: .utf8)+ else {+ return LocalAppCatalogProfileGenerationResult(+ generatedEntries: [],+ attemptedApplicationIDs: [],+ metadata: ["status": "emptyOutput"]+ )+ }++ let output = try JSONDecoder().decode(ProfileWireOutput.self, from: data)+ let validEntries = output.entries.filter { generatedEntry in+ Self.matchesInputApplication(generatedEntry, applications: applications)+ }+ return LocalAppCatalogProfileGenerationResult(+ generatedEntries: validEntries,+ attemptedApplicationIDs: Set(applications.map(\.catalogID)),+ metadata: [+ "status": "schemaDecoded",+ "provider": "donkeyBackend",+ "privacy.store": "false",+ "profileEntryCount": String(validEntries.count)+ ].merging(output.metadata) { current, _ in current }+ )+ } catch {+ return LocalAppCatalogProfileGenerationResult(+ generatedEntries: [],+ attemptedApplicationIDs: [],+ metadata: Self.errorMetadata(error)+ )+ }+ }++ private func responseRequest(+ entry: AIModelRegistryEntry,+ applications: [LocalApplicationCatalogCandidate],+ existingProfiles: [LocalAppFinderCatalogEntry],+ sourceTraceID: String+ ) throws -> RemoteInferenceResponseCreateRequest {+ RemoteInferenceResponseCreateRequest(+ input: .array([+ .object([+ "role": .string("user"),+ "content": .array([+ .object([+ "type": .string("input_text"),+ "text": .string(promptText(+ applications: applications,+ existingProfiles: existingProfiles+ ))+ ])+ ])+ ])+ ]),+ store: false,+ text: [+ "format": .object([+ "type": .string("json_schema"),+ "name": .string(Self.schemaID),+ "strict": .bool(true),+ "schema": Self.jsonValue(Self.schema())+ ])+ ],+ metadata: [+ "source_trace_id": sourceTraceID,+ "prompt_version": entry.promptVersion+ ],+ parameters: [+ "instructions": .string(Self.instructions),+ "temperature": .number(0)+ ]+ )+ }++ private func promptText(+ applications: [LocalApplicationCatalogCandidate],+ existingProfiles: [LocalAppFinderCatalogEntry]+ ) -> String {+ let appRecords = applications.map { application -> [String: String] in+ [+ "appID": application.catalogID,+ "appName": application.appName,+ "bundleIdentifier": application.bundleIdentifier ?? "",+ "pathHint": application.path ?? ""+ ]+ }+ let existing = existingProfiles.map { entry -> [String: String] in+ [+ "appID": entry.appID,+ "appName": entry.appName,+ "bundleIdentifier": entry.bundleIdentifier ?? "",+ "supportStatus": entry.supportStatus.rawValue+ ]+ }+ let appsJSON = Self.jsonString(appRecords)+ let existingJSON = Self.jsonString(existing)+ return [+ "New installed applications JSON:",+ appsJSON,+ "Existing known profiles JSON:",+ existingJSON+ ].joined(separator: "\n")+ }++ private static let instructions = [+ "Generate local app catalog profiles for Donkey's guarded local-app task-intent boundary.",+ "Return strict JSON only with an entries array and metadata object.",+ "Return one entry for each input application. Preserve the input appID, appName, and bundleIdentifier exactly; use an empty string when bundleIdentifier is absent.",+ "Supported means the app has a safe generic workflow through one of these control profiles only: search_then_enter, address_bar_submit, new_document_text.",+ "Use supported only for low-risk actions such as media search/playback, opening websites in browsers, writing text in editors/notes, or creating simple tables in document/spreadsheet apps.",+ "Use candidate when the app might be automatable but a safe generic workflow is uncertain.",+ "Use unsupported when it is not meaningfully controllable through the allowed profiles.",+ "Use denied for password managers, credential/keychain tools, shells/terminals, system settings, process managers, logs/consoles, security tools, payment/finance tools, or anything where generic automation would be risky.",+ "Do not create scripts, hidden actions, app-specific private commands, personal data, or capabilities outside the allowed control profiles.",+ "Capabilities must be compact and require query when text/search/address input is needed."+ ].joined(separator: " ")++ private static func schema() -> [String: Any] {+ let capability: [String: Any] = [+ "type": "object",+ "additionalProperties": false,+ "required": ["id", "summary", "controlProfiles", "requiredEntities"],+ "properties": [+ "id": ["type": "string"],+ "summary": ["type": "string"],+ "controlProfiles": [+ "type": "array",+ "items": [+ "type": "string",+ "enum": [+ "search_then_enter",+ "address_bar_submit",+ "new_document_text"+ ]+ ]+ ],+ "requiredEntities": [+ "type": "array",+ "items": ["type": "string"]+ ]+ ]+ ]++ let entry: [String: Any] = [+ "type": "object",+ "additionalProperties": false,+ "required": [+ "appID",+ "appName",+ "bundleIdentifier",+ "description",+ "supportStatus",+ "capabilities",+ "denyReason",+ "metadata"+ ],+ "properties": [+ "appID": ["type": "string"],+ "appName": ["type": "string"],+ "bundleIdentifier": ["type": "string"],+ "description": ["type": "string"],+ "supportStatus": [+ "type": "string",+ "enum": LocalAppFinderSupportStatus.allCases.map(\.rawValue)+ ],+ "capabilities": [+ "type": "array",+ "items": capability+ ],+ "denyReason": ["type": "string"],+ "metadata": [+ "type": "object",+ "additionalProperties": ["type": "string"]+ ]+ ]+ ]++ return [+ "type": "object",+ "additionalProperties": false,+ "required": ["entries", "metadata"],+ "properties": [+ "entries": [+ "type": "array",+ "items": entry+ ],+ "metadata": [+ "type": "object",+ "additionalProperties": ["type": "string"]+ ]+ ]+ ]+ }++ private static func matchesInputApplication(+ _ entry: LocalAppFinderCatalogEntry,+ applications: [LocalApplicationCatalogCandidate]+ ) -> Bool {+ let entryID = LocalAppFinderProfileStore.catalogID(+ appName: entry.appName,+ bundleIdentifier: entry.bundleIdentifier+ )+ return applications.contains { application in+ application.catalogID == entry.appID+ || application.catalogID == entryID+ || application.bundleIdentifier == entry.bundleIdentifier+ }+ }++ private static func outputText(from value: RemoteInferenceJSONValue) -> String? {+ if let outputText = value.objectValue?["output_text"]?.stringValue,+ !outputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ return outputText+ }++ guard let output = value.objectValue?["output"]?.arrayValue else {+ return nil+ }+ for item in output {+ guard let content = item.objectValue?["content"]?.arrayValue else { continue }+ for contentItem in content {+ guard contentItem.objectValue?["type"]?.stringValue == "output_text",+ let text = contentItem.objectValue?["text"]?.stringValue,+ !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ else {+ continue+ }+ return text+ }+ }+ return nil+ }++ private static func errorMetadata(_ error: Error) -> [String: String] {+ if case DonkeyBackendInferenceClientError.httpStatus(let status, let message) = error {+ return [+ "status": status == 429 ? "rateLimited" : "httpError",+ "http.status": String(status),+ "http.bodyPreview": preview(message, maxCharacters: 240)+ ]+ }+ return [+ "status": "failed",+ "error": String(describing: error)+ ]+ }++ private static func preview(_ value: String, maxCharacters: Int) -> String {+ let singleLine = value+ .replacingOccurrences(of: "\n", with: "\\n")+ .replacingOccurrences(of: "\r", with: "\\r")+ guard singleLine.count > maxCharacters else { return singleLine }+ return String(singleLine.prefix(maxCharacters))+ }++ private static func jsonString<T: Encodable>(_ value: T) -> String {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ guard let data = try? encoder.encode(value),+ let string = String(data: data, encoding: .utf8)+ else {+ return "[]"+ }+ return string+ }++ private static func jsonValue(_ value: Any) -> RemoteInferenceJSONValue {+ switch value {+ case let string as String:+ return .string(string)+ case let bool as Bool:+ return .bool(bool)+ case let int as Int:+ return .number(Double(int))+ case let double as Double:+ return .number(double)+ case let array as [Any]:+ return .array(array.map(jsonValue))+ case let object as [String: Any]:+ return .object(object.mapValues(jsonValue))+ default:+ return .null+ }+ }+}++private struct ProfileWireOutput: Decodable {+ var entries: [LocalAppFinderCatalogEntry]+ var metadata: [String: String]+}++private extension RemoteInferenceJSONValue {+ var objectValue: [String: RemoteInferenceJSONValue]? {+ if case .object(let value) = self {+ return value+ }+ return nil+ }++ var arrayValue: [RemoteInferenceJSONValue]? {+ if case .array(let value) = self {+ return value+ }+ return nil+ }++ var stringValue: String? {+ if case .string(let value) = self {+ return value+ }+ return nil+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppCatalogProfiles.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppCatalogProfiles.swiftnew file mode 100644index 00000000..68480880--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppCatalogProfiles.swift@@ -0,0 +1,638 @@+import DonkeyContracts+import Foundation++public struct LocalApplicationCatalogCandidate: Codable, Equatable, Sendable {+ public var appName: String+ public var bundleIdentifier: String?+ public var path: String?+ public var metadata: [String: String]++ public init(+ appName: String,+ bundleIdentifier: String? = nil,+ path: String? = nil,+ metadata: [String: String] = [:]+ ) {+ self.appName = appName+ self.bundleIdentifier = bundleIdentifier?.nilIfEmpty+ self.path = path?.nilIfEmpty+ self.metadata = metadata+ }++ public var catalogID: String {+ LocalAppFinderProfileStore.catalogID(+ appName: appName,+ bundleIdentifier: bundleIdentifier+ )+ }+}++public protocol LocalApplicationCatalogScanning: Sendable {+ func installedApplications() -> [LocalApplicationCatalogCandidate]+}++public struct MacInstalledApplicationCatalogScanner: LocalApplicationCatalogScanning {+ public init() {}++ public func installedApplications() -> [LocalApplicationCatalogCandidate] {+ MacLocalAppAvailabilityProvider.installedApplications()+ }+}++public struct LocalAppFinderProfileCatalog: Codable, Equatable, Sendable {+ public var schemaVersion: Int+ public var entries: [LocalAppFinderCatalogEntry]+ public var aliases: [String: String]++ public init(+ schemaVersion: Int = 1,+ entries: [LocalAppFinderCatalogEntry],+ aliases: [String: String] = [:]+ ) {+ self.schemaVersion = schemaVersion+ self.entries = entries+ self.aliases = aliases+ }+}++public struct LocalAppCatalogProfileGenerationResult: Equatable, Sendable {+ public var generatedEntries: [LocalAppFinderCatalogEntry]+ public var attemptedApplicationIDs: Set<String>+ public var metadata: [String: String]++ public init(+ generatedEntries: [LocalAppFinderCatalogEntry],+ attemptedApplicationIDs: Set<String>,+ metadata: [String: String] = [:]+ ) {+ self.generatedEntries = generatedEntries+ self.attemptedApplicationIDs = attemptedApplicationIDs+ self.metadata = metadata+ }+}++public protocol LocalAppCatalogProfileGenerating: Sendable {+ func generateProfiles(+ for applications: [LocalApplicationCatalogCandidate],+ existingProfiles: [LocalAppFinderCatalogEntry],+ sourceTraceID: String+ ) async -> LocalAppCatalogProfileGenerationResult+}++public struct NoOpLocalAppCatalogProfileGenerator: LocalAppCatalogProfileGenerating {+ public init() {}++ public func generateProfiles(+ for applications: [LocalApplicationCatalogCandidate],+ existingProfiles _: [LocalAppFinderCatalogEntry],+ sourceTraceID _: String+ ) async -> LocalAppCatalogProfileGenerationResult {+ LocalAppCatalogProfileGenerationResult(+ generatedEntries: [],+ attemptedApplicationIDs: [],+ metadata: [+ "generator": "noop",+ "skippedApplicationCount": String(applications.count)+ ]+ )+ }+}++public struct LocalAppCatalogRefreshState: Codable, Equatable, Sendable {+ public var lastRefreshAt: Date?+ public var seenApplicationIDs: [String]+ public var metadata: [String: String]++ public init(+ lastRefreshAt: Date? = nil,+ seenApplicationIDs: [String] = [],+ metadata: [String: String] = [:]+ ) {+ self.lastRefreshAt = lastRefreshAt+ self.seenApplicationIDs = seenApplicationIDs+ self.metadata = metadata+ }+}++public struct LocalAppCatalogRefreshResult: Equatable, Sendable {+ public var status: String+ public var installedApplicationCount: Int+ public var newApplicationCount: Int+ public var generatedProfileCount: Int+ public var snapshotEntryCount: Int+ public var metadata: [String: String]++ public init(+ status: String,+ installedApplicationCount: Int,+ newApplicationCount: Int,+ generatedProfileCount: Int,+ snapshotEntryCount: Int,+ metadata: [String: String] = [:]+ ) {+ self.status = status+ self.installedApplicationCount = installedApplicationCount+ self.newApplicationCount = newApplicationCount+ self.generatedProfileCount = generatedProfileCount+ self.snapshotEntryCount = snapshotEntryCount+ self.metadata = metadata+ }+}++public struct LocalAppFinderProfileStore: Sendable {+ public var seedCatalogURL: URL?+ public var generatedCatalogURL: URL+ public var resolvedCatalogURL: URL+ public var refreshStateURL: URL+ public var decoder: JSONDecoder+ public var encoder: JSONEncoder++ public init(+ seedCatalogURL: URL?,+ generatedCatalogURL: URL,+ resolvedCatalogURL: URL,+ refreshStateURL: URL,+ decoder: JSONDecoder = JSONDecoder(),+ encoder: JSONEncoder = LocalAppFinderProfileStore.defaultEncoder()+ ) {+ self.seedCatalogURL = seedCatalogURL+ self.generatedCatalogURL = generatedCatalogURL+ self.resolvedCatalogURL = resolvedCatalogURL+ self.refreshStateURL = refreshStateURL+ self.decoder = decoder+ self.encoder = encoder+ }++ public static var defaultDirectoryURL: URL {+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("Donkey", isDirectory: true)+ .appendingPathComponent("AppCatalog", isDirectory: true)+ }++ public static var defaultStore: LocalAppFinderProfileStore {+ let directory = defaultDirectoryURL+ return LocalAppFinderProfileStore(+ seedCatalogURL: Bundle.module.url(+ forResource: "local-app-finder-profiles",+ withExtension: "json"+ ),+ generatedCatalogURL: directory.appendingPathComponent(+ "local-app-finder-profiles.generated.json",+ isDirectory: false+ ),+ resolvedCatalogURL: directory.appendingPathComponent(+ "local-app-finder-catalog.snapshot.json",+ isDirectory: false+ ),+ refreshStateURL: directory.appendingPathComponent(+ "local-app-catalog-refresh-state.json",+ isDirectory: false+ )+ )+ }++ public static func catalogID(appName: String, bundleIdentifier: String?) -> String {+ if let bundleIdentifier = bundleIdentifier?.trimmingCharacters(in: .whitespacesAndNewlines),+ !bundleIdentifier.isEmpty {+ return bundleIdentifier+ }+ return "app:\(LocalAppLookup.normalized(appName))"+ }++ public func profileEntries() -> [LocalAppFinderCatalogEntry] {+ mergedProfileCatalog().entries+ }++ public func resolvedCatalogEntries() -> [LocalAppFinderCatalogEntry] {+ loadCatalog(from: resolvedCatalogURL).entries+ .map { sanitizedEntry($0) }+ .sorted(by: Self.isOrderedBefore)+ }++ public func knownProfileIDs() -> Set<String> {+ let catalog = mergedProfileCatalog()+ return Set(catalog.entries.flatMap { entry in+ [+ entry.appID,+ entry.bundleIdentifier ?? "",+ Self.catalogID(appName: entry.appName, bundleIdentifier: entry.bundleIdentifier)+ ].filter { !$0.isEmpty }+ }).union(catalog.aliases.values)+ }++ public func profile(+ appName: String,+ bundleIdentifier: String?+ ) -> LocalAppFinderCatalogEntry? {+ let catalog = mergedProfileCatalog()+ let entries = catalog.entries+ if let bundleIdentifier = bundleIdentifier?.trimmingCharacters(in: .whitespacesAndNewlines),+ !bundleIdentifier.isEmpty,+ let entry = entries.first(where: {+ $0.bundleIdentifier == bundleIdentifier || $0.appID == bundleIdentifier+ }) {+ return entry+ }++ let normalizedName = LocalAppLookup.normalized(appName)+ if let aliasTarget = catalog.aliases[normalizedName],+ let entry = Self.entry(matching: aliasTarget, in: entries) {+ return entry+ }++ return entries.first {+ LocalAppLookup.normalized($0.appName) == normalizedName+ }+ }++ public func entry(+ appName: String,+ bundleIdentifier: String?,+ path: String? = nil+ ) -> LocalAppFinderCatalogEntry {+ let candidate = LocalApplicationCatalogCandidate(+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ path: path+ )+ return entry(for: candidate)+ }++ public func entry(for candidate: LocalApplicationCatalogCandidate) -> LocalAppFinderCatalogEntry {+ let baseMetadata = baseMetadata(path: candidate.path)+ let appID = candidate.catalogID+ if let profile = profile(+ appName: candidate.appName,+ bundleIdentifier: candidate.bundleIdentifier+ ) {+ let metadata = profile.metadata.merging(baseMetadata) { current, _ in current }+ return LocalAppFinderCatalogEntry(+ appID: appID,+ appName: candidate.appName,+ bundleIdentifier: candidate.bundleIdentifier,+ description: profile.description,+ supportStatus: profile.supportStatus,+ capabilities: profile.capabilities,+ denyReason: profile.denyReason,+ metadata: metadata+ )+ }++ return LocalAppFinderCatalogEntry(+ appID: appID,+ appName: candidate.appName,+ bundleIdentifier: candidate.bundleIdentifier,+ description: "Installed app; no declared executable workflow.",+ supportStatus: .candidate,+ capabilities: [],+ metadata: baseMetadata+ )+ }++ public func inferredAppName(from bundleIdentifier: String) -> String {+ if let profile = profile(appName: "", bundleIdentifier: bundleIdentifier) {+ return profile.appName+ }+ return LocalAppLookup.titleCased(+ bundleIdentifier.split(separator: ".").last.map(String.init) ?? bundleIdentifier+ )+ }++ public func upsertGeneratedProfiles(_ entries: [LocalAppFinderCatalogEntry]) throws {+ guard !entries.isEmpty else { return }++ let seedCatalog = loadCatalog(from: seedCatalogURL)+ var generatedCatalog = loadCatalog(from: generatedCatalogURL)+ var generatedByID = Dictionary(+ uniqueKeysWithValues: generatedCatalog.entries.map { entry in+ (entry.appID, entry)+ }+ )+ let seedIDs = Set(seedCatalog.entries.flatMap { entry in+ [entry.appID, entry.bundleIdentifier ?? ""]+ })++ for entry in entries {+ let sanitized = sanitizedEntry(entry)+ guard !seedIDs.contains(sanitized.appID),+ !seedIDs.contains(sanitized.bundleIdentifier ?? "")+ else {+ continue+ }+ generatedByID[sanitized.appID] = sanitized+ }++ generatedCatalog.entries = generatedByID.values.sorted(by: Self.isOrderedBefore)+ try writeCatalog(generatedCatalog, to: generatedCatalogURL)+ }++ public func writeResolvedCatalogEntries(_ entries: [LocalAppFinderCatalogEntry]) throws {+ try writeCatalog(+ LocalAppFinderProfileCatalog(+ entries: entries+ .map { sanitizedEntry($0) }+ .sorted(by: Self.isOrderedBefore)+ ),+ to: resolvedCatalogURL+ )+ }++ public func loadRefreshState() -> LocalAppCatalogRefreshState {+ guard let data = try? Data(contentsOf: refreshStateURL),+ let state = try? decoder.decode(LocalAppCatalogRefreshState.self, from: data)+ else {+ return LocalAppCatalogRefreshState()+ }+ return state+ }++ public func writeRefreshState(_ state: LocalAppCatalogRefreshState) throws {+ try write(state, to: refreshStateURL)+ }++ private func mergedProfileCatalog() -> LocalAppFinderProfileCatalog {+ let seedCatalog = normalizedCatalog(loadCatalog(from: seedCatalogURL))+ let generatedCatalog = normalizedCatalog(loadCatalog(from: generatedCatalogURL))+ var entriesByID = Dictionary(+ uniqueKeysWithValues: seedCatalog.entries.map { entry in+ (entry.appID, entry)+ }+ )+ let seedBundleIDs = Set(seedCatalog.entries.compactMap(\.bundleIdentifier))+ for entry in generatedCatalog.entries {+ guard entriesByID[entry.appID] == nil,+ !seedBundleIDs.contains(entry.bundleIdentifier ?? "")+ else {+ continue+ }+ entriesByID[entry.appID] = entry+ }++ return LocalAppFinderProfileCatalog(+ entries: entriesByID.values.sorted(by: Self.isOrderedBefore),+ aliases: seedCatalog.aliases.merging(generatedCatalog.aliases) { seed, _ in seed }+ )+ }++ private func normalizedCatalog(_ catalog: LocalAppFinderProfileCatalog) -> LocalAppFinderProfileCatalog {+ LocalAppFinderProfileCatalog(+ schemaVersion: catalog.schemaVersion,+ entries: catalog.entries.map { sanitizedEntry($0) },+ aliases: catalog.aliases.reduce(into: [:]) { result, pair in+ result[LocalAppLookup.normalized(pair.key)] = pair.value+ }+ )+ }++ private func loadCatalog(from url: URL?) -> LocalAppFinderProfileCatalog {+ guard let url,+ let data = try? Data(contentsOf: url),+ let catalog = try? decoder.decode(LocalAppFinderProfileCatalog.self, from: data)+ else {+ return LocalAppFinderProfileCatalog(entries: [])+ }+ return catalog+ }++ private func writeCatalog(_ catalog: LocalAppFinderProfileCatalog, to url: URL) throws {+ try write(catalog, to: url)+ }++ private func write<T: Encodable>(_ value: T, to url: URL) throws {+ try FileManager.default.createDirectory(+ at: url.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ let data = try encoder.encode(value)+ try data.write(to: url, options: .atomic)+ }++ private func sanitizedEntry(_ entry: LocalAppFinderCatalogEntry) -> LocalAppFinderCatalogEntry {+ let appName = entry.appName.trimmingCharacters(in: .whitespacesAndNewlines)+ let safeAppName = appName.isEmpty ? "Unknown App" : appName+ let bundleIdentifier = entry.bundleIdentifier?.nilIfEmpty+ let appID = Self.catalogID(appName: safeAppName, bundleIdentifier: bundleIdentifier)+ let supportStatus = sanitizedSupportStatus(entry)+ let capabilities = supportStatus == .supported || supportStatus == .candidate+ ? entry.capabilities.compactMap(sanitizedCapability)+ : []++ return LocalAppFinderCatalogEntry(+ appID: appID,+ appName: safeAppName,+ bundleIdentifier: bundleIdentifier,+ description: entry.description.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty+ ?? "Installed app; no declared executable workflow.",+ supportStatus: supportStatus == .supported && capabilities.isEmpty ? .candidate : supportStatus,+ capabilities: capabilities,+ denyReason: entry.denyReason?.nilIfEmpty,+ metadata: entry.metadata+ )+ }++ private func sanitizedSupportStatus(_ entry: LocalAppFinderCatalogEntry) -> LocalAppFinderSupportStatus {+ if entry.supportStatus == .supported,+ entry.capabilities.contains(where: { capability in+ capability.controlProfiles.contains(where: Self.allowedControlProfiles.contains)+ }) {+ return .supported+ }+ if entry.supportStatus == .supported {+ return .candidate+ }+ return entry.supportStatus+ }++ private func sanitizedCapability(_ capability: LocalAppFinderCapability) -> LocalAppFinderCapability? {+ let id = capability.id.trimmingCharacters(in: .whitespacesAndNewlines)+ let summary = capability.summary.trimmingCharacters(in: .whitespacesAndNewlines)+ let profiles = capability.controlProfiles+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter(Self.allowedControlProfiles.contains)+ guard !id.isEmpty, !summary.isEmpty, !profiles.isEmpty else { return nil }+ return LocalAppFinderCapability(+ id: id,+ summary: summary,+ controlProfiles: Array(Set(profiles)).sorted(),+ requiredEntities: capability.requiredEntities+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter { !$0.isEmpty }+ )+ }++ private func baseMetadata(path: String?) -> [String: String] {+ var metadata = ["localItem.kind": LocalItemKind.application.rawValue]+ if let path = path?.nilIfEmpty {+ metadata["localItem.path"] = path+ }+ return metadata+ }++ private static func entry(+ matching id: String,+ in entries: [LocalAppFinderCatalogEntry]+ ) -> LocalAppFinderCatalogEntry? {+ entries.first {+ $0.appID == id || $0.bundleIdentifier == id+ }+ }++ private static func isOrderedBefore(+ lhs: LocalAppFinderCatalogEntry,+ rhs: LocalAppFinderCatalogEntry+ ) -> Bool {+ if lhs.appName == rhs.appName {+ return lhs.appID < rhs.appID+ }+ return lhs.appName.localizedCaseInsensitiveCompare(rhs.appName) == .orderedAscending+ }++ public static func defaultEncoder() -> JSONEncoder {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]+ return encoder+ }++ private static let allowedControlProfiles: Set<String> = [+ "address_bar_submit",+ "new_document_text",+ "search_then_enter"+ ]+}++public final class LocalAppDynamicCatalogRefreshLoop: @unchecked Sendable {+ public var scanner: any LocalApplicationCatalogScanning+ public var profileStore: LocalAppFinderProfileStore+ public var profileGenerator: any LocalAppCatalogProfileGenerating+ public var refreshInterval: TimeInterval+ public var maxNewApplicationsPerRefresh: Int++ private let lock = NSLock()+ private var refreshTask: Task<Void, Never>?++ public init(+ scanner: any LocalApplicationCatalogScanning = MacInstalledApplicationCatalogScanner(),+ profileStore: LocalAppFinderProfileStore = .defaultStore,+ profileGenerator: any LocalAppCatalogProfileGenerating = NoOpLocalAppCatalogProfileGenerator(),+ refreshInterval: TimeInterval = 86_400,+ maxNewApplicationsPerRefresh: Int = 200+ ) {+ self.scanner = scanner+ self.profileStore = profileStore+ self.profileGenerator = profileGenerator+ self.refreshInterval = refreshInterval+ self.maxNewApplicationsPerRefresh = max(1, maxNewApplicationsPerRefresh)+ }++ deinit {+ stop()+ }++ public func start() {+ lock.lock()+ guard refreshTask == nil else {+ lock.unlock()+ return+ }+ refreshTask = Task.detached(priority: .utility) { [self] in+ await run()+ }+ lock.unlock()+ }++ public func stop() {+ lock.lock()+ refreshTask?.cancel()+ refreshTask = nil+ lock.unlock()+ }++ public func refreshIfNeeded(+ now: Date = Date(),+ force: Bool = false+ ) async -> LocalAppCatalogRefreshResult {+ let state = profileStore.loadRefreshState()+ if !force,+ let lastRefreshAt = state.lastRefreshAt,+ now.timeIntervalSince(lastRefreshAt) < refreshInterval {+ let snapshotCount = profileStore.resolvedCatalogEntries().count+ return LocalAppCatalogRefreshResult(+ status: "skipped",+ installedApplicationCount: 0,+ newApplicationCount: 0,+ generatedProfileCount: 0,+ snapshotEntryCount: snapshotCount,+ metadata: ["reason": "refreshIntervalNotElapsed"]+ )+ }++ let installedApplications = scanner.installedApplications()+ let previouslySeenIDs = Set(state.seenApplicationIDs)+ let newApplications = installedApplications+ .filter { application in+ profileStore.profile(+ appName: application.appName,+ bundleIdentifier: application.bundleIdentifier+ ) == nil+ && !previouslySeenIDs.contains(application.catalogID)+ }+ .prefix(maxNewApplicationsPerRefresh)++ let sourceTraceID = "local-app-catalog-refresh-\(UUID().uuidString)"+ let generation = await profileGenerator.generateProfiles(+ for: Array(newApplications),+ existingProfiles: profileStore.profileEntries(),+ sourceTraceID: sourceTraceID+ )+ try? profileStore.upsertGeneratedProfiles(generation.generatedEntries)++ let resolvedEntries = installedApplications.map(profileStore.entry(for:))+ try? profileStore.writeResolvedCatalogEntries(resolvedEntries)++ let profileKnownIDs = Set(installedApplications.compactMap { application -> String? in+ profileStore.profile(+ appName: application.appName,+ bundleIdentifier: application.bundleIdentifier+ ) == nil ? nil : application.catalogID+ })+ let seenIDs = previouslySeenIDs+ .union(profileKnownIDs)+ .union(generation.attemptedApplicationIDs)+ let updatedState = LocalAppCatalogRefreshState(+ lastRefreshAt: now,+ seenApplicationIDs: Array(seenIDs).sorted(),+ metadata: [+ "lastSourceTraceID": sourceTraceID,+ "installedApplicationCount": String(installedApplications.count),+ "newApplicationCount": String(newApplications.count),+ "generatedProfileCount": String(generation.generatedEntries.count)+ ].merging(generation.metadata) { current, _ in current }+ )+ try? profileStore.writeRefreshState(updatedState)++ return LocalAppCatalogRefreshResult(+ status: "refreshed",+ installedApplicationCount: installedApplications.count,+ newApplicationCount: newApplications.count,+ generatedProfileCount: generation.generatedEntries.count,+ snapshotEntryCount: resolvedEntries.count,+ metadata: updatedState.metadata+ )+ }++ private func run() async {+ while !Task.isCancelled {+ _ = await refreshIfNeeded()+ let seconds = max(60, refreshInterval)+ let nanoseconds = UInt64(seconds * 1_000_000_000)+ try? await Task.sleep(nanoseconds: nanoseconds)+ }+ }+}++private extension String {+ var nilIfEmpty: String? {+ let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)+ return trimmed.isEmpty ? nil : trimmed+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swiftindex a96e9373..e97159ad 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift@@ -38,7 +38,11 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {public init() {}public func appFinderCatalogEntries() -> [LocalAppFinderCatalogEntry] {- Self.cachedInstalledApplicationCatalogEntries+ let snapshotEntries = LocalAppFinderProfileStore.defaultStore.resolvedCatalogEntries()+ if !snapshotEntries.isEmpty {+ return snapshotEntries+ }+ return Self.cachedInstalledApplicationCatalogEntries}public func availability(for target: LocalAppTarget) -> LocalAppAvailability {@@ -204,31 +208,50 @@ public struct MacLocalAppAvailabilityProvider: LocalAppAvailabilityProviding {.first}- private static func installedApplicationCatalogEntries() -> [LocalAppFinderCatalogEntry] {+ public static func installedApplications() -> [LocalApplicationCatalogCandidate] {let urls = spotlightApplicationURLs() + fallbackApplicationURLs()- var entriesByID: [String: LocalAppFinderCatalogEntry] = [:]+ var applicationsByID: [String: LocalApplicationCatalogCandidate] = [:]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(+ let candidate = LocalApplicationCatalogCandidate(appName: appName,bundleIdentifier: bundleIdentifier,- path: url.path+ path: url.path,+ metadata: [+ "localItem.kind": LocalItemKind.application.rawValue,+ "localItem.path": url.path+ ])- entriesByID[entry.appID] = entry+ applicationsByID[candidate.catalogID] = candidate}- return entriesByID.values.sorted {+ return applicationsByID.values.sorted {if $0.appName == $1.appName {- return $0.appID < $1.appID+ return $0.catalogID < $1.catalogID}return $0.appName.localizedCaseInsensitiveCompare($1.appName) == .orderedAscending}}- private static let cachedInstalledApplicationCatalogEntries = installedApplicationCatalogEntries()+ private static func installedApplicationCatalogEntries() -> [LocalAppFinderCatalogEntry] {+ cachedInstalledApplications+ .map { LocalAppFinderProfileStore.defaultStore.entry(for: $0) }+ .sorted {+ if $0.appName == $1.appName {+ return $0.appID < $1.appID+ }+ return $0.appName.localizedCaseInsensitiveCompare($1.appName) == .orderedAscending+ }+ }++ private static let cachedInstalledApplications = installedApplications()++ private static var cachedInstalledApplicationCatalogEntries: [LocalAppFinderCatalogEntry] {+ installedApplicationCatalogEntries()+ }private static func spotlightApplicationURLs() -> [URL] {let query = #"kMDItemContentTypeTree == "com.apple.application-bundle""#@@ -609,7 +632,7 @@ public struct StaticLocalAppAvailabilityProvider: LocalAppAvailabilityProviding}private static func inferredAppName(from bundleIdentifier: String) -> String {- LocalAppLookup.titleCased(bundleIdentifier.split(separator: ".").last.map(String.init) ?? bundleIdentifier)+ LocalAppFinderProfileStore.defaultStore.inferredAppName(from: bundleIdentifier)}}@@ -713,261 +736,20 @@ 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,+ LocalAppFinderProfileStore.defaultStore.entry(appName: appName,bundleIdentifier: bundleIdentifier,- description: profile.description,- supportStatus: profile.supportStatus,- capabilities: profile.capabilities,- denyReason: profile.denyReason,- metadata: metadata+ path: path)}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- )+ LocalAppFinderProfileStore.defaultStore.inferredAppName(from: bundleIdentifier)}}diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/local-app-finder-profiles.json b/apps/Donkey/Sources/DonkeyRuntime/Resources/local-app-finder-profiles.jsonnew file mode 100644index 00000000..75c8d0ad--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/local-app-finder-profiles.json@@ -0,0 +1,302 @@+{+ "schemaVersion": 1,+ "entries": [+ {+ "appID": "com.apple.Music",+ "appName": "Music",+ "bundleIdentifier": "com.apple.Music",+ "description": "Apple Music library and playback app.",+ "supportStatus": "supported",+ "capabilities": [+ {+ "id": "play_media",+ "summary": "Search for and play a song, artist, album, podcast, or playlist.",+ "controlProfiles": [+ "search_then_enter"+ ],+ "requiredEntities": [+ "query"+ ]+ }+ ],+ "metadata": {}+ },+ {+ "appID": "com.spotify.client",+ "appName": "Spotify",+ "bundleIdentifier": "com.spotify.client",+ "description": "Spotify music and podcast playback app.",+ "supportStatus": "supported",+ "capabilities": [+ {+ "id": "play_media",+ "summary": "Search for and play a song, artist, album, podcast, or playlist.",+ "controlProfiles": [+ "search_then_enter"+ ],+ "requiredEntities": [+ "query"+ ]+ }+ ],+ "metadata": {}+ },+ {+ "appID": "com.apple.Safari",+ "appName": "Safari",+ "bundleIdentifier": "com.apple.Safari",+ "description": "Apple web browser for opening websites and URLs.",+ "supportStatus": "supported",+ "capabilities": [+ {+ "id": "open_url",+ "summary": "Open a requested website or URL.",+ "controlProfiles": [+ "address_bar_submit"+ ],+ "requiredEntities": [+ "query"+ ]+ }+ ],+ "metadata": {}+ },+ {+ "appID": "com.google.Chrome",+ "appName": "Google Chrome",+ "bundleIdentifier": "com.google.Chrome",+ "description": "Google web browser for opening websites and URLs.",+ "supportStatus": "supported",+ "capabilities": [+ {+ "id": "open_url",+ "summary": "Open a requested website or URL.",+ "controlProfiles": [+ "address_bar_submit"+ ],+ "requiredEntities": [+ "query"+ ]+ }+ ],+ "metadata": {}+ },+ {+ "appID": "company.thebrowser.Browser",+ "appName": "Arc",+ "bundleIdentifier": "company.thebrowser.Browser",+ "description": "Arc web browser for opening websites and URLs.",+ "supportStatus": "supported",+ "capabilities": [+ {+ "id": "open_url",+ "summary": "Open a requested website or URL.",+ "controlProfiles": [+ "address_bar_submit"+ ],+ "requiredEntities": [+ "query"+ ]+ }+ ],+ "metadata": {}+ },+ {+ "appID": "com.apple.Notes",+ "appName": "Notes",+ "bundleIdentifier": "com.apple.Notes",+ "description": "Apple Notes app for creating and editing notes.",+ "supportStatus": "supported",+ "capabilities": [+ {+ "id": "write_text",+ "summary": "Create a new text document or note and type the requested text.",+ "controlProfiles": [+ "new_document_text"+ ],+ "requiredEntities": [+ "query"+ ]+ }+ ],+ "metadata": {}+ },+ {+ "appID": "com.apple.TextEdit",+ "appName": "TextEdit",+ "bundleIdentifier": "com.apple.TextEdit",+ "description": "Apple text editor for creating plain or rich text documents.",+ "supportStatus": "supported",+ "capabilities": [+ {+ "id": "write_text",+ "summary": "Create a new text document or note and type the requested text.",+ "controlProfiles": [+ "new_document_text"+ ],+ "requiredEntities": [+ "query"+ ]+ }+ ],+ "metadata": {}+ },+ {+ "appID": "com.apple.iWork.Numbers",+ "appName": "Numbers",+ "bundleIdentifier": "com.apple.iWork.Numbers",+ "description": "Apple spreadsheet app for creating tables and spreadsheets.",+ "supportStatus": "supported",+ "capabilities": [+ {+ "id": "create_table",+ "summary": "Create a compact table or spreadsheet from tab-separated text.",+ "controlProfiles": [+ "new_document_text"+ ],+ "requiredEntities": [+ "query"+ ]+ }+ ],+ "metadata": {}+ },+ {+ "appID": "com.microsoft.Excel",+ "appName": "Microsoft Excel",+ "bundleIdentifier": "com.microsoft.Excel",+ "description": "Microsoft spreadsheet app for creating and editing workbooks.",+ "supportStatus": "candidate",+ "capabilities": [+ {+ "id": "create_table",+ "summary": "Create a compact table or spreadsheet from tab-separated text.",+ "controlProfiles": [+ "new_document_text"+ ],+ "requiredEntities": [+ "query"+ ]+ }+ ],+ "metadata": {}+ },+ {+ "appID": "com.apple.Terminal",+ "appName": "Terminal",+ "bundleIdentifier": "com.apple.Terminal",+ "description": "Terminal is a shell app and is not selected for generic local-app automation.",+ "supportStatus": "denied",+ "capabilities": [],+ "denyReason": "Terminal is a shell app and is not selected for generic local-app automation.",+ "metadata": {}+ },+ {+ "appID": "com.googlecode.iterm2",+ "appName": "iTerm",+ "bundleIdentifier": "com.googlecode.iterm2",+ "description": "iTerm is a shell app and is not selected for generic local-app automation.",+ "supportStatus": "denied",+ "capabilities": [],+ "denyReason": "iTerm is a shell app and is not selected for generic local-app automation.",+ "metadata": {}+ },+ {+ "appID": "com.apple.keychainaccess",+ "appName": "Keychain Access",+ "bundleIdentifier": "com.apple.keychainaccess",+ "description": "Keychain Access can expose credentials and is denied for local-app automation.",+ "supportStatus": "denied",+ "capabilities": [],+ "denyReason": "Keychain Access can expose credentials and is denied for local-app automation.",+ "metadata": {}+ },+ {+ "appID": "com.apple.Passwords",+ "appName": "Passwords",+ "bundleIdentifier": "com.apple.Passwords",+ "description": "Password manager apps are denied for local-app automation.",+ "supportStatus": "denied",+ "capabilities": [],+ "denyReason": "Password manager apps are denied for local-app automation.",+ "metadata": {}+ },+ {+ "appID": "com.apple.systempreferences",+ "appName": "System Settings",+ "bundleIdentifier": "com.apple.systempreferences",+ "description": "System settings changes require a more specific reviewed capability.",+ "supportStatus": "denied",+ "capabilities": [],+ "denyReason": "System settings changes require a more specific reviewed capability.",+ "metadata": {}+ },+ {+ "appID": "com.apple.ActivityMonitor",+ "appName": "Activity Monitor",+ "bundleIdentifier": "com.apple.ActivityMonitor",+ "description": "Process-management tools are denied for generic local-app automation.",+ "supportStatus": "denied",+ "capabilities": [],+ "denyReason": "Process-management tools are denied for generic local-app automation.",+ "metadata": {}+ },+ {+ "appID": "com.apple.Console",+ "appName": "Console",+ "bundleIdentifier": "com.apple.Console",+ "description": "System log tools are denied for generic local-app automation.",+ "supportStatus": "denied",+ "capabilities": [],+ "denyReason": "System log tools are denied for generic local-app automation.",+ "metadata": {}+ },+ {+ "appID": "app:1password",+ "appName": "1Password",+ "description": "Password manager apps are denied for local-app automation.",+ "supportStatus": "denied",+ "capabilities": [],+ "denyReason": "Password manager apps are denied for local-app automation.",+ "metadata": {}+ },+ {+ "appID": "app:bitwarden",+ "appName": "Bitwarden",+ "description": "Password manager apps are denied for local-app automation.",+ "supportStatus": "denied",+ "capabilities": [],+ "denyReason": "Password manager apps are denied for local-app automation.",+ "metadata": {}+ },+ {+ "appID": "app:lastpass",+ "appName": "LastPass",+ "description": "Password manager apps are denied for local-app automation.",+ "supportStatus": "denied",+ "capabilities": [],+ "denyReason": "Password manager apps are denied for local-app automation.",+ "metadata": {}+ },+ {+ "appID": "app:dashlane",+ "appName": "Dashlane",+ "description": "Password manager apps are denied for local-app automation.",+ "supportStatus": "denied",+ "capabilities": [],+ "denyReason": "Password manager apps are denied for local-app automation.",+ "metadata": {}+ }+ ],+ "aliases": {+ "chrome": "com.google.Chrome",+ "excel": "com.microsoft.Excel",+ "iterm": "com.googlecode.iterm2",+ "iterm2": "com.googlecode.iterm2",+ "system preferences": "com.apple.systempreferences",+ "1password": "app:1password",+ "bitwarden": "app:bitwarden",+ "lastpass": "app:lastpass",+ "dashlane": "app:dashlane"+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swiftindex a9bd059e..3503d5b5 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift@@ -595,6 +595,126 @@ struct LocalAppTaskTests {#expect(catalog.taskDefinitions.contains { $0.targetApp.appName == "Preview" } == false)}+ @Test+ func appFinderProfilesLoadFromBundledJSON() throws {+ let store = LocalAppFinderProfileStore.defaultStore++ let music = try #require(store.profile(appName: "Music", bundleIdentifier: "com.apple.Music"))+ #expect(music.supportStatus == .supported)+ #expect(music.capabilities.map(\.id).contains("play_media"))++ let chrome = try #require(store.profile(appName: "Chrome", bundleIdentifier: nil))+ #expect(chrome.bundleIdentifier == "com.google.Chrome")+ #expect(chrome.capabilities.map(\.id).contains("open_url"))++ let terminal = try #require(store.profile(appName: "Terminal", bundleIdentifier: "com.apple.Terminal"))+ #expect(terminal.supportStatus == .denied)+ #expect(terminal.capabilities.isEmpty)+ }++ @Test+ func dynamicCatalogRefreshProfilesOnlyNewApplicationsOncePerDay() async throws {+ let rootURL = FileManager.default.temporaryDirectory+ .appendingPathComponent("DonkeyAppCatalog-\(UUID().uuidString)", isDirectory: true)+ defer { try? FileManager.default.removeItem(at: rootURL) }+ try FileManager.default.createDirectory(at: rootURL, withIntermediateDirectories: true)++ let seedURL = rootURL.appendingPathComponent("seed.json")+ let seedEntry = LocalAppFinderCatalogEntry(+ appID: "com.apple.Notes",+ appName: "Notes",+ bundleIdentifier: "com.apple.Notes",+ description: "Seeded Notes profile.",+ supportStatus: .supported,+ capabilities: [+ LocalAppFinderCapability(+ id: "write_text",+ summary: "Write text.",+ controlProfiles: ["new_document_text"],+ requiredEntities: ["query"]+ )+ ]+ )+ try JSONEncoder().encode(LocalAppFinderProfileCatalog(entries: [seedEntry])).write(to: seedURL)++ let profileStore = LocalAppFinderProfileStore(+ seedCatalogURL: seedURL,+ generatedCatalogURL: rootURL.appendingPathComponent("generated.json"),+ resolvedCatalogURL: rootURL.appendingPathComponent("snapshot.json"),+ refreshStateURL: rootURL.appendingPathComponent("state.json")+ )+ let scanner = RecordingApplicationCatalogScanner(applications: [+ LocalApplicationCatalogCandidate(+ appName: "Notes",+ bundleIdentifier: "com.apple.Notes",+ path: "/Applications/Notes.app"+ ),+ LocalApplicationCatalogCandidate(+ appName: "Figma",+ bundleIdentifier: "com.figma.Desktop",+ path: "/Applications/Figma.app"+ )+ ])+ let generator = RecordingCatalogProfileGenerator()+ let refreshLoop = LocalAppDynamicCatalogRefreshLoop(+ scanner: scanner,+ profileStore: profileStore,+ profileGenerator: generator,+ refreshInterval: 86_400+ )+ let now = Date(timeIntervalSince1970: 1_000)++ let firstRefresh = await refreshLoop.refreshIfNeeded(now: now)++ #expect(firstRefresh.status == "refreshed")+ #expect(firstRefresh.newApplicationCount == 1)+ #expect(firstRefresh.generatedProfileCount == 1)+ #expect(await generator.requestedBatches() == [["com.figma.Desktop"]])+ let figmaProfile = try #require(profileStore.profile(+ appName: "Figma",+ bundleIdentifier: "com.figma.Desktop"+ ))+ #expect(figmaProfile.supportStatus == .supported)+ #expect(profileStore.resolvedCatalogEntries().contains {+ $0.appID == "com.figma.Desktop" && $0.supportStatus == .supported+ })++ let skippedRefresh = await refreshLoop.refreshIfNeeded(+ now: now.addingTimeInterval(3_600)+ )+ #expect(skippedRefresh.status == "skipped")+ #expect(await generator.requestedBatches() == [["com.figma.Desktop"]])++ scanner.setApplications([+ LocalApplicationCatalogCandidate(+ appName: "Notes",+ bundleIdentifier: "com.apple.Notes",+ path: "/Applications/Notes.app"+ ),+ LocalApplicationCatalogCandidate(+ appName: "Figma",+ bundleIdentifier: "com.figma.Desktop",+ path: "/Applications/Figma.app"+ ),+ LocalApplicationCatalogCandidate(+ appName: "Linear",+ bundleIdentifier: "com.linear",+ path: "/Applications/Linear.app"+ )+ ])++ let nextDayRefresh = await refreshLoop.refreshIfNeeded(+ now: now.addingTimeInterval(90_000)+ )++ #expect(nextDayRefresh.status == "refreshed")+ #expect(nextDayRefresh.newApplicationCount == 1)+ #expect(await generator.requestedBatches() == [+ ["com.figma.Desktop"],+ ["com.linear"]+ ])+ }+@Testfunc documentFormFillPlannerMapsStructuredDataToObservedFieldsForReview() throws {let intent = documentFormFillIntent()@@ -1308,6 +1428,68 @@ struct LocalAppTaskTests {}}+private final class RecordingApplicationCatalogScanner: LocalApplicationCatalogScanning, @unchecked Sendable {+ private let lock = NSLock()+ private var applications: [LocalApplicationCatalogCandidate]++ init(applications: [LocalApplicationCatalogCandidate]) {+ self.applications = applications+ }++ func installedApplications() -> [LocalApplicationCatalogCandidate] {+ lock.lock()+ defer { lock.unlock() }+ return applications+ }++ func setApplications(_ applications: [LocalApplicationCatalogCandidate]) {+ lock.lock()+ self.applications = applications+ lock.unlock()+ }+}++private actor RecordingCatalogProfileGenerator: LocalAppCatalogProfileGenerating {+ private var batches: [[String]] = []++ func generateProfiles(+ for applications: [LocalApplicationCatalogCandidate],+ existingProfiles _: [LocalAppFinderCatalogEntry],+ sourceTraceID _: String+ ) async -> LocalAppCatalogProfileGenerationResult {+ let ids = applications.map(\.catalogID).sorted()+ batches.append(ids)++ let entries = applications.map { application in+ LocalAppFinderCatalogEntry(+ appID: application.catalogID,+ appName: application.appName,+ bundleIdentifier: application.bundleIdentifier,+ description: "Generated profile for \(application.appName).",+ supportStatus: .supported,+ capabilities: [+ LocalAppFinderCapability(+ id: "write_text",+ summary: "Write text in \(application.appName).",+ controlProfiles: ["new_document_text"],+ requiredEntities: ["query"]+ )+ ],+ metadata: ["generated": "test"]+ )+ }+ return LocalAppCatalogProfileGenerationResult(+ generatedEntries: entries,+ attemptedApplicationIDs: Set(ids),+ metadata: ["generator": "recording-test"]+ )+ }++ func requestedBatches() -> [[String]] {+ batches+ }+}+@MainActorprivate final class FakeLocalAppTaskAppController: LocalAppTaskAppControlling {private let launchObservation: LocalAppTaskObservationdiff --git a/docs/guides/decision-system.md b/docs/guides/decision-system.mdindex a833d6d9..c938709b 100644--- a/docs/guides/decision-system.md+++ b/docs/guides/decision-system.md@@ -108,10 +108,13 @@ Successful or reviewed plans can be stored as runtime task definitions in agentWeather, Music, and document form-fill fixtures remain useful for tests and replay. The supported runtime path is generic: local app/item lookup, model-selected intent or plan, catalog validation, guarded execution, verification, and optional memory-backed learning.+The local app finder catalog is seeded from bundled JSON and refreshed in the background from the user's installed applications. Donkey persists a daily app-catalog snapshot under Application Support, compares it with the previously seen application ids, and sends only newly discovered apps through the typed catalog-profile model route. Generated profiles are persisted as JSON, sanitized to the allowed generic control profiles, and merged with the shipped seed; bundled deny/support entries remain authoritative.+## Source Entry Points- 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, 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`.+- App-finder profile JSON loading and background refresh live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppCatalogProfiles.swift`; hosted profile generation lives in `apps/Donkey/Sources/DonkeyAI/HostedLocalAppCatalogProfileGenerator.swift`.- Guarded execution lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift` and the action-engine backends.