Skip to content

Open source CapCut alternative.

TypeScript

refactor(app): remove dead upfront-planning scaffolding

David Le1dbc9d8dc020
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 812b8978..a17f9fa0 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -581,7 +581,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
|| allowedSensitiveTools.contains(descriptor.name)
}
.map(\.name)
- + LocalAppHarnessStepExecutor.descriptors.map(\.name)
)).sorted()
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift
index 17fc0e0d..06d2c31b 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift
@@ -2,11 +2,6 @@ import DonkeyContracts
import DonkeyHarness
import Foundation
-public enum AppHarnessGenericLifecycleToolNames {
- public static let agentPathVisualize = "agent.path.visualize"
- public static let localAppTools: [String] = (LocalAppActionPlanTool.allCases.map(\.rawValue) + [agentPathVisualize]).sorted()
-}
-
public struct AppHarnessGenericLifecyclePreparedTurn: Equatable, Sendable {
public var thread: HarnessThread
public var task: HarnessTaskState
@@ -132,98 +127,6 @@ public struct AppHarnessGenericLifecycle: Sendable {
)
}
- @discardableResult
- public func planLocalTaskRun(
- taskID: String,
- resolution: LocalAppTaskCatalogResolution,
- fallbackGoal: String,
- traceID: String,
- availableToolNames: [String] = AppHarnessGenericLifecycleToolNames.localAppTools
- ) async -> HarnessTaskState? {
- let intent = Self.intentAnalysis(
- for: resolution,
- fallbackGoal: fallbackGoal
- )
- _ = await coordinator.updateIntent(taskID: taskID, intent: intent)
- let plannedStepMetadata = resolution.intent?.metadata ?? [:]
- let modelPlanSteps = Self.modelPlanningSteps(
- from: plannedStepMetadata,
- traceID: traceID,
- availableToolNames: availableToolNames,
- normalizedEntities: resolution.intent?.normalizedEntities ?? [:],
- entities: resolution.intent?.entities ?? [:]
- )
- let plan = HarnessPlan(
- goal: intent.goal,
- steps: modelPlanSteps,
- successCriteria: Self.stringArrayMetadata(
- plannedStepMetadata["genericHarness.verificationCriteriaJSON"],
- fallback: ["Resolved local app result is completed or handed to a user gate."]
- ),
- fallbackPolicy: Self.stringArrayMetadata(
- plannedStepMetadata["genericHarness.fallbacksJSON"],
- fallback: ["If execution needs review or missing detail, stop at the user gate."]
- ),
- clarificationPolicy: Self.clarificationPolicy(from: plannedStepMetadata),
- confidence: intent.confidence,
- metadata: [
- "planner": "genericHarnessLocalAppPlan",
- "traceID": traceID,
- "resolution.status": resolution.status.rawValue,
- "modelPlan.stepCount": String(modelPlanSteps.count),
- "modelPlan.schemaVersion": plannedStepMetadata["genericHarness.schemaVersion"] ?? ""
- ]
- )
- _ = await coordinator.updatePlan(taskID: taskID, plan: plan)
- return await coordinator.startRunning(
- taskID: taskID,
- reason: "User query task planned through generic harness"
- )
- }
-
- @discardableResult
- public func planRecovery(
- taskID: String,
- reason: String,
- traceID: String
- ) async -> HarnessTaskState? {
- guard let task = await coordinator.task(id: taskID) else { return nil }
-
- let plan = HarnessPlan(
- goal: task.goal,
- steps: [
- HarnessPlanStep(
- id: "recover-local-app-task",
- summary: "Recover from an unsuccessful user-query local app task.",
- toolCall: HarnessToolCall(
- id: "local-app-recover-\(traceID)",
- name: "run.recover",
- input: ["reason": reason],
- metadata: [
- "adapter": "userQuery",
- "traceID": traceID
- ]
- ),
- expectedObservation: "Recovery records a safe fallback or updated task evidence."
- )
- ],
- successCriteria: ["Recovery stops safely or prepares a future continuation."],
- fallbackPolicy: ["If recovery cannot proceed, leave the task failed safe."],
- clarificationPolicy: ["Ask only if a specific missing user detail would let the task continue."],
- confidence: task.intent?.confidence ?? 0,
- metadata: [
- "planner": "genericHarnessUserQueryRecovery",
- "traceID": traceID,
- "recovery.reason": reason
- ]
- )
- _ = await coordinator.updatePlan(taskID: taskID, plan: plan)
- return await coordinator.startRunning(
- taskID: taskID,
- reason: "User query recovery planned through generic harness"
- )
- }
-
public func taskState(taskID: String) async -> HarnessTaskState? {
await coordinator.task(id: taskID)
}
@@ -380,168 +283,6 @@ public struct AppHarnessGenericLifecycle: Sendable {
)
}
- private static func intentAnalysis(
- for resolution: LocalAppTaskCatalogResolution,
- fallbackGoal: String
- ) -> HarnessIntentAnalysis {
- let taskType = resolution.intent?.taskType ?? resolution.definition?.taskType
- let targetApp = resolution.intent?.targetApp.appName
- ?? resolution.definition?.targetApp.appName
- ?? resolution.availability?.target.appName
- let goalParts = [
- taskType,
- targetApp.map { "in \($0)" }
- ].compactMap { $0 }
- let goal = goalParts.isEmpty ? fallbackGoal : goalParts.joined(separator: " ")
- let metadata = resolution.intent?.metadata ?? [:]
- let modelGoal = metadata["genericHarness.intent.goal"]
- .flatMap { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : $0 }
- let missingInformation: [String]
- if resolution.status == .needsConfirmation {
- missingInformation = Self.stringArrayMetadata(
- metadata["genericHarness.missingInformationJSON"],
- fallback: [resolution.metadata["reason"] ?? "more detail"]
- )
- } else {
- missingInformation = Self.stringArrayMetadata(
- metadata["genericHarness.missingInformationJSON"],
- fallback: []
- )
- }
- return HarnessIntentAnalysis(
- goal: modelGoal ?? goal,
- entities: resolution.intent?.normalizedEntities ?? resolution.intent?.entities ?? [:],
- ambiguityClass: HarnessAmbiguityClass(
- rawValue: metadata["genericHarness.ambiguity.class"] ?? ""
- ) ?? (resolution.status == .needsConfirmation ? .recoverable : .safe),
- riskLevel: HarnessRiskLevel(
- rawValue: metadata["genericHarness.risk.level"] ?? ""
- ) ?? .medium,
- missingInformation: missingInformation,
- shouldAskBeforeActing: metadata["genericHarness.shouldAskBeforeActing"] == "true"
- || resolution.status == .needsConfirmation,
- confidence: resolution.intent?.confidence ?? 0,
- metadata: [
- "resolution.status": resolution.status.rawValue,
- "taskType": taskType ?? "",
- "targetApp": targetApp ?? "",
- "intentID": resolution.intent?.intentID ?? ""
- ].merging(resolution.metadata) { current, _ in current }
- )
- }
-
- private static func modelPlanningSteps(
- from metadata: [String: String],
- traceID: String,
- availableToolNames: [String],
- normalizedEntities: [String: String],
- entities: [String: String]
- ) -> [HarnessPlanStep] {
- guard let text = metadata["genericHarness.planStepsJSON"],
- let data = text.data(using: .utf8),
- let values = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]]
- else {
- return []
- }
- let allowedToolNames = Set(availableToolNames)
-
- return values.enumerated().map { index, value in
- let id = nonEmpty(stringValue(value["id"])) ?? "model-plan-step-\(index + 1)"
- let toolName = nonEmpty(stringValue(value["toolName"]))
- let toolCall = toolName.flatMap { toolName -> HarnessToolCall? in
- guard allowedToolNames.contains(toolName) else { return nil }
- let input = toolInput(
- from: value,
- normalizedEntities: normalizedEntities,
- entities: entities
- )
- return HarnessToolCall(
- id: "local-app-step-\(traceID)-\(index + 1)",
- name: toolName,
- input: input.merging([
- "inputEntity": stringValue(value["inputEntity"]) ?? "",
- "controlID": stringValue(value["controlID"]) ?? "",
- "focusKey": stringValue(value["focusKey"]) ?? "",
- "expectedObservation": stringValue(value["expectedObservation"]) ?? "",
- "modelStepID": id,
- "modelStepIndex": String(index)
- ]) { current, _ in current },
- metadata: [
- "adapter": "userQuery",
- "traceID": traceID,
- "source": "hostedGenericHarnessPlanning"
- ]
- )
- }
- return HarnessPlanStep(
- id: "model-\(id)",
- summary: nonEmpty(stringValue(value["summary"])) ?? "Model-planned harness step",
- toolCall: toolCall,
- expectedObservation: nonEmpty(stringValue(value["expectedObservation"])),
- metadata: [
- "source": "hostedGenericHarnessPlanning",
- "toolName": toolName ?? "",
- "inputEntity": stringValue(value["inputEntity"]) ?? "",
- "controlID": stringValue(value["controlID"]) ?? "",
- "focusKey": stringValue(value["focusKey"]) ?? ""
- ]
- )
- }
- }
-
- private static func toolInput(
- from value: [String: Any],
- normalizedEntities: [String: String],
- entities: [String: String]
- ) -> [String: String] {
- var input = value["toolInputs"] as? [String: String] ?? [:]
- let inputEntity = nonEmpty(input["inputEntity"] ?? stringValue(value["inputEntity"]))
- if let inputEntity {
- input["inputEntity"] = inputEntity
- }
- if input["input"]?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty != false,
- let inputEntity,
- let entityValue = normalizedEntities[inputEntity] ?? entities[inputEntity] {
- input["input"] = entityValue
- }
- return input
- }
-
- private static func clarificationPolicy(from metadata: [String: String]) -> [String] {
- var policy = stringArrayMetadata(
- metadata["genericHarness.clarification.questionsJSON"],
- fallback: []
- )
- if let text = nonEmpty(metadata["genericHarness.clarification.policy"]) {
- policy.append(text)
- }
- return policy.isEmpty
- ? ["Ask a specific follow-up question when the resolved task is incomplete."]
- : policy
- }
-
- private static func stringArrayMetadata(
- _ text: String?,
- fallback: [String]
- ) -> [String] {
- guard let text,
- let data = text.data(using: .utf8),
- let values = try? JSONSerialization.jsonObject(with: data) as? [String]
- else {
- return fallback
- }
- let cleaned = values.compactMap(nonEmpty)
- return cleaned.isEmpty ? fallback : cleaned
- }
-
- private static func nonEmpty(_ value: String?) -> String? {
- let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
- return trimmed.isEmpty ? nil : trimmed
- }
-
- private static func stringValue(_ value: Any?) -> String? {
- value as? String
- }
}
private extension HarnessThreadEventRole {
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift
deleted file mode 100644
index d3d23e38..00000000
--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift
+++ /dev/null
@@ -1,44 +0,0 @@
-import DonkeyContracts
-
-public enum AppHarnessTurnClassificationKind: String, Equatable, Sendable {
- case unknown
-}
-
-public struct AppHarnessTurnClassification: Equatable, Sendable {
- public var kind: AppHarnessTurnClassificationKind
- public var router: String
- public var missingDetail: String?
- public var metadata: [String: String]
-
- public init(
- kind: AppHarnessTurnClassificationKind,
- router: String,
- missingDetail: String? = nil,
- metadata: [String: String] = [:]
- ) {
- self.kind = kind
- self.router = router
- self.missingDetail = missingDetail
- self.metadata = metadata
- }
-}
-
-public struct AppHarnessTurnClassifier: Sendable {
- public init() {}
-
- public func classify(
- text _: String,
- request _: AppHarnessTurnRequest,
- catalog _: LocalAppTaskCatalog
- ) -> AppHarnessTurnClassification {
- let classifierMetadata = [
- "classifier": "model-intent-required-v1"
- ]
- return AppHarnessTurnClassification(
- kind: .unknown,
- router: "modelIntentRequired",
- missingDetail: "actionable request",
- metadata: classifierMetadata
- )
- }
-}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRequest.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRequest.swift
new file mode 100644
index 00000000..b8abc524
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRequest.swift
@@ -0,0 +1,27 @@
+import DonkeyContracts
+import Foundation
+
+public struct AppHarnessTurnRequest: Equatable, Sendable {
+ public var turn: AppHarnessTurn
+ public var recentEvents: [UserQueryTaskEvent]
+ public var assets: [UserQueryTaskAsset]
+ public var targetState: [String: String]
+ public var memory: [String]
+ public var policy: [String: String]
+
+ public init(
+ turn: AppHarnessTurn,
+ recentEvents: [UserQueryTaskEvent] = [],
+ assets: [UserQueryTaskAsset] = [],
+ targetState: [String: String] = [:],
+ memory: [String] = [],
+ policy: [String: String] = [:]
+ ) {
+ self.turn = turn
+ self.recentEvents = recentEvents
+ self.assets = assets
+ self.targetState = targetState
+ self.memory = memory
+ self.policy = policy
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift
deleted file mode 100644
index a8ed94c7..00000000
--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift
+++ /dev/null
@@ -1,539 +0,0 @@
-import DonkeyContracts
-import Foundation
-
-public struct AppHarnessContextPacketLimits: Equatable, Sendable {
- public var maxRecentEvents: Int
- public var maxAssets: Int
- public var maxEventTextCharacters: Int
- public var maxAssetNameCharacters: Int
- public var maxMemoryItems: Int
- public var maxMemoryTextCharacters: Int
- public var maxPromptCharacters: Int
-
- public init(
- maxRecentEvents: Int = 8,
- maxAssets: Int = 8,
- maxEventTextCharacters: Int = 360,
- maxAssetNameCharacters: Int = 120,
- maxMemoryItems: Int = 4,
- maxMemoryTextCharacters: Int = 360,
- maxPromptCharacters: Int = 3_200
- ) {
- self.maxRecentEvents = max(0, maxRecentEvents)
- self.maxAssets = max(0, maxAssets)
- self.maxEventTextCharacters = max(40, maxEventTextCharacters)
- self.maxAssetNameCharacters = max(24, maxAssetNameCharacters)
- self.maxMemoryItems = max(0, maxMemoryItems)
- self.maxMemoryTextCharacters = max(40, maxMemoryTextCharacters)
- self.maxPromptCharacters = max(240, maxPromptCharacters)
- }
-}
-
-public struct AppHarnessTurnRequest: Equatable, Sendable {
- public var turn: AppHarnessTurn
- public var recentEvents: [UserQueryTaskEvent]
- public var assets: [UserQueryTaskAsset]
- public var targetState: [String: String]
- public var memory: [String]
- public var policy: [String: String]
-
- public init(
- turn: AppHarnessTurn,
- recentEvents: [UserQueryTaskEvent] = [],
- assets: [UserQueryTaskAsset] = [],
- targetState: [String: String] = [:],
- memory: [String] = [],
- policy: [String: String] = [:]
- ) {
- self.turn = turn
- self.recentEvents = recentEvents
- self.assets = assets
- self.targetState = targetState
- self.memory = memory
- self.policy = policy
- }
-}
-
-public struct AppHarnessRoutingOutcome: Equatable, Sendable {
- public var decision: AppHarnessDecision
- public var assistantResponse: String?
- public var missingDetail: String?
- public var resolution: LocalAppTaskCatalogResolution?
- public var metadata: [String: String]
-
- public init(
- decision: AppHarnessDecision,
- assistantResponse: String? = nil,
- missingDetail: String? = nil,
- resolution: LocalAppTaskCatalogResolution? = nil,
- metadata: [String: String] = [:]
- ) {
- self.decision = decision
- self.assistantResponse = assistantResponse
- self.missingDetail = missingDetail
- self.resolution = resolution
- self.metadata = metadata
- }
-}
-
-public struct AppHarnessRoutingResult: Equatable, Sendable {
- public var contextPacket: AppHarnessContextPacket
- public var outcome: AppHarnessRoutingOutcome
-
- public init(contextPacket: AppHarnessContextPacket, outcome: AppHarnessRoutingOutcome) {
- self.contextPacket = contextPacket
- self.outcome = outcome
- }
-}
-
-public struct AppHarnessContextPacketBuilder: Sendable {
- public var limits: AppHarnessContextPacketLimits
-
- public init(limits: AppHarnessContextPacketLimits = AppHarnessContextPacketLimits()) {
- self.limits = limits
- }
-
- public func build(
- request: AppHarnessTurnRequest,
- catalog: LocalAppTaskCatalog,
- traceID: String
- ) -> AppHarnessContextPacket {
- var redactionCount = 0
- var compactionRecords: [AppHarnessContextCompactionRecord] = []
- var turn = request.turn
- let redactedTurn = Self.redacted(turn.text)
- redactionCount += redactedTurn.count
- let boundedTurn = Self.bounded(redactedTurn.text, maxLength: limits.maxPromptCharacters)
- turn.text = boundedTurn.text
- compactionRecords.append(
- AppHarnessContextCompactionRecord(
- itemKind: .currentTurn,
- originalCount: request.turn.text.isEmpty ? 0 : 1,
- includedCount: turn.text.isEmpty ? 0 : 1,
- truncatedCount: boundedTurn.wasTruncated ? 1 : 0,
- metadata: ["traceID": traceID]
- )
- )
-
- let preparedEvents = request.recentEvents.map { event -> PreparedHarnessContextEvent in
- let redacted = Self.redacted(event.text)
- redactionCount += redacted.count
- let bounded = Self.bounded(redacted.text, maxLength: limits.maxEventTextCharacters)
- return PreparedHarnessContextEvent(
- event: AppHarnessContextEvent(
- role: event.role,
- text: bounded.text,
- sequence: event.sequence
- ),
- sourceID: event.id,
- isTransientCorrection: Self.isTransientCorrection(event),
- wasTruncated: bounded.wasTruncated
- )
- }
- let eventCompaction = Self.compactEvents(
- preparedEvents,
- limit: limits.maxRecentEvents
- )
- let events = eventCompaction.events
- compactionRecords.append(contentsOf: eventCompaction.records)
-
- let assets = request.assets
- .suffix(limits.maxAssets)
- .map { asset -> AppHarnessContextAsset in
- let boundedName = Self.bounded(asset.displayName, maxLength: limits.maxAssetNameCharacters)
- return AppHarnessContextAsset(
- displayName: boundedName.text,
- contentType: asset.contentType,
- byteCount: asset.byteCount
- )
- }
- compactionRecords.append(
- AppHarnessContextCompactionRecord(
- itemKind: .asset,
- originalCount: request.assets.count,
- includedCount: assets.count,
- droppedCount: max(0, request.assets.count - assets.count),
- truncatedCount: request.assets.suffix(limits.maxAssets).filter {
- $0.displayName.count > limits.maxAssetNameCharacters
- }.count
- )
- )
-
- let memory = request.memory
- .prefix(limits.maxMemoryItems)
- .map { item -> String in
- let redacted = Self.redacted(item)
- redactionCount += redacted.count
- return Self.bounded(redacted.text, maxLength: limits.maxMemoryTextCharacters).text
- }
- compactionRecords.append(
- AppHarnessContextCompactionRecord(
- itemKind: .memory,
- originalCount: request.memory.count,
- includedCount: memory.count,
- droppedCount: max(0, request.memory.count - memory.count),
- truncatedCount: request.memory.prefix(limits.maxMemoryItems).filter {
- Self.redacted($0).text.count > limits.maxMemoryTextCharacters
- }.count
- )
- )
-
- let runtimeCapabilities = catalog.taskDefinitions
- .map { "\($0.taskType):\($0.targetApp.appName)" }
- .sorted()
- compactionRecords.append(
- AppHarnessContextCompactionRecord(
- itemKind: .runtimeCapability,
- originalCount: catalog.taskDefinitions.count,
- includedCount: runtimeCapabilities.count
- )
- )
- compactionRecords.append(
- AppHarnessContextCompactionRecord(
- itemKind: .targetState,
- originalCount: request.targetState.count,
- includedCount: request.targetState.count
- )
- )
- compactionRecords.append(
- AppHarnessContextCompactionRecord(
- itemKind: .policy,
- originalCount: request.policy.count,
- includedCount: request.policy.count
- )
- )
-
- let promptBounds = Self.bounded(
- Self.promptText(
- turn: turn,
- events: events,
- assets: assets,
- runtimeCapabilities: runtimeCapabilities,
- targetState: request.targetState,
- memory: memory,
- policy: request.policy
- ),
- maxLength: limits.maxPromptCharacters
- )
- let promptText = promptBounds.text
-
- return AppHarnessContextPacket(
- traceID: traceID,
- currentTurn: turn,
- recentEvents: events,
- assets: assets,
- runtimeCapabilities: runtimeCapabilities,
- targetState: request.targetState,
- memory: memory,
- policy: request.policy,
- promptText: promptText,
- redactionCount: redactionCount,
- compactionRecords: compactionRecords,
- metadata: [
- "bounds.maxRecentEvents": String(limits.maxRecentEvents),
- "bounds.maxAssets": String(limits.maxAssets),
- "bounds.maxPromptCharacters": String(limits.maxPromptCharacters),
- "compaction.recordCount": String(compactionRecords.count),
- "compaction.promptTruncated": String(promptBounds.wasTruncated),
- "events.originalCount": String(request.recentEvents.count),
- "events.droppedCount": String(eventCompaction.droppedCount),
- "events.droppedTransientCorrectionCount": String(eventCompaction.droppedTransientCorrectionCount),
- "events.includedCount": String(events.count),
- "assets.includedCount": String(assets.count),
- "memory.includedCount": String(memory.count),
- "prompt.characterCount": String(promptText.count)
- ]
- )
- }
-
- private static func promptText(
- turn: AppHarnessTurn,
- events: [AppHarnessContextEvent],
- assets: [AppHarnessContextAsset],
- runtimeCapabilities: [String],
- targetState: [String: String],
- memory: [String],
- policy: [String: String]
- ) -> String {
- var sections = [
- "Trace: \(turn.id)",
- "Turn source: \(turn.source.rawValue)",
- "Current turn: \(turn.text)"
- ]
- if !events.isEmpty {
- sections.append("Recent thread:\n" + events.map { "\($0.role.rawValue): \($0.text)" }.joined(separator: "\n"))
- }
- if !assets.isEmpty {
- sections.append("Assets: " + assets.map { "\($0.displayName) (\($0.contentType))" }.joined(separator: ", "))
- }
- if !runtimeCapabilities.isEmpty {
- sections.append("Runtime capabilities: " + runtimeCapabilities.joined(separator: ", "))
- }
- if !targetState.isEmpty {
- sections.append("Target state: " + keyValueText(targetState))
- }
- if !memory.isEmpty {
- sections.append("Memory:\n" + memory.joined(separator: "\n"))
- }
- if !policy.isEmpty {
- sections.append("Policy: " + keyValueText(policy))
- }
- return sections.joined(separator: "\n\n")
- }
-
- private static func keyValueText(_ values: [String: String]) -> String {
- values
- .sorted { $0.key < $1.key }
- .map { "\($0.key)=\($0.value)" }
- .joined(separator: ", ")
- }
-
- private static func redacted(_ text: String) -> (text: String, count: Int) {
- var redacted = text
- var count = 0
- let replacements = [
- #"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}"#: "[redacted-email]",
- #"\b(?:\d[ -]*?){13,16}\b"#: "[redacted-number]",
- #"(?i)(password|token|api[_ -]?key)\s*[:=]\s*\S+"#: "$1=[redacted-secret]"
- ]
- for (pattern, replacement) in replacements {
- guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else {
- continue
- }
- let range = NSRange(redacted.startIndex..<redacted.endIndex, in: redacted)
- count += regex.numberOfMatches(in: redacted, range: range)
- redacted = regex.stringByReplacingMatches(
- in: redacted,
- options: [],
- range: range,
- withTemplate: replacement
- )
- }
- return (redacted, count)
- }
-
- private static func bounded(_ text: String, maxLength: Int) -> (text: String, wasTruncated: Bool) {
- guard text.count > maxLength else { return (text, false) }
-
- let endIndex = text.index(text.startIndex, offsetBy: maxLength)
- return (String(text[..<endIndex]).trimmingCharacters(in: .whitespacesAndNewlines) + "...", true)
- }
-
- private static func compactEvents(
- _ preparedEvents: [PreparedHarnessContextEvent],
- limit: Int
- ) -> HarnessEventCompactionResult {
- guard limit > 0 else {
- let transientCount = preparedEvents.filter(\.isTransientCorrection).count
- return HarnessEventCompactionResult(
- events: [],
- records: [
- AppHarnessContextCompactionRecord(
- itemKind: .recentEvent,
- originalCount: preparedEvents.count,
- includedCount: 0,
- droppedCount: preparedEvents.count,
- truncatedCount: 0
- ),
- AppHarnessContextCompactionRecord(
- itemKind: .transientCorrection,
- originalCount: transientCount,
- includedCount: 0,
- droppedCount: transientCount,
- truncatedCount: 0
- )
- ],
- droppedCount: preparedEvents.count,
- droppedTransientCorrectionCount: transientCount
- )
- }
-
- let selected: [PreparedHarnessContextEvent]
- if preparedEvents.count <= limit {
- selected = preparedEvents
- } else {
- let nonTransient = preparedEvents.filter { !$0.isTransientCorrection }
- var chosen = Array(nonTransient.suffix(limit))
- if chosen.count < limit {
- let chosenIDs = Set(chosen.map(\.sourceID))
- let fill = preparedEvents
- .filter { $0.isTransientCorrection && !chosenIDs.contains($0.sourceID) }
- .suffix(limit - chosen.count)
- chosen.append(contentsOf: fill)
- }
- selected = chosen.sorted { lhs, rhs in
- if lhs.event.sequence == rhs.event.sequence {
- return lhs.sourceID < rhs.sourceID
- }
- return lhs.event.sequence < rhs.event.sequence
- }
- }
-
- let selectedIDs = Set(selected.map(\.sourceID))
- let dropped = preparedEvents.filter { !selectedIDs.contains($0.sourceID) }
- let transientOriginal = preparedEvents.filter(\.isTransientCorrection).count
- let transientIncluded = selected.filter(\.isTransientCorrection).count
- let transientDropped = dropped.filter(\.isTransientCorrection).count
- let recentTruncated = selected.filter { !$0.isTransientCorrection && $0.wasTruncated }.count
- let transientTruncated = selected.filter { $0.isTransientCorrection && $0.wasTruncated }.count
-
- return HarnessEventCompactionResult(
- events: selected.map(\.event),
- records: [
- AppHarnessContextCompactionRecord(
- itemKind: .recentEvent,
- originalCount: preparedEvents.count,
- includedCount: selected.count,
- droppedCount: dropped.count,
- truncatedCount: recentTruncated,
- metadata: ["strategy": "dropTransientCorrectionsFirst"]
- ),
- AppHarnessContextCompactionRecord(
- itemKind: .transientCorrection,
- originalCount: transientOriginal,
- includedCount: transientIncluded,
- droppedCount: transientDropped,
- truncatedCount: transientTruncated,
- metadata: ["strategy": "dropBeforeDurableEvents"]
- )
- ],
- droppedCount: dropped.count,
- droppedTransientCorrectionCount: transientDropped
- )
- }
-
- private static func isTransientCorrection(_: UserQueryTaskEvent) -> Bool {
- false
- }
-}
-
-private struct PreparedHarnessContextEvent: Equatable, Sendable {
- var event: AppHarnessContextEvent
- var sourceID: String
- var isTransientCorrection: Bool
- var wasTruncated: Bool
-}
-
-private struct HarnessEventCompactionResult: Equatable, Sendable {
- var events: [AppHarnessContextEvent]
- var records: [AppHarnessContextCompactionRecord]
- var droppedCount: Int
- var droppedTransientCorrectionCount: Int
-}
-
-public struct AppHarnessTurnRouter: Sendable {
- public var catalog: LocalAppTaskCatalog
- public var contextBuilder: AppHarnessContextPacketBuilder
- public var turnClassifier: AppHarnessTurnClassifier
-
- public init(
- catalog: LocalAppTaskCatalog,
- contextBuilder: AppHarnessContextPacketBuilder = AppHarnessContextPacketBuilder(),
- turnClassifier: AppHarnessTurnClassifier = AppHarnessTurnClassifier()
- ) {
- self.catalog = catalog
- self.contextBuilder = contextBuilder
- self.turnClassifier = turnClassifier
- }
-
- public func route(
- request: AppHarnessTurnRequest,
- traceID: String
- ) -> AppHarnessRoutingResult {
- let packet = contextBuilder.build(
- request: request,
- catalog: catalog,
- traceID: traceID
- )
- let trimmedText = request.turn.text.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmedText.isEmpty else {
- return AppHarnessRoutingResult(
- contextPacket: packet,
- outcome: AppHarnessRoutingOutcome(
- decision: AppHarnessDecision(
- kind: .noOp,
- traceID: traceID,
- metadata: ["router": "emptyTurn"]
- ),
- metadata: ["router": "emptyTurn"]
- )
- )
- }
-
- let classification = turnClassifier.classify(
- text: trimmedText,
- request: request,
- catalog: catalog
- )
-
- if request.turn.isFollowUp && classification.kind == .unknown {
- return AppHarnessRoutingResult(
- contextPacket: packet,
- outcome: AppHarnessRoutingOutcome(
- decision: decision(
- kind: .runLocalTask,
- traceID: traceID,
- metadata: ["router": "followUpActionContext"]
- ),
- metadata: ["router": "followUpActionContext"]
- )
- )
- }
-
- return AppHarnessRoutingResult(
- contextPacket: packet,
- outcome: AppHarnessRoutingOutcome(
- decision: decision(
- kind: .runLocalTask,
- traceID: traceID,
- metadata: ["router": "modelIntent"]
- ),
- metadata: ["router": "modelIntent"].merging(classification.metadata) { current, _ in current }
- )
- )
- }
-
- private func decision(
- kind: AppHarnessDecisionKind,
- traceID: String,
- message: String? = nil,
- missingDetail: String? = nil,
- resolution: LocalAppTaskCatalogResolution? = nil,
- metadata: [String: String] = [:]
- ) -> AppHarnessDecision {
- AppHarnessDecision(
- kind: kind,
- message: message,
- missingDetail: missingDetail,
- taskIntentID: resolution?.intent?.intentID,
- traceID: traceID,
- metadata: metadata.merging([
- "structuredDecision": "true",
- "resolution.status": resolution?.status.rawValue ?? "none"
- ]) { current, _ in current }
- )
- }
-
- private func clarificationPrompt(
- for missingDetail: String,
- resolution: LocalAppTaskCatalogResolution
- ) -> String {
- let readableDetail = missingDetail
- .split(separator: "_")
- .joined(separator: " ")
- if let definition = resolution.definition {
- let taskTitle = Self.displayTitle(for: definition)
- return "What \(readableDetail) should I use for \(taskTitle)?"
- }
- return "What \(readableDetail) should I use?"
- }
-
- private static func displayTitle(for definition: LocalAppTaskDefinition) -> String {
- if let displayTitle = definition.metadata["displayTitle"], !displayTitle.isEmpty {
- return displayTitle
- }
- return definition.taskType
- .split(separator: "_")
- .joined(separator: " ")
- }
-}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift
deleted file mode 100644
index 00914b33..00000000
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppHarnessStepExecutor.swift
+++ /dev/null
@@ -1,956 +0,0 @@
-import DonkeyContracts
-import DonkeyHarness
-import Foundation
-
-public actor LocalAppHarnessStepExecutor {
- public typealias ActionEngineFactory = @Sendable (LocalAppTaskDefinition) -> ActionEngineGuardrail
- public typealias AutomationActionEngineFactory = @Sendable (LocalAppTaskDefinition) -> ActionEngineGuardrail
-
- private let command: String
- private let traceID: String
- private let resolution: LocalAppTaskCatalogResolution
- private let baseMetadata: [String: String]
- private let appController: any LocalAppTaskAppControlling
- private let actionEngineFactory: ActionEngineFactory
- private let automationActionEngineFactory: AutomationActionEngineFactory
- private let permissionPolicy: ToolCallPolicy
- private let coordinator: RunCoordinator?
-
- private var runStartedAt = ProcessInfo.processInfo.systemUptime * 1_000
- private var runStarted = false
- private var latestObservation: LocalAppTaskObservation?
- private var initialActionPlan: LocalAppEvidenceBackedActionPlan?
- private var finalActionPlan: LocalAppEvidenceBackedActionPlan?
- private var actionTraces: [ActionEngineCommandTrace] = []
- private var executedWorkflowStepIDs: Set<String> = []
- private var latestStatus: LocalAppTaskLiveRunStatus = .failedSafe
- private var latestStatusReason = "notStarted"
- private var latestFailureFacts: [String: String] = [:]
-
- public init(
- command: String,
- traceID: String,
- resolution: LocalAppTaskCatalogResolution,
- metadata: [String: String] = [:],
- appController: any LocalAppTaskAppControlling,
- actionEngineFactory: @escaping ActionEngineFactory = LocalAppTaskActionEngines.keyboardOrAutomation(for:),
- automationActionEngineFactory: @escaping AutomationActionEngineFactory = LocalAppTaskActionEngines.appleScriptAutomation(for:),
- permissionPolicy: ToolCallPolicy = ToolCallPolicy(
- allowedCapabilities: ToolCallPolicy.defaultAllowedCapabilities.union([.input]),
- deniedCapabilities: []
- ),
- coordinator: RunCoordinator? = nil
- ) {
- self.command = command
- self.traceID = traceID
- self.resolution = resolution
- self.baseMetadata = metadata
- self.appController = appController
- self.actionEngineFactory = actionEngineFactory
- self.automationActionEngineFactory = automationActionEngineFactory
- self.permissionPolicy = permissionPolicy
- self.coordinator = coordinator
- }
-
- public static var descriptors: [HarnessToolDescriptor] {
- [
- descriptor(
- .openOrFocusApp,
- summary: "Open or focus the resolved local app and return bounded app evidence.",
- input: ["targetID": "Resolved local app target."],
- output: ["observation": "Focused app and visible state evidence."],
- permissions: [.appControl],
- safety: .reversible
- ),
- descriptor(
- .observeApp,
- summary: "Observe the resolved local app with Accessibility and screenshot evidence when needed.",
- output: ["observation": "Visible text, controls, and evidence metadata."],
- permissions: [.screenCapture, .accessibility],
- safety: .readOnly
- ),
- descriptor(
- .newDocument,
- summary: "Run one guarded model-planned new document action.",
- input: ["focusKey": "Model-selected shortcut when provided."],
- permissions: [.input],
- safety: .guardedInput
- ),
- descriptor(
- .focusSearch,
- summary: "Run one guarded model-planned search focus action.",
- input: ["controlID": "Model-selected control id.", "focusKey": "Model-selected shortcut."],
- permissions: [.input],
- safety: .guardedInput
- ),
- descriptor(
- .focusAddressBar,
- summary: "Run one guarded model-planned address-bar focus action.",
- input: ["controlID": "Model-selected control id.", "focusKey": "Model-selected shortcut."],
- permissions: [.input],
- safety: .guardedInput
- ),
- descriptor(
- .focusTextEntry,
- summary: "Run one guarded model-planned text-entry focus action.",
- input: ["controlID": "Model-selected control id.", "focusKey": "Model-selected shortcut."],
- permissions: [.input],
- safety: .guardedInput
- ),
- descriptor(
- .setText,
- summary: "Enter one model-selected structured entity into the focused local-app control.",
- input: ["inputEntity": "Structured intent entity to type.", "controlID": "Model-selected control id."],
- permissions: [.input],
- safety: .guardedInput
- ),
- descriptor(
- .clickTarget,
- summary: "Click one model-selected Accessibility or AI visual target.",
- input: ["controlID": "Model-selected Accessibility control id or AI visual segment id."],
- permissions: [.input],
- safety: .guardedInput
- ),
- descriptor(
- .pressReturn,
- summary: "Run one guarded model-planned Return submit action.",
- input: ["focusKey": "Optional model-selected key."],
- permissions: [.input],
- safety: .guardedInput
- ),
- descriptor(
- .verifyCommand,
- summary: "Observe the app and verify command progress from concrete post-action evidence.",
- output: ["verification": "Verified, blocked, or failed status with evidence."],
- permissions: [.screenCapture, .accessibility, .verification],
- safety: .readOnly
- ),
- descriptor(
- .verifyVisibleText,
- summary: "Observe the app and verify visible text from concrete post-action evidence.",
- output: ["verification": "Verified, blocked, or failed status with evidence."],
- permissions: [.screenCapture, .accessibility, .verification],
- safety: .readOnly
- )
- ]
- }
-
- public func registerTools(in registry: HarnessToolRegistry) async {
- for descriptor in Self.descriptors {
- await registry.register(
- HarnessTool(descriptor: descriptor) { context in
- await self.execute(context)
- }
- )
- }
- }
-
- public func currentResult() -> LocalAppTaskLiveRunResult {
- makeResult(status: latestStatus, reason: latestStatusReason)
- }
-
- private func execute(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
- guard let tool = LocalAppActionPlanTool(rawValue: context.call.name) else {
- return HarnessToolResult(
- callID: context.call.id,
- toolName: context.call.name,
- status: .unknownTool,
- summary: "Unknown local-app harness tool.",
- metadata: ["reason": "unknownLocalAppTool"]
- )
- }
-
- guard resolution.status == .resolved,
- let definition = resolution.definition,
- let intent = resolution.intent,
- let availability = resolution.availability
- else {
- let result = unresolvedToolResult(context)
- latestStatus = status(for: resolution.status)
- latestStatusReason = result.metadata["reason"] ?? resolution.status.rawValue
- return result
- }
-
- await publishRunStartIfNeeded(definition: definition, intent: intent)
-
- switch tool {
- case .openOrFocusApp:
- return await openOrFocus(context, definition: definition, intent: intent, availability: availability)
- case .observeApp:
- return await observe(context, definition: definition, intent: intent, reason: "observe")
- case .newDocument, .focusSearch, .focusAddressBar, .focusTextEntry, .setText, .clickTarget, .pressReturn:
- return await executeAction(context, tool: tool, definition: definition, intent: intent, availability: availability)
- case .verifyCommand, .verifyVisibleText:
- return await verify(context, tool: tool, definition: definition, intent: intent)
- }
- }
-
- private func openOrFocus(
- _ context: HarnessToolExecutionContext,
- definition: LocalAppTaskDefinition,
- intent: TaskIntent,
- availability: LocalAppAvailability
- ) async -> HarnessToolResult {
- await coordinator?.recordToolEvent(
- capability: .input,
- decision: permissionPolicy.decision(for: .input),
- toolName: "mac-launch-focus",
- summary: "Launching or focusing local app",
- traceID: traceID,
- metadata: [
- "targetApp": definition.targetApp.appName,
- "bundleIdentifier": definition.targetApp.bundleIdentifier ?? ""
- ]
- )
- let observation = await appController.launchOrFocus(
- definition: definition,
- availability: availability
- )
- latestObservation = observation
- initialActionPlan = LocalAppTaskAdapter(definition: definition)
- .evidenceBackedActionPlan(for: intent, observation: observation)
- latestStatus = .needsUserReview
- latestStatusReason = "openedOrFocusedAwaitingVerification"
- return observationResult(
- context,
- observation: observation,
- summary: "Observed local app after open or focus.",
- status: observation.appIsFocused || observation.appIsRunning ? .succeeded : .failed,
- extraFacts: ["localApp.lastStep": context.call.name]
- )
- }
-
- private func observe(
- _ context: HarnessToolExecutionContext,
- definition: LocalAppTaskDefinition,
- intent: TaskIntent,
- reason: String
- ) async -> HarnessToolResult {
- await coordinator?.recordToolEvent(
- capability: .perception,
- decision: permissionPolicy.decision(for: .perception),
- toolName: "local-app-observation",
- summary: "Observing local app",
- traceID: traceID,
- metadata: ["reason": reason]
- )
- let observation = await observeAppState(definition: definition, intent: intent, reason: reason)
- latestObservation = observation
- initialActionPlan = initialActionPlan ?? LocalAppTaskAdapter(definition: definition)
- .evidenceBackedActionPlan(for: intent, observation: observation)
- latestStatus = .needsUserReview
- latestStatusReason = "observedAwaitingVerification"
- return observationResult(
- context,
- observation: observation,
- summary: "Observed local app state.",
- status: .succeeded,
- extraFacts: ["localApp.lastStep": context.call.name]
- )
- }
-
- private func observeAppState(
- definition: LocalAppTaskDefinition,
- intent: TaskIntent,
- reason: String
- ) async -> LocalAppTaskObservation {
- await appController.observe(definition: definition) { partialObservation in
- await self.recordPartialObservation(
- partialObservation,
- definition: definition,
- intent: intent,
- reason: reason
- )
- }
- }
-
- private func recordPartialObservation(
- _ observation: LocalAppTaskObservation,
- definition: LocalAppTaskDefinition,
- intent: TaskIntent,
- reason: String
- ) async {
- latestObservation = observationWithActionEvidence(observation)
- initialActionPlan = initialActionPlan ?? LocalAppTaskAdapter(definition: definition)
- .evidenceBackedActionPlan(for: intent, observation: latestObservation)
- await coordinator?.recordToolEvent(
- capability: .perception,
- decision: permissionPolicy.decision(for: .perception),
- toolName: "local-app-observation",
- summary: "Observed partial streaming UI evidence",
- traceID: traceID,
- metadata: [
- "reason": reason,
- "stream": "partial",
- "controlCount": observation.metadata["controlCount"] ?? "",
- "source": observation.metadata["runtime.backend"] ?? observation.metadata["observer"] ?? ""
- ]
- )
- }
-
- private func executeAction(
- _ context: HarnessToolExecutionContext,
- tool: LocalAppActionPlanTool,
- definition: LocalAppTaskDefinition,
- intent: TaskIntent,
- availability: LocalAppAvailability
- ) async -> HarnessToolResult {
- let adapter = LocalAppTaskAdapter(definition: definition)
- let command = commandTemplate(
- tool: tool,
- context: context,
- adapter: adapter,
- intent: intent
- )
- guard let command else {
- latestStatus = .failedSafe
- latestStatusReason = "missingModelPlannedCommand"
- latestFailureFacts = [
- "missingTool": context.call.name,
- "missingTool.inputEntity": context.call.input["inputEntity"] ?? "",
- "missingTool.controlID": context.call.input["controlID"] ?? "",
- "missingTool.focusKey": context.call.input["focusKey"] ?? "",
- "missingTool.modelStepID": context.call.input["modelStepID"] ?? "",
- "plan.tools": definition.metadata["plan.tools"] ?? ""
- ]
- return HarnessToolResult(
- callID: context.call.id,
- toolName: context.call.name,
- status: .failed,
- summary: "No guarded command matched the model-planned local-app step.",
- observations: HarnessObservationDelta(
- facts: [
- "localApp.status": latestStatus.rawValue,
- "localApp.reason": latestStatusReason,
- "localApp.missingTool": context.call.name
- ],
- uncertainty: ["missing guarded command for \(context.call.name)"]
- ),
- metadata: ["reason": latestStatusReason]
- )
- }
-
- await coordinator?.recordToolEvent(
- capability: .input,
- decision: permissionPolicy.decision(for: .input),
- toolName: command.metadata["automationBackend"] == "appleScript"
- ? "mac-applescript-action-engine"
- : "mac-keyboard-action-engine",
- summary: "Executing one guarded local-app command",
- traceID: traceID,
- metadata: [
- "commandID": command.id,
- "workflowStepID": command.metadata["workflowStepID"] ?? "",
- "modelToolName": context.call.name
- ]
- )
- let engine = actionEngineFactory(definition)
- var trace = await engine.handle(command, permissionPolicy: permissionPolicy)
- actionTraces.append(trace)
- if trace.decision == .denied(reason: "focus guard failed") {
- _ = await appController.launchOrFocus(definition: definition, availability: availability)
- let retry = command.withHarnessIssuedAt(Self.now(advancedByMilliseconds: 25))
- trace = await engine.handle(retry, permissionPolicy: permissionPolicy)
- actionTraces.append(trace)
- }
-
- if trace.executed || trace.decision == .skippedNoLiveInput {
- if let workflowStepID = workflowStepID(from: trace.command) {
- executedWorkflowStepIDs.insert(workflowStepID)
- }
- } else {
- latestStatus = .failedSafe
- latestStatusReason = "actionDenied"
- let observation = await observeAppState(definition: definition, intent: intent, reason: "actionDenied")
- latestObservation = observationWithActionEvidence(observation)
- return HarnessToolResult(
- callID: context.call.id,
- toolName: context.call.name,
- status: .failed,
- summary: "Guarded local-app command was denied.",
- observations: observationDelta(
- latestObservation,
- definition: definition,
- extraFacts: [
- "localApp.status": latestStatus.rawValue,
- "localApp.reason": latestStatusReason,
- "localApp.actionDeniedReason": decisionReason(trace.decision)
- ],
- uncertainty: ["guarded command denied"]
- ),
- metadata: [
- "reason": latestStatusReason,
- "actionDeniedReason": decisionReason(trace.decision)
- ].merging(actionTraceMetadata()) { current, _ in current }
- )
- }
-
- try? await Task.sleep(nanoseconds: 200_000_000)
- let observation = await observeAppState(definition: definition, intent: intent, reason: "postAction")
- latestObservation = observationWithActionEvidence(observation)
- latestStatus = .needsUserReview
- latestStatusReason = "actionExecutedAwaitingVerification"
- return observationResult(
- context,
- observation: latestObservation,
- summary: "Executed one guarded local-app command and observed the result.",
- status: .succeeded,
- extraFacts: [
- "localApp.status": latestStatus.rawValue,
- "localApp.lastStep": context.call.name
- ],
- metadata: actionTraceMetadata()
- )
- }
-
- private func verify(
- _ context: HarnessToolExecutionContext,
- tool: LocalAppActionPlanTool,
- definition: LocalAppTaskDefinition,
- intent: TaskIntent
- ) async -> HarnessToolResult {
- try? await Task.sleep(nanoseconds: 700_000_000)
- await coordinator?.recordToolEvent(
- capability: .perception,
- decision: permissionPolicy.decision(for: .perception),
- toolName: "local-app-observation",
- summary: "Observing local app for verification",
- traceID: traceID,
- metadata: ["modelToolName": context.call.name]
- )
- let observation = await observeAppState(definition: definition, intent: intent, reason: "verify")
- latestObservation = observationWithActionEvidence(observation)
- let plan = LocalAppTaskAdapter(definition: definition)
- .evidenceBackedActionPlan(for: intent, observation: latestObservation)
- let verification = LocalAppTaskVerificationPolicy.verify(
- intent: intent,
- definition: definition,
- observation: latestObservation,
- tool: tool
- )
- finalActionPlan = plan
- latestStatus = status(for: verification.terminalState)
- latestStatusReason = verification.metadata["reason"] ?? verification.terminalState.rawValue
- let verified = verification.terminalState == .completed
- if verified {
- await coordinator?.complete(reason: "Local app task completed")
- } else {
- await coordinator?.pause(reason: "Local app task verification did not complete")
- }
- var facts = [
- "localApp.status": latestStatus.rawValue,
- "localApp.reason": latestStatusReason,
- "verification.status": verification.status.rawValue,
- "verification.summary": verification.summary,
- "verification.verified": String(verified),
- "lastAcceptedTool": context.call.name
- ]
- for (key, value) in verification.metadata {
- facts["verification.\(key)"] = value
- }
- return HarnessToolResult(
- callID: context.call.id,
- toolName: context.call.name,
- status: verified ? .succeeded : .failed,
- summary: verified
- ? "Local app verification succeeded."
- : "Local app verification did not find completed evidence.",
- observations: observationDelta(
- latestObservation,
- definition: definition,
- extraFacts: facts,
- uncertainty: verified ? [] : ["local app verification incomplete"]
- ),
- metadata: facts.merging(actionTraceMetadata()) { current, _ in current }
- )
- }
-
- private func commandTemplate(
- tool: LocalAppActionPlanTool,
- context: HarnessToolExecutionContext,
- adapter: LocalAppTaskAdapter,
- intent: TaskIntent
- ) -> ActionEngineCommand? {
- let automationCommands = adapter.guardedAutomationCommandTemplates(
- for: intent,
- issuedAt: Self.now()
- )
- let keyboardCommands = automationCommands.isEmpty
- ? adapter.guardedKeyboardCommandTemplates(for: intent, issuedAt: Self.now())
- : automationCommands
- let inputEntity = Self.trimmed(context.call.input["inputEntity"])
- let controlID = Self.trimmed(context.call.input["controlID"])
- let focusKey = Self.trimmed(context.call.input["focusKey"])
- let candidates = keyboardCommands.filter { command in
- if executedWorkflowStepIDs.contains(workflowStepID(from: command) ?? "") {
- return false
- }
- if command.metadata["plan.tool"] == tool.rawValue {
- return matchesStructuredInputs(
- command,
- inputEntity: inputEntity,
- controlID: controlID,
- focusKey: focusKey
- )
- }
- return role(for: tool) == command.metadata["workflowStepRole"]
- && matchesStructuredInputs(
- command,
- inputEntity: inputEntity,
- controlID: controlID,
- focusKey: focusKey
- )
- }
- return candidates.first?.withHarnessIssuedAt(Self.now())
- ?? visualClickCommand(
- tool: tool,
- context: context,
- adapter: adapter,
- intent: intent,
- controlID: controlID
- )
- ?? structuredKeyboardCommand(
- tool: tool,
- context: context,
- adapter: adapter,
- intent: intent,
- inputEntity: inputEntity,
- controlID: controlID,
- focusKey: focusKey
- )
- }
-
- private func matchesStructuredInputs(
- _ command: ActionEngineCommand,
- inputEntity: String?,
- controlID: String?,
- focusKey: String?
- ) -> Bool {
- if let inputEntity,
- let commandEntity = command.metadata["entityName"],
- commandEntity != inputEntity {
- return false
- }
- if let controlID,
- let commandControlID = command.metadata["controlID"],
- commandControlID != controlID {
- return false
- }
- if let focusKey,
- !focusKey.isEmpty,
- command.key != focusKey,
- command.metadata["key"] != focusKey {
- return false
- }
- return true
- }
-
- private func visualClickCommand(
- tool: LocalAppActionPlanTool,
- context: HarnessToolExecutionContext,
- adapter: LocalAppTaskAdapter,
- intent: TaskIntent,
- controlID: String?
- ) -> ActionEngineCommand? {
- guard [.focusSearch, .focusAddressBar, .focusTextEntry, .clickTarget].contains(tool),
- let controlID,
- let observation = latestObservation,
- let targetBounds = LocalAppObservationGeometry.screenControlBounds(
- controlID: controlID,
- metadata: observation.metadata
- )
- else {
- return nil
- }
-
- return ActionEngineCommand(
- id: "\(intent.intentID)-visual-click-\(Self.slug(controlID))",
- traceID: intent.metadata["traceID"] ?? intent.intentID,
- targetID: adapter.targetID,
- kind: .tap,
- issuedAt: Self.now(),
- targetBounds: targetBounds,
- metadata: LocalAppObservationGeometry.groundedMetadata(
- controlID: controlID,
- observation: observation
- ).merging([
- "taskIntentID": intent.intentID,
- "taskType": intent.taskType,
- "targetApp": adapter.definition.targetApp.appName,
- "bundleIdentifier": adapter.definition.targetApp.bundleIdentifier ?? "",
- "workflowStepID": context.call.input["modelStepID"] ?? "visual-click-\(Self.slug(controlID))",
- "workflowStepRole": role(for: tool),
- "controlID": controlID,
- "inputStrategy": "visual-coordinate",
- "visualFallback": "aiOrObservedBounds",
- "plan.tool": tool.rawValue
- ]) { current, _ in current }
- )
- }
-
- private func structuredKeyboardCommand(
- tool: LocalAppActionPlanTool,
- context: HarnessToolExecutionContext,
- adapter: LocalAppTaskAdapter,
- intent: TaskIntent,
- inputEntity: String?,
- controlID: String?,
- focusKey: String?
- ) -> ActionEngineCommand? {
- let key: String
- var metadata: [String: String] = [
- "taskIntentID": intent.intentID,
- "taskType": intent.taskType,
- "targetApp": adapter.definition.targetApp.appName,
- "bundleIdentifier": adapter.definition.targetApp.bundleIdentifier ?? "",
- "workflowStepID": context.call.input["modelStepID"] ?? "model-step-\(Self.slug(tool.rawValue))",
- "workflowStepRole": role(for: tool),
- "plan.tool": tool.rawValue,
- "inputStrategy": "model-planned-tool-call"
- ]
- if let controlID {
- metadata["controlID"] = controlID
- }
-
- switch tool {
- case .setText:
- guard let inputEntity,
- let text = intent.normalizedEntities[inputEntity] ?? intent.entities[inputEntity],
- !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
- else {
- return nil
- }
- key = text
- metadata["entityName"] = inputEntity
- metadata["inputRole"] = "textEntry"
- metadata["text"] = text
- case .pressReturn:
- key = "Return"
- case .newDocument:
- key = "Command+N"
- case .focusSearch, .focusAddressBar, .focusTextEntry:
- guard let focusKey else { return nil }
- key = focusKey
- case .openOrFocusApp, .observeApp, .clickTarget, .verifyCommand, .verifyVisibleText:
- return nil
- }
-
- return ActionEngineCommand(
- id: "\(intent.intentID)-model-step-\(Self.slug(context.call.id))",
- traceID: intent.metadata["traceID"] ?? intent.intentID,
- targetID: adapter.targetID,
- kind: .key,
- issuedAt: Self.now(),
- key: key,
- metadata: metadata
- )
- }
-
- private func observationWithActionEvidence(_ observation: LocalAppTaskObservation?) -> LocalAppTaskObservation? {
- guard var observation else { return nil }
- let executed = actionTraces.filter(\.executed)
- let submitCount = executed.filter {
- $0.command.metadata["workflowStepRole"] == LocalAppTaskStepRole.submit.rawValue
- }.count
- observation.metadata.merge([
- "postActionObservation": "true",
- "executedCommandCount": String(executed.count),
- "submittedCommandCount": String(submitCount)
- ]) { current, _ in current }
- return observation
- }
-
- private func observationResult(
- _ context: HarnessToolExecutionContext,
- observation: LocalAppTaskObservation?,
- summary: String,
- status: HarnessToolResultStatus,
- extraFacts: [String: String] = [:],
- metadata: [String: String] = [:]
- ) -> HarnessToolResult {
- HarnessToolResult(
- callID: context.call.id,
- toolName: context.call.name,
- status: status,
- summary: summary,
- observations: observationDelta(
- observation,
- definition: resolution.definition,
- extraFacts: extraFacts,
- uncertainty: status == .succeeded ? [] : ["local app observation incomplete"]
- ),
- metadata: metadata.merging([
- "executor": "LocalAppHarnessStepExecutor",
- "traceID": traceID
- ]) { current, _ in current }
- )
- }
-
- private func observationDelta(
- _ observation: LocalAppTaskObservation?,
- definition: LocalAppTaskDefinition?,
- extraFacts: [String: String] = [:],
- uncertainty: [String] = []
- ) -> HarnessObservationDelta {
- var facts = extraFacts
- if let observation {
- facts.merge([
- "localApp.appIsRunning": String(observation.appIsRunning),
- "localApp.appIsFocused": String(observation.appIsFocused),
- "localApp.observationConfidence": String(format: "%.3f", observation.confidence)
- ]) { current, _ in current }
- for (key, value) in observation.metadata {
- facts["localApp.observation.\(key)"] = value
- }
- }
- if let definition {
- facts["localApp.targetApp"] = definition.targetApp.appName
- facts["localApp.taskType"] = definition.taskType
- }
- let elements = observation?.availableControls.map { key, value in
- HarnessWorldElement(
- id: key,
- label: key,
- role: "control",
- isActionEligible: value,
- actions: value ? ["focus", "setValue"] : [],
- metadata: ["source": "localAppObservation"]
- )
- }
- .sorted { $0.id < $1.id } ?? []
- return HarnessObservationDelta(
- focusedApp: observation?.appIsFocused == true ? definition?.targetApp.appName : nil,
- visibleText: observation?.visibleText ?? [:],
- elements: elements,
- facts: facts,
- uncertainty: uncertainty
- )
- }
-
- private func unresolvedToolResult(_ context: HarnessToolExecutionContext) -> HarnessToolResult {
- let status: HarnessToolResultStatus
- let question: String?
- switch resolution.status {
- case .resolved:
- status = .failed
- question = nil
- case .needsConfirmation:
- status = .waitingForUser
- question = resolution.metadata["assistantResponse"] ?? "What detail should I use?"
- case .unsupportedCommand:
- status = .waitingForUser
- question = "What local app task should I run?"
- case .appUnavailable:
- status = .failed
- question = nil
- }
- return HarnessToolResult(
- callID: context.call.id,
- toolName: context.call.name,
- status: status,
- summary: "Local app task resolution is \(resolution.status.rawValue).",
- observations: HarnessObservationDelta(
- facts: [
- "localApp.status": self.status(for: resolution.status).rawValue,
- "localApp.resolutionStatus": resolution.status.rawValue,
- "localApp.reason": resolution.metadata["reason"] ?? resolution.status.rawValue
- ],
- uncertainty: [resolution.status.rawValue]
- ),
- question: question,
- metadata: [
- "executor": "LocalAppHarnessStepExecutor",
- "reason": resolution.metadata["reason"] ?? resolution.status.rawValue,
- "traceID": traceID
- ]
- )
- }
-
- private func makeResult(status: LocalAppTaskLiveRunStatus, reason: String) -> LocalAppTaskLiveRunResult {
- var metadata = baseMetadata.merging([
- "reason": reason,
- "latency.totalMS": Self.formatLatency(Self.uptimeMilliseconds() - runStartedAt),
- "executedCommandCount": String(actionTraces.filter(\.executed).count),
- "skippedNoLiveInputCommandCount": String(actionTraces.filter { $0.decision == .skippedNoLiveInput }.count)
- ]) { current, _ in current }
- metadata.merge(actionTraceMetadata()) { current, _ in current }
- metadata.merge(latestFailureFacts) { current, _ in current }
- if let verificationStep = finalActionPlan?.steps.first(where: { $0.role == .verifyResult }) {
- metadata["verification.summary"] = verificationStep.summary
- metadata["verification.status"] = verificationStep.status.rawValue
- for (key, value) in verificationStep.metadata {
- metadata["verification.\(key)"] = value
- }
- }
- return LocalAppTaskLiveRunResult(
- command: command,
- traceID: traceID,
- status: status,
- resolution: resolution,
- initialActionPlan: initialActionPlan,
- finalActionPlan: finalActionPlan,
- observation: latestObservation,
- actionTraces: actionTraces,
- metadata: metadata
- )
- }
-
- private func publishRunStartIfNeeded(
- definition: LocalAppTaskDefinition,
- intent: TaskIntent
- ) async {
- guard !runStarted else { return }
- runStarted = true
- await coordinator?.setTraceID(traceID)
- _ = await coordinator?.start(
- RunSession(
- userGoal: command,
- targetID: LocalAppTaskAdapter(definition: definition).targetID,
- runtimeProfile: "local-app-harness-step-loop",
- permissionPolicy: permissionPolicy
- )
- )
- await coordinator?.recordToolEvent(
- capability: .model,
- decision: .allow,
- toolName: "generic-harness-local-app-plan",
- summary: "Local app task plan entered guarded step loop",
- traceID: traceID,
- metadata: [
- "intentID": intent.intentID,
- "taskType": intent.taskType,
- "targetApp": definition.targetApp.appName
- ]
- )
- }
-
- private func status(for resolutionStatus: LocalAppTaskCatalogResolutionStatus) -> LocalAppTaskLiveRunStatus {
- switch resolutionStatus {
- case .resolved:
- return .failedSafe
- case .needsConfirmation:
- return .needsConfirmation
- case .unsupportedCommand:
- return .unsupportedCommand
- case .appUnavailable:
- return .appUnavailable
- }
- }
-
- private func status(for terminalState: LocalAppTaskTerminalState) -> LocalAppTaskLiveRunStatus {
- switch terminalState {
- case .completed:
- return .completed
- case .needsUserReview:
- return .needsUserReview
- case .failedSafe, .timedOut:
- return .failedSafe
- }
- }
-
- private func role(for tool: LocalAppActionPlanTool) -> String {
- switch tool {
- case .newDocument, .clickTarget, .pressReturn:
- return LocalAppTaskStepRole.submit.rawValue
- case .focusSearch, .focusAddressBar, .focusTextEntry:
- return LocalAppTaskStepRole.focusControl.rawValue
- case .setText:
- return LocalAppTaskStepRole.enterText.rawValue
- case .openOrFocusApp:
- return LocalAppTaskStepRole.launchOrFocusApp.rawValue
- case .observeApp:
- return LocalAppTaskStepRole.observeApp.rawValue
- case .verifyCommand, .verifyVisibleText:
- return LocalAppTaskStepRole.verifyResult.rawValue
- }
- }
-
- private func workflowStepID(from command: ActionEngineCommand) -> String? {
- command.metadata["workflowStepID"] ?? command.metadata["workflowStepRole"]
- }
-
- private func decisionReason(_ decision: ActionEngineCommandDecision) -> String {
- switch decision {
- case .skippedNoLiveInput:
- return "skippedNoLiveInput"
- case .executedLive:
- return "executedLive"
- case .denied(let reason):
- return reason
- }
- }
-
- private func actionTraceMetadata() -> [String: String] {
- guard !actionTraces.isEmpty else { return [:] }
- let lastTrace = actionTraces[actionTraces.count - 1]
- let backends = Set(actionTraces.compactMap { $0.metadata["liveInputBackend"] }).sorted()
- return [
- "action.traceCount": String(actionTraces.count),
- "action.executedCount": String(actionTraces.filter(\.executed).count),
- "action.backends": backends.joined(separator: ","),
- "action.lastCommandID": lastTrace.command.id,
- "action.lastCommandKind": lastTrace.command.kind.rawValue,
- "action.lastDecision": decisionReason(lastTrace.decision),
- "action.lastBackend": lastTrace.metadata["liveInputBackend"] ?? "",
- "action.overlayPointer": backends.contains("mac-apple-script") ? "fallbackOnly" : "visualOnly"
- ]
- }
-
- private static func slug(_ value: String) -> String {
- LocalAppTextNormalizer.normalizedPhrase(value)
- .split(separator: " ")
- .joined(separator: "-")
- }
-
- private static func descriptor(
- _ tool: LocalAppActionPlanTool,
- summary: String,
- input: [String: String] = [:],
- output: [String: String] = [:],
- permissions: [HarnessPermission],
- safety: HarnessToolSafetyClass
- ) -> HarnessToolDescriptor {
- HarnessToolDescriptor(
- name: tool.rawValue,
- pluginID: "user-query.local-app",
- summary: summary,
- inputSchema: input,
- outputSchema: output,
- requiredPermissions: permissions,
- safetyClass: safety,
- requiredContext: ["structured intent", "resolved local app task", "generic harness task"],
- verificationHints: ["Observe after the step and verify with concrete local-app evidence."],
- metadata: ["executor": "LocalAppHarnessStepExecutor"]
- )
- }
-
- private static func trimmed(_ value: String?) -> String? {
- let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
- return trimmed.isEmpty ? nil : trimmed
- }
-
- private static func now(advancedByMilliseconds milliseconds: Double = 0) -> RunTraceTimestamp {
- let now = ProcessInfo.processInfo.systemUptime
- return RunTraceTimestamp(
- wallClock: Date().addingTimeInterval(milliseconds / 1_000),
- monotonicUptimeNanoseconds: UInt64((now * 1_000_000_000) + (milliseconds * 1_000_000))
- )
- }
-
- private static func uptimeMilliseconds() -> Double {
- ProcessInfo.processInfo.systemUptime * 1_000
- }
-
- private static func formatLatency(_ milliseconds: Double) -> String {
- String(format: "%.3f", max(0, milliseconds))
- }
-
-}
-
-private extension ActionEngineCommand {
- func withHarnessIssuedAt(_ issuedAt: RunTraceTimestamp) -> ActionEngineCommand {
- var command = self
- command.issuedAt = issuedAt
- return command
- }
-}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
index d33cb11e..a3551fff 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
@@ -789,551 +789,6 @@ public struct LocalAppTaskCatalogResolution: Equatable, Sendable {
}
}
-public struct LocalAppTaskCatalog: Sendable {
- public var taskDefinitions: [LocalAppTaskDefinition]
- public var availabilityProvider: any LocalAppAvailabilityProviding
-
- public init(
- taskDefinitions: [LocalAppTaskDefinition],
- availabilityProvider: any LocalAppAvailabilityProviding = MacLocalAppAvailabilityProvider()
- ) {
- self.taskDefinitions = taskDefinitions
- self.availabilityProvider = availabilityProvider
- }
-
- public func resolve(command _: String) -> LocalAppTaskCatalogResolution {
- LocalAppTaskCatalogResolution(
- status: .unsupportedCommand,
- metadata: ["reason": "modelIntentRequired"]
- )
- }
-
- public func resolve(intent: TaskIntent) -> LocalAppTaskCatalogResolution {
- if intent.confidence < Self.minimumModelIntentConfidence {
- var metadata = [
- "reason": "lowConfidenceIntent",
- "taskType": intent.taskType,
- "targetApp": intent.targetApp.appName,
- "intentConfidence": String(intent.confidence)
- ]
- for key in [
- "responseMode",
- "assistantResponse",
- "missingEntity",
- "notActionableReason"
- ] {
- if let value = intent.metadata[key], !value.isEmpty {
- metadata[key] = value
- }
- }
- return LocalAppTaskCatalogResolution(
- status: .needsConfirmation,
- intent: intent,
- metadata: metadata
- )
- }
-
- if intent.taskType == Self.genericAppOpenTaskType {
- return resolveGenericAppOpen(intent: intent)
- }
- if intent.taskType == Self.genericLocalAppInteractionTaskType {
- return resolveGenericLocalAppInteraction(intent: intent)
- }
-
- guard let definition = taskDefinitions.first(where: { supports(intent: intent, definition: $0) }) else {
- return LocalAppTaskCatalogResolution(
- status: .unsupportedCommand,
- intent: intent,
- metadata: ["reason": "parsedIntentDefinitionMissing"]
- )
- }
-
- if intent.needsConfirmation {
- // Donkey is an act-first Mac agent: it doesn't over-confirm safe, reversible actions.
- // But when the planner explicitly asked to confirm (needsConfirmation=true), the default
- // is to HONOR that — we only proceed without confirming when the planner ALSO explicitly
- // classified the action as low-risk and non-dangerous. Absent risk metadata (e.g. a
- // non-hosted parser), medium/high risk, dangerous ambiguity, or a missing required detail
- // all keep the confirmation hard-stop, rather than silently bypassing it.
- // riskLevel ∈ {low, medium, high}; ambiguityClass ∈ {safe, recoverable, dangerous}.
- // A non-hosted parser leaves both empty, which is (correctly) NOT low-risk → confirm.
- let riskLevel = intent.metadata["genericHarness.risk.level"]?.lowercased() ?? ""
- let ambiguityClass = intent.metadata["genericHarness.ambiguity.class"]?.lowercased() ?? ""
- let hasMissingEntity = !(intent.metadata["missingEntity"] ?? "").isEmpty
- let explicitlyLowRisk = riskLevel == "low" && ambiguityClass != "dangerous"
- let mustConfirm = hasMissingEntity || !explicitlyLowRisk
- if mustConfirm {
- return LocalAppTaskCatalogResolution(
- status: .needsConfirmation,
- intent: intent,
- definition: definition,
- metadata: ["reason": intent.metadata["missingEntity"] ?? "needsConfirmation"]
- )
- }
- }
-
- let availability = availabilityProvider.availability(for: definition.targetApp)
- guard availability.isInstalled else {
- return LocalAppTaskCatalogResolution(
- status: .appUnavailable,
- intent: intent,
- definition: definition,
- availability: availability,
- metadata: ["reason": "targetAppUnavailable"]
- )
- }
-
- return LocalAppTaskCatalogResolution(
- status: .resolved,
- intent: intent,
- definition: definition,
- availability: availability,
- metadata: [
- "taskType": definition.taskType,
- "targetApp": definition.targetApp.appName
- ]
- )
- }
-
- public func adapter(for definition: LocalAppTaskDefinition) -> LocalAppTaskAdapter {
- LocalAppTaskAdapter(definition: definition)
- }
-
- public func appFinderCatalogEntries() -> [LocalAppFinderCatalogEntry] {
- availabilityProvider.appFinderCatalogEntries()
- }
-
- private func supports(
- intent: TaskIntent,
- definition: LocalAppTaskDefinition
- ) -> Bool {
- intent.taskType == definition.taskType
- && intent.targetApp.appName == definition.targetApp.appName
- && intent.targetApp.bundleIdentifier == definition.targetApp.bundleIdentifier
- }
-
- private func resolveGenericAppOpen(intent: TaskIntent) -> LocalAppTaskCatalogResolution {
- let requestedAppName = intent.metadata["requestedItemName"]
- ?? intent.entities["appName"]
- ?? intent.targetApp.appName
- let cleanedRequestedAppName = LocalAppLookup.cleanedLookupName(requestedAppName)
- guard !cleanedRequestedAppName.isEmpty,
- cleanedRequestedAppName != LocalAppLookup.cleanedLookupName(Self.genericLocalItemTarget.appName)
- else {
- return LocalAppTaskCatalogResolution(
- status: .needsConfirmation,
- intent: intent,
- definition: Self.genericAppOpenDefinition(target: Self.genericLocalItemTarget),
- metadata: [
- "reason": "appName",
- "taskType": Self.genericAppOpenTaskType
- ]
- )
- }
- let availability = availabilityProvider.availability(namedLocalItem: cleanedRequestedAppName)
- let target = availability.target
- let definition = Self.genericAppOpenDefinition(target: target)
- var resolvedIntent = intent
- resolvedIntent.targetApp = target
- resolvedIntent.normalizedEntities["appName"] = target.appName
- resolvedIntent.metadata["bundleIdentifier"] = target.bundleIdentifier ?? ""
- resolvedIntent.metadata["targetApp"] = target.appName
- resolvedIntent.metadata["requestedItemName"] = cleanedRequestedAppName
-
- guard availability.isInstalled else {
- return LocalAppTaskCatalogResolution(
- status: .appUnavailable,
- intent: resolvedIntent,
- definition: definition,
- availability: availability,
- metadata: [
- "reason": "targetAppUnavailable",
- "taskType": definition.taskType,
- "targetApp": target.appName,
- "requestedItemName": cleanedRequestedAppName,
- "lookupProvider": availability.metadata["provider"] ?? "",
- "itemKind": availability.metadata["itemKind"] ?? target.metadata["localItem.kind"] ?? ""
- ]
- )
- }
-
- return LocalAppTaskCatalogResolution(
- status: .resolved,
- intent: resolvedIntent,
- definition: definition,
- availability: availability,
- metadata: [
- "taskType": definition.taskType,
- "targetApp": target.appName,
- "requestedItemName": cleanedRequestedAppName,
- "lookupProvider": availability.metadata["provider"] ?? "",
- "itemKind": availability.metadata["itemKind"] ?? target.metadata["localItem.kind"] ?? ""
- ]
- )
- }
-
- private func resolveGenericLocalAppInteraction(intent: TaskIntent) -> LocalAppTaskCatalogResolution {
- let requestedAppName = intent.metadata["requestedItemName"]
- ?? intent.normalizedEntities["appName"]
- ?? intent.entities["appName"]
- ?? intent.targetApp.appName
- let cleanedRequestedAppName = LocalAppLookup.cleanedLookupName(requestedAppName)
- guard !cleanedRequestedAppName.isEmpty,
- cleanedRequestedAppName != LocalAppLookup.cleanedLookupName(Self.genericLocalAppInteractionTarget.appName)
- else {
- return LocalAppTaskCatalogResolution(
- status: .needsConfirmation,
- intent: intent,
- definition: Self.genericLocalAppInteractionDefinition,
- metadata: [
- "reason": "appName",
- "taskType": Self.genericLocalAppInteractionTaskType
- ]
- )
- }
-
- let hasGenericExecutablePlan = Self.hasGenericExecutablePlan(intent.metadata)
- let availability = availabilityProvider.availability(namedApp: cleanedRequestedAppName)
- guard let plan = intent.actionPlan else {
- let definition = hasGenericExecutablePlan
- ? Self.genericLocalAppInteractionDefinition(
- target: availability.target,
- plan: LocalAppActionPlan(tools: [], inputEntity: "query", focusKey: "")
- )
- : Self.genericLocalAppInteractionDefinition
- return LocalAppTaskCatalogResolution(
- status: hasGenericExecutablePlan && availability.isInstalled
- ? .resolved
- : (hasGenericExecutablePlan ? .appUnavailable : .needsConfirmation),
- intent: intent,
- definition: definition,
- availability: hasGenericExecutablePlan ? availability : nil,
- metadata: [
- "reason": "missingActionPlan",
- "taskType": Self.genericLocalAppInteractionTaskType,
- "targetApp": cleanedRequestedAppName
- ]
- )
- }
- guard plan.isExecutable || hasGenericExecutablePlan else {
- return LocalAppTaskCatalogResolution(
- status: .needsConfirmation,
- intent: intent,
- definition: Self.genericLocalAppInteractionDefinition,
- metadata: [
- "reason": "invalidActionPlan",
- "taskType": Self.genericLocalAppInteractionTaskType,
- "targetApp": cleanedRequestedAppName,
- "plan.tools": plan.tools.map(\.rawValue).joined(separator: ",")
- ]
- )
- }
-
- let inputEntity = plan.inputEntity
- if plan.requiresTextInput,
- Self.entityValue(named: inputEntity, in: intent).isEmpty {
- return LocalAppTaskCatalogResolution(
- status: .needsConfirmation,
- intent: intent,
- definition: Self.genericLocalAppInteractionDefinition,
- metadata: [
- "reason": inputEntity,
- "taskType": Self.genericLocalAppInteractionTaskType,
- "targetApp": cleanedRequestedAppName
- ]
- )
- }
-
- let target = availability.target
- let definition = Self.genericLocalAppInteractionDefinition(
- target: target,
- plan: plan
- )
- var resolvedIntent = intent
- resolvedIntent.targetApp = target
- resolvedIntent.normalizedEntities["appName"] = target.appName
- resolvedIntent.metadata["bundleIdentifier"] = target.bundleIdentifier ?? ""
- resolvedIntent.metadata["targetApp"] = target.appName
- resolvedIntent.metadata["requestedItemName"] = cleanedRequestedAppName
-
- guard availability.isInstalled else {
- return LocalAppTaskCatalogResolution(
- status: .appUnavailable,
- intent: resolvedIntent,
- definition: definition,
- availability: availability,
- metadata: [
- "reason": "targetAppUnavailable",
- "taskType": definition.taskType,
- "targetApp": target.appName,
- "requestedItemName": cleanedRequestedAppName,
- "lookupProvider": availability.metadata["provider"] ?? "",
- "itemKind": availability.metadata["itemKind"] ?? target.metadata["localItem.kind"] ?? ""
- ]
- )
- }
-
- return LocalAppTaskCatalogResolution(
- status: .resolved,
- intent: resolvedIntent,
- definition: definition,
- availability: availability,
- metadata: [
- "taskType": definition.taskType,
- "targetApp": target.appName,
- "requestedItemName": cleanedRequestedAppName,
- "lookupProvider": availability.metadata["provider"] ?? "",
- "itemKind": availability.metadata["itemKind"] ?? target.metadata["localItem.kind"] ?? "",
- "plan.tools": plan.tools.map(\.rawValue).joined(separator: ",")
- ]
- )
- }
-
- private static func hasGenericExecutablePlan(_ metadata: [String: String]) -> Bool {
- guard let text = metadata["genericHarness.planStepsJSON"],
- let data = text.data(using: .utf8),
- let steps = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]]
- else {
- return false
- }
- return steps.contains { step in
- guard let toolName = step["toolName"] as? String else { return false }
- return toolName == "skill.script.execute"
- || toolName == "automation.applescript.execute"
- }
- }
-
- public static var genericLocalItemOpenDefinition: LocalAppTaskDefinition {
- genericAppOpenDefinition(target: genericLocalItemTarget)
- }
-
- public static var genericLocalAppInteractionDefinition: LocalAppTaskDefinition {
- genericLocalAppInteractionDefinition(
- target: genericLocalAppInteractionTarget,
- plan: .defaultSearchSubmitPlan
- )
- }
-
- public static func genericAppOpenDefinition(target: LocalAppTarget) -> LocalAppTaskDefinition {
- return LocalAppTaskDefinition(
- taskType: genericAppOpenTaskType,
- targetApp: target,
- triggerTerms: [],
- entityRules: [
- LocalAppTaskEntityRule(
- name: "appName",
- required: true,
- metadata: [
- "dynamicLookupEntity": "true",
- "description": "Requested local app, file, or folder name selected by the model"
- ]
- )
- ],
- workflowSteps: BuiltInLocalAppTaskDefinitions.commonWorkflowPrefix + [
- LocalAppTaskWorkflowStepDefinition(
- id: "verify-opened-app",
- role: .verifyResult,
- summary: "Verify the target app is visible or focused"
- )
- ],
- observationStrategies: [.accessibility, .windowMetadata],
- verificationEntityName: "appName",
- metadata: [
- "catalogEntry": "generic-app-open",
- "displayTitle": "open local item",
- "taskLabelTemplate": "Open {appName}",
- "verificationTextKey": "appName",
- "domain": "app",
- "dynamicTarget": target.metadata["dynamicTarget"] ?? "false",
- "localItem.kind": target.metadata["localItem.kind"] ?? "",
- "localItem.path": target.metadata["localItem.path"] ?? ""
- ]
- )
- }
-
- public static func genericLocalAppInteractionDefinition(
- target: LocalAppTarget,
- plan: LocalAppActionPlan
- ) -> LocalAppTaskDefinition {
- let inputEntity = plan.inputEntity
- var metadata: [String: String] = [
- "catalogEntry": "generic-local-app-interaction",
- "displayTitle": "local app interaction",
- "taskLabelTemplate": "Use {appName}",
- "verificationTextKey": inputEntity,
- "domain": "app",
- "dynamicTarget": target.metadata["dynamicTarget"] ?? "false",
- "modelPlanned": "true",
- "plan.tools": plan.tools.map(\.rawValue).joined(separator: ","),
- "plan.verificationTools": plan.verificationTools.map(\.rawValue).joined(separator: ","),
- "plan.inputEntity": inputEntity,
- "plan.allowedTools": LocalAppActionPlanTool.allCases.map(\.rawValue).joined(separator: ","),
- "plan.setTextInputContract": "inputEntityValueIsExactTextToEnter"
- ]
- metadata["verificationMode"] = plan.requiresVisibleTextVerification
- ? "visibleText"
- : "commandAttempted"
-
- return LocalAppTaskDefinition(
- taskType: genericLocalAppInteractionTaskType,
- targetApp: target,
- triggerTerms: [],
- entityRules: [
- LocalAppTaskEntityRule(
- name: "appName",
- required: true,
- metadata: [
- "dynamicLookupEntity": "true",
- "description": "Requested local app selected by the model"
- ]
- ),
- LocalAppTaskEntityRule(
- name: "goal",
- required: true,
- metadata: ["description": "Short model-selected action goal"]
- ),
- LocalAppTaskEntityRule(
- name: "query",
- required: false,
- metadata: ["description": "Text to enter when the model plan includes set_text"]
- )
- ],
- workflowSteps: Self.workflowSteps(for: plan),
- observationStrategies: [.accessibility, .windowMetadata, .screenshotForLocalModel],
- verificationEntityName: inputEntity,
- metadata: metadata
- )
- }
-
- private static func workflowSteps(
- for plan: LocalAppActionPlan
- ) -> [LocalAppTaskWorkflowStepDefinition] {
- var steps = BuiltInLocalAppTaskDefinitions.commonWorkflowPrefix
- var submitIndex = 1
- let inputEntity = plan.inputEntity
- for tool in plan.tools {
- switch tool {
- case .openOrFocusApp, .observeApp:
- continue
- case .newDocument:
- steps.append(LocalAppTaskWorkflowStepDefinition(
- id: "model-plan-new-document",
- role: .submit,
- summary: "Create a new document or note",
- metadata: [
- "key": "Command+N",
- "plan.tool": tool.rawValue
- ]
- ))
- case .focusSearch, .focusAddressBar, .focusTextEntry:
- var metadata = [
- "controlID": plan.controlID,
- "plan.tool": tool.rawValue
- ]
- if !plan.focusKey.isEmpty {
- metadata["key"] = plan.focusKey
- }
- steps.append(LocalAppTaskWorkflowStepDefinition(
- id: "model-plan-\(Self.toolSlug(tool.rawValue))",
- role: .focusControl,
- summary: "Focus the model-selected input control",
- metadata: metadata
- ))
- case .setText:
- steps.append(LocalAppTaskWorkflowStepDefinition(
- id: "model-plan-set-text",
- role: .enterText,
- summary: "Enter the model-selected text entity",
- metadata: [
- "controlID": plan.controlID,
- "entityName": inputEntity,
- "plan.tool": tool.rawValue
- ]
- ))
- case .clickTarget:
- steps.append(LocalAppTaskWorkflowStepDefinition(
- id: "model-plan-click-target-\(submitIndex)",
- role: .submit,
- summary: "Click the model-selected visual or Accessibility target",
- metadata: [
- "controlID": plan.controlID,
- "plan.tool": tool.rawValue
- ]
- ))
- submitIndex += 1
- case .pressReturn:
- steps.append(LocalAppTaskWorkflowStepDefinition(
- id: "model-plan-press-return-\(submitIndex)",
- role: .submit,
- summary: "Submit the model-planned action",
- metadata: [
- "key": "Return",
- "plan.tool": tool.rawValue
- ]
- ))
- submitIndex += 1
- case .verifyCommand, .verifyVisibleText:
- steps.append(LocalAppTaskWorkflowStepDefinition(
- id: "model-plan-\(Self.toolSlug(tool.rawValue))",
- role: .verifyResult,
- summary: "Verify the model-planned action",
- metadata: ["plan.tool": tool.rawValue]
- ))
- }
- }
- if steps.contains(where: { $0.role == .verifyResult }) == false {
- steps.append(LocalAppTaskWorkflowStepDefinition(
- id: "model-plan-verify",
- role: .verifyResult,
- summary: "Verify the model-planned action"
- ))
- }
- return steps
- }
-
- private static func toolSlug(_ value: String) -> String {
- value
- .split(whereSeparator: { !$0.isLetter && !$0.isNumber })
- .joined(separator: "-")
- .lowercased()
- }
-
- private static func entityValue(named entityName: String, in intent: TaskIntent) -> String {
- (intent.normalizedEntities[entityName] ?? intent.entities[entityName] ?? "")
- .trimmingCharacters(in: .whitespacesAndNewlines)
- }
-
- private func slug(_ value: String) -> String {
- LocalAppTextNormalizer.normalizedPhrase(value)
- .split(separator: " ")
- .joined(separator: "-")
- }
-
- private static let genericAppOpenTaskType = "app_open"
- private static let genericLocalAppInteractionTaskType = "local_app_interaction"
- private static let minimumModelIntentConfidence = 0.55
- private static var genericLocalItemTarget: LocalAppTarget {
- LocalAppTarget(
- appName: "Local Item",
- titleContains: nil,
- metadata: [
- "dynamicTarget": "true",
- "localItem.kind": "dynamic"
- ]
- )
- }
- private static var genericLocalAppInteractionTarget: LocalAppTarget {
- LocalAppTarget(
- appName: "Local App",
- titleContains: nil,
- metadata: [
- "dynamicTarget": "true",
- "localItem.kind": LocalItemKind.application.rawValue
- ]
- )
- }
-}
-
public enum BuiltInLocalAppTaskDefinitions {
public static var commonWorkflowPrefix: [LocalAppTaskWorkflowStepDefinition] {
[
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift
deleted file mode 100644
index 3820289c..00000000
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskDefinitionLoader.swift
+++ /dev/null
@@ -1,117 +0,0 @@
-import DonkeyContracts
-import Foundation
-
-public enum LocalAppTaskDefinitionLoaderError: Error, Equatable, Sendable {
- case unsupportedFileExtension(String)
- case unreadableDirectory(URL)
- case decodeFailed(URL, String)
-}
-
-public struct LocalAppTaskDefinitionLoader: Sendable {
- public var decoder: JSONDecoder
- public var memoryStore: SQLiteAgentMemoryStore?
-
- public init(
- decoder: JSONDecoder = JSONDecoder(),
- memoryStore: SQLiteAgentMemoryStore? = .shared
- ) {
- self.decoder = decoder
- self.memoryStore = memoryStore
- }
-
- public static var defaultDirectoryURL: URL {
- FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
- .appendingPathComponent("Donkey", isDirectory: true)
- .appendingPathComponent("TaskDefinitions", isDirectory: true)
- }
-
- public func load(from url: URL) throws -> [LocalAppTaskDefinition] {
- switch url.pathExtension.lowercased() {
- case "json":
- return try loadJSON(from: url)
- case "jsonl":
- return try loadJSONLines(from: url)
- default:
- throw LocalAppTaskDefinitionLoaderError.unsupportedFileExtension(url.pathExtension)
- }
- }
-
- public func loadDirectory(_ directoryURL: URL) throws -> [LocalAppTaskDefinition] {
- guard let fileURLs = FileManager.default.enumerator(
- at: directoryURL,
- includingPropertiesForKeys: [.isRegularFileKey],
- options: [.skipsHiddenFiles]
- ) else {
- throw LocalAppTaskDefinitionLoaderError.unreadableDirectory(directoryURL)
- }
-
- var definitions: [LocalAppTaskDefinition] = []
- for case let fileURL as URL in fileURLs {
- guard ["json", "jsonl"].contains(fileURL.pathExtension.lowercased()) else {
- continue
- }
- definitions.append(contentsOf: try load(from: fileURL))
- }
- return definitions
- }
-
- public func cachedDefinitions(from directoryURL: URL) throws -> [LocalAppTaskDefinition] {
- let definitions = try loadDirectory(directoryURL)
- memoryStore?.prewarmTaskDefinitions(definitions)
- return memoryStore?.taskDefinitions() ?? definitions
- }
-
- public func defaultDefinitions() -> [LocalAppTaskDefinition] {
- memoryStore?.prewarmTaskDefinitions(Self.runtimeSeedDefinitions)
- if let generatedDefinitions = try? loadDirectory(Self.defaultDirectoryURL) {
- memoryStore?.prewarmTaskDefinitions(generatedDefinitions)
- }
- return memoryStore?.taskDefinitions() ?? Self.runtimeSeedDefinitions
- }
-
- public static var runtimeSeedDefinitions: [LocalAppTaskDefinition] {
- [
- LocalAppTaskCatalog.genericLocalItemOpenDefinition,
- LocalAppTaskCatalog.genericLocalAppInteractionDefinition
- ]
- }
-
- private func loadJSON(from url: URL) throws -> [LocalAppTaskDefinition] {
- do {
- let data = try Data(contentsOf: url)
- if let array = try? decoder.decode([LocalAppTaskDefinition].self, from: data) {
- return array
- }
- return [try decoder.decode(LocalAppTaskDefinition.self, from: data)]
- } catch {
- throw LocalAppTaskDefinitionLoaderError.decodeFailed(url, String(describing: error))
- }
- }
-
- private func loadJSONLines(from url: URL) throws -> [LocalAppTaskDefinition] {
- do {
- let text = try String(contentsOf: url, encoding: .utf8)
- return try text
- .split(separator: "\n")
- .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
- .filter { !$0.isEmpty }
- .map { line in
- try decoder.decode(LocalAppTaskDefinition.self, from: Data(line.utf8))
- }
- } catch {
- throw LocalAppTaskDefinitionLoaderError.decodeFailed(url, String(describing: error))
- }
- }
-}
-
-public extension LocalAppTaskCatalog {
- static func defaultLocal(
- availabilityProvider: any LocalAppAvailabilityProviding = MacLocalAppAvailabilityProvider(),
- loader: LocalAppTaskDefinitionLoader = LocalAppTaskDefinitionLoader()
- ) -> LocalAppTaskCatalog {
- LocalAppTaskCatalog(
- taskDefinitions: loader.defaultDefinitions(),
- availabilityProvider: availabilityProvider
- )
- }
-}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift
deleted file mode 100644
index 33a7a732..00000000
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift
+++ /dev/null
@@ -1,246 +0,0 @@
-import DonkeyContracts
-import DonkeyRuntime
-import Testing
-
-@Suite
-struct AppHarnessTurnRouterTests {
- @Test
- func greetingDefersToModelIntentClassifierWithoutWordScanning() {
- let result = router().route(
- request: AppHarnessTurnRequest(
- turn: AppHarnessTurn(text: "hi there", source: .typedPrompt)
- ),
- traceID: "trace-chat"
- )
-
- #expect(result.outcome.decision.kind == .runLocalTask)
- #expect(result.outcome.decision.traceID == "trace-chat")
- #expect(result.outcome.metadata["router"] == "modelIntent")
- #expect(result.outcome.resolution == nil)
- #expect(result.outcome.assistantResponse == nil)
- }
-
- @Test
- func arithmeticQuestionAlsoDefersToModelIntentRouting() {
- let result = router().route(
- request: AppHarnessTurnRequest(
- turn: AppHarnessTurn(text: "What is 2+2?", source: .typedPrompt)
- ),
- traceID: "trace-math"
- )
-
- #expect(result.outcome.decision.kind == .runLocalTask)
- #expect(result.outcome.metadata["router"] == "modelIntent")
- #expect(result.outcome.resolution == nil)
- #expect(result.outcome.assistantResponse == nil)
- }
-
- @Test
- func openMusicDefersToModelIntentRouting() {
- let result = router().route(
- request: AppHarnessTurnRequest(
- turn: AppHarnessTurn(text: "open music", source: .typedPrompt)
- ),
- traceID: "trace-open-music"
- )
-
- #expect(result.outcome.decision.kind == .runLocalTask)
- #expect(result.outcome.metadata["router"] == "modelIntent")
- #expect(result.outcome.resolution == nil)
- }
-
- @Test
- func missingAppOpenDefersToModelIntentRouting() {
- let result = router().route(
- request: AppHarnessTurnRequest(
- turn: AppHarnessTurn(text: "open Imaginary App", source: .typedPrompt)
- ),
- traceID: "trace-missing-app"
- )
-
- #expect(result.outcome.decision.kind == .runLocalTask)
- #expect(result.outcome.metadata["router"] == "modelIntent")
- #expect(result.outcome.resolution == nil)
- }
-
- @Test
- func actionableWeatherRequestDefersToModelIntentRouting() {
- let result = router().route(
- request: AppHarnessTurnRequest(
- turn: AppHarnessTurn(text: "show me the weather for SF", source: .typedPrompt)
- ),
- traceID: "trace-action"
- )
-
- #expect(result.outcome.decision.kind == .runLocalTask)
- #expect(result.outcome.metadata["router"] == "modelIntent")
- #expect(result.outcome.resolution == nil)
- }
-
- @Test
- func voiceTranscriptRoutesThroughSameHarnessPathAsTypedText() {
- let result = router().route(
- request: AppHarnessTurnRequest(
- turn: AppHarnessTurn(text: "show me the weather for SF", source: .voiceTranscript)
- ),
- traceID: "trace-voice-action"
- )
-
- #expect(result.contextPacket.currentTurn.source == .voiceTranscript)
- #expect(result.outcome.decision.kind == .runLocalTask)
- #expect(result.outcome.metadata["router"] == "modelIntent")
- #expect(result.outcome.resolution == nil)
- }
-
- @Test
- func ambiguousWeatherRequestAlsoRequiresModelIntent() {
- let result = router().route(
- request: AppHarnessTurnRequest(
- turn: AppHarnessTurn(text: "show weather", source: .typedPrompt)
- ),
- traceID: "trace-clarify"
- )
-
- #expect(result.outcome.decision.kind == .runLocalTask)
- #expect(result.outcome.metadata["router"] == "modelIntent")
- #expect(result.outcome.resolution == nil)
- }
-
- @Test
- func followUpTurnKeepsRecentThreadContextBoundedAndRedacted() {
- let limits = AppHarnessContextPacketLimits(
- maxRecentEvents: 2,
- maxAssets: 1,
- maxEventTextCharacters: 64,
- maxAssetNameCharacters: 32,
- maxPromptCharacters: 420
- )
- let result = router(limits: limits).route(
- request: AppHarnessTurnRequest(
- turn: AppHarnessTurn(
- text: "use token=secret123 and [email protected]",
- source: .followUp,
- taskID: "task-1",
- isFollowUp: true
- ),
- recentEvents: [
- UserQueryTaskEvent(
- id: "event-1",
- taskID: "task-1",
- role: .user,
- text: "older event should be excluded",
- sequence: 0
- ),
- UserQueryTaskEvent(
- id: "event-2",
- taskID: "task-1",
- role: .assistant,
- text: "contact me at [email protected]",
- sequence: 1
- ),
- UserQueryTaskEvent(
- id: "event-3",
- taskID: "task-1",
- role: .user,
- text: String(repeating: "long ", count: 80),
- sequence: 2
- )
- ],
- assets: [
- UserQueryTaskAsset(
- id: "asset-1",
- taskID: "task-1",
- source: .userUploaded,
- displayName: "old.pdf",
- contentType: "application/pdf",
- urlString: "file:///tmp/old.pdf"
- ),
- UserQueryTaskAsset(
- id: "asset-2",
- taskID: "task-1",
- source: .userUploaded,
- displayName: "current-document-with-a-very-long-name.pdf",
- contentType: "application/pdf",
- urlString: "file:///tmp/current.pdf"
- )
- ]
- ),
- traceID: "trace-context"
- )
-
- #expect(result.contextPacket.recentEvents.count == 2)
- #expect(result.contextPacket.assets.count == 1)
- #expect(result.contextPacket.promptText.count <= 423)
- #expect(!result.contextPacket.promptText.contains("[email protected]"))
- #expect(!result.contextPacket.promptText.contains("[email protected]"))
- #expect(!result.contextPacket.promptText.contains("secret123"))
- #expect(result.contextPacket.promptText.contains("[redacted-email]"))
- #expect(result.contextPacket.promptText.contains("[redacted-secret]"))
- #expect(result.contextPacket.redactionCount == 3)
- #expect(result.contextPacket.compactionRecords.contains {
- $0.itemKind == .recentEvent && $0.originalCount == 3 && $0.includedCount == 2
- })
- }
-
- @Test
- func contextCompactionDoesNotInferTransientCorrectionsFromText() {
- let limits = AppHarnessContextPacketLimits(
- maxRecentEvents: 2,
- maxAssets: 0,
- maxPromptCharacters: 600
- )
- let result = router(limits: limits).route(
- request: AppHarnessTurnRequest(
- turn: AppHarnessTurn(text: "thanks", source: .typedPrompt),
- recentEvents: [
- UserQueryTaskEvent(
- id: "event-1",
- taskID: "task-1",
- role: .assistant,
- text: "Retry nudge: invalid output, try again.",
- sequence: 1
- ),
- UserQueryTaskEvent(
- id: "event-2",
- taskID: "task-1",
- role: .user,
- text: "show me the weather for SF",
- sequence: 2
- ),
- UserQueryTaskEvent(
- id: "event-3",
- taskID: "task-1",
- role: .assistant,
- text: "Opening Weather for San Francisco.",
- sequence: 3
- )
- ]
- ),
- traceID: "trace-typed-compaction"
- )
-
- #expect(result.contextPacket.recentEvents.map(\.sequence) == [2, 3])
- #expect(result.contextPacket.metadata["events.droppedTransientCorrectionCount"] == "0")
- #expect(result.contextPacket.compactionRecords.contains {
- $0.itemKind == .transientCorrection && $0.droppedCount == 0
- })
- }
-
- private func router(
- limits: AppHarnessContextPacketLimits = AppHarnessContextPacketLimits()
- ) -> AppHarnessTurnRouter {
- AppHarnessTurnRouter(
- catalog: LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,
- availabilityProvider: StaticLocalAppAvailabilityProvider(
- installedBundleIdentifiers: [
- "com.apple.weather",
- "com.apple.Music",
- "com.adobe.Reader"
- ]
- )
- ),
- contextBuilder: AppHarnessContextPacketBuilder(limits: limits)
- )
- }
-}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
index 0ab0e677..c020cbf9 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
@@ -1384,7 +1384,7 @@ struct GenericHarnessTests {
request: request,
pointerTask: task,
traceID: "trace-1",
- availableToolNames: AppHarnessGenericLifecycleToolNames.localAppTools,
+ availableToolNames: ["screen.observe", "elements.get"],
grantedPermissions: [.verification]
)
@@ -1392,203 +1392,13 @@ struct GenericHarnessTests {
#expect(prepared.thread.activeTaskIDs == [task.id])
#expect(prepared.task.id == task.id)
#expect(prepared.task.context.turn?.id == "turn-1")
- #expect(prepared.task.context.availableToolNames == AppHarnessGenericLifecycleToolNames.localAppTools)
+ #expect(prepared.task.context.availableToolNames == ["screen.observe", "elements.get"])
#expect(prepared.task.grantedPermissions == [.verification])
#expect(prepared.compactedContext.events.map(\.id) == ["event-1"])
#expect(prepared.compactedContext.assets.map(\.id) == ["asset-1"])
#expect(prepared.compactedContext.promptText.contains("Current turn: open calendar"))
}
- @Test
- func userQueryLifecyclePlansLocalAppStepAndStopsForExecutorUserGate() async {
- let store = InMemoryHarnessThreadStore()
- let coordinator = HarnessTaskCoordinator()
- let lifecycle = AppHarnessGenericLifecycle(threadStore: store, coordinator: coordinator)
- let task = await coordinator.createTask(
- id: "pointer-task-gate",
- threadID: "thread-gate",
- goal: "send a message",
- grantedPermissions: [.verification]
- )
- let intent = TaskIntent(
- intentID: "intent-1",
- taskType: "local_app_interaction",
- targetApp: LocalAppTarget(appName: "Messages"),
- entities: ["recipient": "Alex"],
- normalizedEntities: ["recipient": "Alex"],
- confidence: 0.8,
- parserSource: .onlineModel,
- metadata: [
- "genericHarness.planStepsJSON": """
- [{"id":"enter-message","summary":"Enter the message.","toolName":"ui.setText","inputEntity":"message","controlID":"editor","focusKey":"","expectedObservation":"Message is entered."}]
- """
- ]
- )
- let resolution = LocalAppTaskCatalogResolution(
- status: .needsConfirmation,
- intent: intent,
- metadata: ["reason": "missing message"]
- )
- _ = await lifecycle.planLocalTaskRun(
- taskID: task.id,
- resolution: resolution,
- fallbackGoal: "send a message",
- traceID: "trace-gate"
- )
- let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()
- await registry.register(
- HarnessTool(
- descriptor: LocalAppHarnessStepExecutor.descriptors.first {
- $0.name == LocalAppActionPlanTool.setText.rawValue
- }!
- ) { context in
- HarnessToolResult(
- callID: context.call.id,
- toolName: context.call.name,
- status: .waitingForUser,
- summary: "Need the message text.",
- question: "What should I send?"
- )
- }
- )
- let runtime = GenericHarnessRuntime(
- coordinator: coordinator,
- registry: registry
- )
-
- let result = await runtime.executeNextPlannedStep(taskID: task.id)
-
- #expect(result?.stoppedForGate == true)
- #expect(result?.task.status == .waitingForUser)
- #expect(result?.task.pendingContinuation?.question == "What should I send?")
- #expect(result?.task.pendingContinuation?.pendingToolCall?.name == LocalAppActionPlanTool.setText.rawValue)
- #expect(result?.toolResult?.status == .waitingForUser)
- }
-
- @Test
- func userQueryLifecyclePlansGenericSkillToolSteps() async throws {
- let store = InMemoryHarnessThreadStore()
- let coordinator = HarnessTaskCoordinator()
- let lifecycle = AppHarnessGenericLifecycle(threadStore: store, coordinator: coordinator)
- let task = await coordinator.createTask(
- id: "skill-task",
- threadID: "skill-thread",
- goal: "play media"
- )
- let intent = TaskIntent(
- intentID: "intent-skill-music",
- taskType: "local_app_interaction",
- targetApp: LocalAppTarget(appName: "Music"),
- entities: [
- "appName": "Music",
- "goal": "play media",
- "query": "Yellow Coldplay"
- ],
- normalizedEntities: [
- "appName": "Music",
- "goal": "play media",
- "query": "Yellow Coldplay"
- ],
- confidence: 0.9,
- parserSource: .onlineModel,
- actionPlan: LocalAppActionPlan(tools: [], inputEntity: "query", focusKey: ""),
- metadata: [
- "genericHarness.schemaVersion": "generic_harness_planning",
- "genericHarness.planStepsJSON": """
- [{"id":"load-music-skill","summary":"Load the media skill.","toolName":"skill.load","inputEntity":"","controlID":"","focusKey":"","toolInputs":{"skillID":"music-media"},"expectedObservation":"Skill loaded."},{"id":"play-media","summary":"Run the validated script.","toolName":"skill.script.execute","inputEntity":"query","controlID":"","focusKey":"","toolInputs":{"skillID":"music-media","scriptID":"scripts-play-media-by-search"},"expectedObservation":"status=played"}]
- """,
- "genericHarness.verificationCriteriaJSON": #"["status=played"]"#,
- "genericHarness.fallbacksJSON": #"["Ask for a different query."]"#
- ]
- )
- let resolution = LocalAppTaskCatalogResolution(
- status: .resolved,
- intent: intent,
- definition: LocalAppTaskCatalog.genericLocalAppInteractionDefinition(
- target: LocalAppTarget(appName: "Music", bundleIdentifier: "com.apple.Music"),
- plan: LocalAppActionPlan(tools: [], inputEntity: "query", focusKey: "")
- )
- )
-
- let planned = await lifecycle.planLocalTaskRun(
- taskID: task.id,
- resolution: resolution,
- fallbackGoal: "play music",
- traceID: "trace-skill-plan",
- availableToolNames: ["skill.load", "skill.script.execute"]
- )
-
- let steps = try #require(planned?.plan?.steps)
- let calls = steps.compactMap(\.toolCall)
- #expect(calls.map(\.name) == ["skill.load", "skill.script.execute"])
- #expect(calls[0].input["skillID"] == "music-media")
- #expect(calls[1].input["scriptID"] == "scripts-play-media-by-search")
- #expect(calls[1].input["input"] == "Yellow Coldplay")
- }
-
- @Test
- func userQueryLifecycleUsesHostedGenericPlanningMetadata() async {
- let store = InMemoryHarnessThreadStore()
- let coordinator = HarnessTaskCoordinator()
- let lifecycle = AppHarnessGenericLifecycle(threadStore: store, coordinator: coordinator)
- let task = await coordinator.createTask(
- id: "pointer-task-hosted-plan",
- threadID: "thread-hosted-plan",
- goal: "open a site"
- )
- let intent = TaskIntent(
- intentID: "intent-hosted-plan",
- taskType: "local_app_interaction",
- targetApp: LocalAppTarget(appName: "Safari"),
- entities: ["query": "https://example.org"],
- normalizedEntities: ["query": "https://example.org"],
- confidence: 0.92,
- parserSource: .onlineModel,
- metadata: [
- "genericHarness.schemaVersion": "generic_harness_planning",
- "genericHarness.intent.goal": "open example.org in Safari",
- "genericHarness.ambiguity.class": "safe",
- "genericHarness.risk.level": "low",
- "genericHarness.shouldAskBeforeActing": "false",
- "genericHarness.missingInformationJSON": "[]",
- "genericHarness.planStepsJSON": """
- [{"controlID":"addressBar","expectedObservation":"Address bar is focused.","focusKey":"Command+L","id":"focus-address","inputEntity":"","summary":"Focus the browser address bar.","toolName":"ui.focusAddressBar"},{"controlID":"addressBar","expectedObservation":"Requested URL is entered.","focusKey":"","id":"enter-url","inputEntity":"query","summary":"Enter the requested URL.","toolName":"ui.setText"}]
- """,
- "genericHarness.verificationCriteriaJSON": #"["The requested website navigation is attempted."]"#,
- "genericHarness.fallbacksJSON": #"["Ask before navigating if the URL is ambiguous."]"#,
- "genericHarness.clarification.questionsJSON": #"["Which URL should I open?"]"#,
- "genericHarness.clarification.policy": "Ask only if the requested URL is missing."
- ]
- )
- let resolution = LocalAppTaskCatalogResolution(
- status: .resolved,
- intent: intent
- )
-
- _ = await lifecycle.planLocalTaskRun(
- taskID: task.id,
- resolution: resolution,
- fallbackGoal: "open a site",
- traceID: "trace-hosted-plan"
- )
- let planned = await coordinator.task(id: task.id)
-
- #expect(planned?.intent?.goal == "open example.org in Safari")
- #expect(planned?.intent?.riskLevel == .low)
- #expect(planned?.plan?.steps.first?.id == "model-focus-address")
- #expect(planned?.plan?.steps.first?.toolCall?.name == LocalAppActionPlanTool.focusAddressBar.rawValue)
- #expect(planned?.plan?.steps.first?.metadata["toolName"] == "ui.focusAddressBar")
- #expect(planned?.plan?.steps.contains { $0.id == "run-local-app-task" } == false)
- #expect(planned?.plan?.successCriteria == ["The requested website navigation is attempted."])
- #expect(planned?.plan?.fallbackPolicy == ["Ask before navigating if the URL is ambiguous."])
- #expect(planned?.plan?.clarificationPolicy == [
- "Which URL should I open?",
- "Ask only if the requested URL is missing."
- ])
- #expect(planned?.plan?.metadata["modelPlan.schemaVersion"] == "generic_harness_planning")
- #expect(planned?.plan?.metadata["modelPlan.stepCount"] == "2")
- }
-
@Test
func userQueryLifecycleConsumesPendingContinuationOnFollowUpTurn() async {
let store = InMemoryHarnessThreadStore()
@@ -1628,7 +1438,7 @@ struct GenericHarnessTests {
request: request,
pointerTask: pointerTask,
traceID: "trace-answer",
- availableToolNames: AppHarnessGenericLifecycleToolNames.localAppTools
+ availableToolNames: ["screen.observe", "elements.get"]
)
#expect(prepared.task.status == .resuming)
@@ -1694,35 +1504,6 @@ struct GenericHarnessTests {
#expect(reloaded?.grantedPermissions == [.accessibility, .input])
}
- @Test
- func userQueryLifecyclePlansRecoveryAsGenericToolStep() async {
- let store = InMemoryHarnessThreadStore()
- let coordinator = HarnessTaskCoordinator()
- let lifecycle = AppHarnessGenericLifecycle(threadStore: store, coordinator: coordinator)
- let task = await coordinator.createTask(
- id: "pointer-task-recover",
- threadID: "thread-recover",
- goal: "open an app",
- grantedPermissions: [.lifecycle]
- )
- _ = await lifecycle.planRecovery(
- taskID: task.id,
- reason: "App not found",
- traceID: "trace-recover"
- )
- let runtime = GenericHarnessRuntime(
- coordinator: coordinator,
- registry: BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()
- )
-
- let result = await runtime.executeNextPlannedStep(taskID: task.id)
-
- #expect(result?.toolResult?.toolName == "run.recover")
- #expect(result?.toolResult?.status == .succeeded)
- #expect(result?.task.toolHistory.map(\.call.name) == ["run.recover"])
- #expect(result?.task.plan?.metadata["planner"] == "genericHarnessUserQueryRecovery")
- }
-
@Test
func threadStorePersistsThreadsEventsAndAssetsByThreadID() async {
let store = InMemoryHarnessThreadStore()
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
index 49e92550..88d01f63 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalAppTaskTests.swift
@@ -21,74 +21,6 @@ struct LocalAppTaskTests {
#expect(intent.metadata["catalogEntry"] == "built-in-weather-lookup")
}
- @Test
- func catalogResolvesGenericAppOpenIntentFromModelSelectedLocalItem() throws {
- let catalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,
- availabilityProvider: StaticLocalAppAvailabilityProvider(
- installedBundleIdentifiers: ["com.figma.Desktop"],
- installedApplicationNames: ["Figma": "com.figma.Desktop"],
- installedLocalItemNames: ["Quarterly Plan.pdf": "file"]
- )
- )
- let resolution = catalog.resolve(intent: TaskIntent(
- intentID: "app_open-figma",
- taskType: "app_open",
- targetApp: LocalAppTarget(appName: "Local Item", metadata: ["dynamicTarget": "true"]),
- entities: ["appName": "figma"],
- normalizedEntities: ["appName": "Figma"],
- confidence: 0.91,
- parserSource: .localModel,
- metadata: ["requestedItemName": "figma"]
- ))
- let intent = try #require(resolution.intent)
-
- #expect(resolution.status == .resolved)
- #expect(intent.taskType == "app_open")
- #expect(intent.targetApp.appName == "Figma")
- #expect(intent.targetApp.bundleIdentifier == "com.figma.Desktop")
- #expect(intent.normalizedEntities["appName"] == "Figma")
- #expect(intent.metadata["catalogEntry"] == "generic-app-open")
-
- let fileResolution = catalog.resolve(intent: TaskIntent(
- intentID: "app_open-quarterly-plan",
- taskType: "app_open",
- targetApp: LocalAppTarget(appName: "Local Item", metadata: ["dynamicTarget": "true"]),
- entities: ["appName": "quarterly plan.pdf"],
- normalizedEntities: ["appName": "Quarterly Plan.pdf"],
- confidence: 0.88,
- parserSource: .localModel,
- metadata: ["requestedItemName": "quarterly plan.pdf"]
- ))
- #expect(fileResolution.status == .resolved)
- let fileDefinition = try #require(fileResolution.definition)
- #expect(LocalAppTaskVerificationPolicy.mode(for: fileDefinition) == .openedLocalItem)
- #expect(fileResolution.metadata["itemKind"] == "file")
- }
-
- @Test
- func lowConfidenceModelIntentAsksForConfirmationBeforeLookupExecution() {
- let catalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,
- availabilityProvider: StaticLocalAppAvailabilityProvider(
- installedBundleIdentifiers: ["com.figma.Desktop"],
- installedApplicationNames: ["Figma": "com.figma.Desktop"]
- )
- )
- let resolution = catalog.resolve(intent: TaskIntent(
- intentID: "app_open-uncertain",
- taskType: "app_open",
- targetApp: LocalAppTarget(appName: "Local Item", metadata: ["dynamicTarget": "true"]),
- entities: ["appName": "figma"],
- normalizedEntities: ["appName": "Figma"],
- confidence: 0.4,
- parserSource: .localModel
- ))
-
- #expect(resolution.status == .needsConfirmation)
- #expect(resolution.metadata["reason"] == "lowConfidenceIntent")
- }
-
@Test
func structuredDocumentFormFillIntentBuildsReviewOnlyTask() throws {
let intent = documentFormFillIntent()
@@ -116,14 +48,6 @@ struct LocalAppTaskTests {
#expect(intent.metadata["missingEntity"] == "city")
}
- @Test
- func catalogResolveCommandDoesNotParseWordsFromUserText() {
- let resolution = catalog().resolve(command: "open my calendar")
-
- #expect(resolution.status == .unsupportedCommand)
- #expect(resolution.metadata["reason"] == "modelIntentRequired")
- }
-
@Test
func genericAdapterBuildsLocalNavigationRequestForTargetApp() throws {
let intent = weatherIntent(rawCity: "San Francisco", city: "San Francisco")
@@ -199,138 +123,6 @@ struct LocalAppTaskTests {
#expect(localAdapter.verifiesVisibleText("New York", matches: intent) == false)
}
- @Test
- func appOpenAdapterVerifiesFocusedApp() throws {
- let catalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,
- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Music"])
- )
- let resolution = catalog.resolve(intent: TaskIntent(
- intentID: "app_open-music",
- taskType: "app_open",
- targetApp: LocalAppTarget(appName: "Local Item", metadata: ["dynamicTarget": "true"]),
- entities: ["appName": "music"],
- normalizedEntities: ["appName": "Music"],
- confidence: 0.9,
- parserSource: .localModel
- ))
- let intent = try #require(resolution.intent)
- let definition = try #require(resolution.definition)
- let localAdapter = LocalAppTaskAdapter(definition: definition)
- let plan = localAdapter.evidenceBackedActionPlan(
- for: intent,
- observation: LocalAppTaskObservation(
- appIsRunning: true,
- appIsFocused: true,
- confidence: 0.72
- )
- )
-
- #expect(plan.terminalState == .completed)
- #expect(plan.verificationConfidence == 0.8)
- #expect(plan.steps.first(where: { $0.role == .verifyResult })?.status == .verified)
- }
-
- @Test
- func catalogResolvesGenericModelPlannedLocalAppInteraction() throws {
- let catalog = LocalAppTaskCatalog(
- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
- availabilityProvider: StaticLocalAppAvailabilityProvider(
- installedBundleIdentifiers: ["com.apple.Music"]
- )
- )
-
- let resolution = catalog.resolve(intent: genericLocalAppInteractionIntent(
- appName: "Music",
- query: "Sample Track",
- planTools: [
- .openOrFocusApp,
- .observeApp,
- .focusSearch,
- .setText,
- .pressReturn,
- .pressReturn,
- .verifyCommand
- ]
- ))
- let intent = try #require(resolution.intent)
- let definition = try #require(resolution.definition)
- let localAdapter = LocalAppTaskAdapter(definition: definition)
- let plan = localAdapter.evidenceBackedActionPlan(
- for: intent,
- observation: LocalAppTaskObservation(
- appIsRunning: true,
- appIsFocused: true,
- availableControls: ["search": true],
- confidence: 0.7,
- metadata: groundedControlMetadata()
- )
- )
-
- #expect(resolution.status == .resolved)
- #expect(intent.taskType == "local_app_interaction")
- #expect(intent.targetApp.appName == "Music")
- #expect(intent.targetApp.bundleIdentifier == "com.apple.Music")
- #expect(definition.metadata["modelPlanned"] == "true")
- #expect(definition.metadata["plan.tools"] == "app.openOrFocus,app.observe,ui.focusSearch,ui.setText,ui.pressReturn,ui.pressReturn,app.verifyCommand")
- #expect(plan.terminalState == .completed)
- #expect(plan.steps.map(\.role) == [
- .parseIntent,
- .launchOrFocusApp,
- .observeApp,
- .focusControl,
- .enterText,
- .submit,
- .submit,
- .verifyResult
- ])
-
- let commands = localAdapter.guardedKeyboardCommandTemplates(
- for: intent,
- issuedAt: timestamp(100)
- )
- #expect(commands.map(\.key) == ["Command+F", "Sample Track", "Return", "Return"])
- #expect(commands.first?.metadata["plan.tool"] == "ui.focusSearch")
- }
-
- @Test
- func genericInteractionShortcutFocusDoesNotRequireControlBounds() throws {
- let catalog = LocalAppTaskCatalog(
- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
- availabilityProvider: StaticLocalAppAvailabilityProvider(
- installedBundleIdentifiers: ["com.apple.Music"]
- )
- )
- let resolution = catalog.resolve(intent: genericLocalAppInteractionIntent(
- appName: "Music",
- query: "Sample Track",
- planTools: [
- .openOrFocusApp,
- .observeApp,
- .focusSearch,
- .setText,
- .pressReturn,
- .verifyCommand
- ]
- ))
- let intent = try #require(resolution.intent)
- let definition = try #require(resolution.definition)
- let plan = catalog.adapter(for: definition).evidenceBackedActionPlan(
- for: intent,
- observation: LocalAppTaskObservation(
- appIsRunning: true,
- appIsFocused: true,
- availableControls: [:],
- confidence: 0.7
- )
- )
-
- #expect(resolution.status == .resolved)
- #expect(plan.canExecuteGuardedActions == true)
- #expect(plan.terminalState == .completed)
- #expect(plan.steps.first(where: { $0.role == .focusControl })?.status == .verified)
- }
-
@Test
func staticProviderBuildsAppFinderCatalogWithSupportAndDenyMetadata() throws {
let provider = StaticLocalAppAvailabilityProvider(
@@ -356,220 +148,6 @@ struct LocalAppTaskTests {
#expect(draftPad.capabilities.isEmpty)
}
- @Test
- func catalogResolvesGenericModelPlannedTextEntryCreation() throws {
- let catalog = LocalAppTaskCatalog(
- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
- availabilityProvider: StaticLocalAppAvailabilityProvider(
- installedBundleIdentifiers: ["com.example.DraftPad"],
- installedApplicationNames: ["DraftPad": "com.example.DraftPad"]
- )
- )
- let textToEnter = "Checklist\n- First item\n- Second item\n- Third item"
- let intent = TaskIntent(
- intentID: "local_app_interaction-draftpad-checklist",
- taskType: "local_app_interaction",
- targetApp: LocalAppTarget(appName: "DraftPad", titleContains: "DraftPad"),
- entities: [
- "appName": "DraftPad",
- "goal": "create text content",
- "query": textToEnter
- ],
- normalizedEntities: [
- "appName": "DraftPad",
- "goal": "create text content",
- "query": textToEnter
- ],
- confidence: 0.9,
- parserSource: .onlineModel,
- actionPlan: LocalAppActionPlan(
- tools: [
- .openOrFocusApp,
- .observeApp,
- .newDocument,
- .setText,
- .verifyCommand
- ],
- inputEntity: "query",
- controlID: "editor",
- focusKey: ""
- ),
- metadata: ["requestedItemName": "DraftPad"]
- )
-
- let resolution = catalog.resolve(intent: intent)
- let resolvedIntent = try #require(resolution.intent)
- let definition = try #require(resolution.definition)
- let localAdapter = LocalAppTaskAdapter(definition: definition)
- let plan = localAdapter.evidenceBackedActionPlan(
- for: resolvedIntent,
- observation: LocalAppTaskObservation(
- appIsRunning: true,
- appIsFocused: true,
- confidence: 0.72
- )
- )
- let commands = localAdapter.guardedKeyboardCommandTemplates(
- for: resolvedIntent,
- issuedAt: timestamp(100)
- )
-
- #expect(resolution.status == .resolved)
- #expect(resolvedIntent.targetApp.bundleIdentifier == "com.example.DraftPad")
- #expect(definition.metadata["plan.tools"] == "app.openOrFocus,app.observe,ui.newDocument,ui.setText,app.verifyCommand")
- #expect(definition.metadata["plan.setTextInputContract"] == "inputEntityValueIsExactTextToEnter")
- #expect(plan.terminalState == .completed)
- #expect(commands.map(\.key) == ["Command+N", textToEnter])
- #expect(commands.first?.metadata["plan.tool"] == "ui.newDocument")
- #expect(commands.last?.metadata["inputRole"] == "textEntry")
- }
-
- @Test
- func genericModelPlannedInteractionRequiresTypedActionPlanBeforeExecution() {
- let catalog = LocalAppTaskCatalog(
- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
- availabilityProvider: StaticLocalAppAvailabilityProvider(
- installedBundleIdentifiers: ["com.apple.Music"]
- )
- )
-
- let resolution = catalog.resolve(intent: genericLocalAppInteractionIntent(
- appName: "Music",
- query: "Sample Track",
- planTools: nil
- ))
-
- #expect(resolution.status == .needsConfirmation)
- #expect(resolution.metadata["reason"] == "missingActionPlan")
- }
-
- @Test
- func catalogResolvesStructuredIntentAgainstAvailableInstalledAppDefinition() throws {
- let catalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,
- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: [
- "com.apple.weather",
- "com.apple.Music",
- "com.apple.Preview"
- ])
- )
-
- let resolution = catalog.resolve(intent: weatherIntent(rawCity: "SF", city: "San Francisco"))
-
- #expect(resolution.status == .resolved)
- #expect(resolution.intent?.normalizedEntities["city"] == "San Francisco")
- #expect(resolution.definition?.taskType == "weather_lookup")
- #expect(resolution.definition?.observationStrategies == [.accessibility, .windowMetadata, .screenshotForLocalModel])
- #expect(resolution.availability?.isInstalled == true)
-
- let definition = try #require(resolution.definition)
- let intent = try #require(resolution.intent)
- let plan = catalog.adapter(for: definition).evidenceBackedActionPlan(for: intent)
- #expect(plan.steps.map(\.role).contains(.verifyResult))
-
- let documentResolution = catalog.resolve(intent: documentFormFillIntent())
- #expect(documentResolution.status == .resolved)
- #expect(documentResolution.definition?.taskType == "document_form_fill")
- }
-
- @Test
- func catalogSeparatesUnsupportedMissingEntityAndUnavailableApp() {
- let availableCatalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,
- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])
- )
- let unavailableAppResolution = availableCatalog.resolve(intent: TaskIntent(
- intentID: "app_open-missing",
- taskType: "app_open",
- targetApp: LocalAppTarget(appName: "Local Item", metadata: ["dynamicTarget": "true"]),
- entities: ["appName": "an app that does not exist"],
- normalizedEntities: ["appName": "An App That Does Not Exist"],
- confidence: 0.86,
- parserSource: .localModel
- ))
- #expect(unavailableAppResolution.status == .appUnavailable)
- #expect(unavailableAppResolution.metadata["reason"] == "targetAppUnavailable")
- #expect(availableCatalog.resolve(intent: weatherIntent(rawCity: "", city: "", needsConfirmation: true)).status == .needsConfirmation)
-
- let unavailableCatalog = LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,
- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: [])
- )
- #expect(unavailableCatalog.resolve(intent: weatherIntent(rawCity: "SF", city: "San Francisco")).status == .appUnavailable)
- }
-
- @Test
- func taskDefinitionLoaderLoadsLocalJSONDefinitions() throws {
- let directoryURL = FileManager.default.temporaryDirectory
- .appendingPathComponent("DonkeyTaskDefinitionLoader-\(UUID().uuidString)", isDirectory: true)
- try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
- defer { try? FileManager.default.removeItem(at: directoryURL) }
-
- let definition = LocalAppTaskDefinition(
- taskType: "notes_capture",
- targetApp: LocalAppTarget(appName: "Notes", bundleIdentifier: "com.apple.Notes"),
- triggerTerms: [],
- entityRules: [
- LocalAppTaskEntityRule(
- name: "note"
- )
- ],
- workflowSteps: [
- LocalAppTaskWorkflowStepDefinition(
- id: "parse-intent",
- role: .parseIntent,
- summary: "Parse note intent"
- )
- ],
- verificationEntityName: "note",
- metadata: ["source": "test-json"]
- )
- let fileURL = directoryURL.appendingPathComponent("notes.json")
- try JSONEncoder().encode(definition).write(to: fileURL)
-
- let storeURL = temporaryStoreDirectory()
- defer { try? FileManager.default.removeItem(at: storeURL) }
- let store = try SQLiteAgentMemoryStore(baseDirectory: storeURL, cleanupLegacyStores: false)
- let definitions = try LocalAppTaskDefinitionLoader(memoryStore: store).cachedDefinitions(from: directoryURL)
- let loaded = try #require(definitions.first(where: { $0.taskType == "notes_capture" }))
- #expect(loaded.targetApp.bundleIdentifier == "com.apple.Notes")
- #expect(loaded.metadata["source"] == "test-json")
- #expect(store.taskDefinitions().map(\.taskType).contains("notes_capture"))
-
- let catalog = LocalAppTaskCatalog(
- taskDefinitions: definitions,
- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Notes"])
- )
- #expect(catalog.resolve(intent: TaskIntent(
- intentID: "notes_capture-buy-milk",
- taskType: "notes_capture",
- targetApp: LocalAppTarget(appName: "Notes", bundleIdentifier: "com.apple.Notes"),
- entities: ["note": "buy milk"],
- normalizedEntities: ["note": "buy milk"],
- confidence: 0.9,
- parserSource: .localModel
- )).status == .resolved)
- }
-
- @Test
- func defaultLocalCatalogLoadsRuntimeDefinitionsFromCache() {
- let storeURL = temporaryStoreDirectory()
- defer { try? FileManager.default.removeItem(at: storeURL) }
- let store = try? SQLiteAgentMemoryStore(baseDirectory: storeURL, cleanupLegacyStores: false)
- let loader = LocalAppTaskDefinitionLoader(memoryStore: store)
-
- let catalog = LocalAppTaskCatalog.defaultLocal(
- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: []),
- loader: loader
- )
-
- #expect(catalog.taskDefinitions.map(\.taskType) == ["app_open", "local_app_interaction"])
- #expect(store?.taskDefinitions().map(\.taskType) == ["app_open", "local_app_interaction"])
- #expect(catalog.taskDefinitions.contains { $0.targetApp.appName == "Weather" } == false)
- #expect(catalog.taskDefinitions.contains { $0.targetApp.appName == "Music" } == false)
- #expect(catalog.taskDefinitions.contains { $0.targetApp.appName == "Preview" } == false)
- }
-
@Test
func appFinderProfilesLoadFromBundledJSON() throws {
let store = LocalAppFinderProfileStore.defaultStore
@@ -994,225 +572,6 @@ struct LocalAppTaskTests {
#expect(groundedMetadata["control.bounds.space"] == HotLoopCoordinateSpace.normalizedTarget.rawValue)
}
- @Test @MainActor
- func visualObservationBoundsCanDriveModelPlannedClickTarget() async throws {
- let catalog = LocalAppTaskCatalog(
- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
- availabilityProvider: StaticLocalAppAvailabilityProvider(
- installedBundleIdentifiers: ["com.apple.Music"]
- )
- )
- let intent = genericLocalAppInteractionIntent(
- appName: "Music",
- query: "Sample Track",
- planTools: [.openOrFocusApp, .observeApp, .clickTarget, .verifyCommand]
- )
- let resolution = catalog.resolve(intent: intent)
- let definition = try #require(resolution.definition)
- var metadata = LocalAppObservationGeometry.targetBoundsMetadata(
- WindowTargetBounds(x: 100, y: 200, width: 500, height: 300)
- )
- metadata.merge(LocalAppObservationGeometry.controlMetadata(
- controlID: "search",
- frame: HotLoopRect(x: 50, y: 60, width: 100, height: 40, space: .window),
- source: .localUIUnderstanding,
- label: "Search",
- kind: .button,
- confidence: 0.82,
- extra: [
- "localUIElement.actionEligibility": "guardedAction",
- "directInputActionsAllowed": "true"
- ]
- )) { current, _ in current }
- let observation = LocalAppTaskObservation(
- appIsRunning: true,
- appIsFocused: true,
- availableControls: ["search": true],
- visibleText: ["visibleText": "Search"],
- confidence: 0.82,
- metadata: metadata
- )
- let backend = RecordingLocalAppTaskInputBackend()
- let executor = LocalAppHarnessStepExecutor(
- command: "click the visible search target",
- traceID: "trace-visual-click",
- resolution: resolution,
- appController: FakeLocalAppTaskAppController(
- launchObservation: observation,
- finalObservation: observation
- ),
- actionEngineFactory: { _ in
- ActionEngineGuardrail(
- configuration: ActionEngineConfiguration(liveInputEnabled: true),
- inputBackend: backend
- )
- }
- )
- let registry = HarnessToolRegistry()
- await executor.registerTools(in: registry)
-
- _ = await registry.execute(
- HarnessToolCall(id: "observe", name: LocalAppActionPlanTool.observeApp.rawValue),
- taskID: "task-visual-click",
- worldModel: HarnessWorldModel(),
- grantedPermissions: [.screenCapture, .accessibility, .input]
- )
- let clickResult = await registry.execute(
- HarnessToolCall(
- id: "click",
- name: LocalAppActionPlanTool.clickTarget.rawValue,
- input: [
- "controlID": "search",
- "modelStepID": "click-search"
- ]
- ),
- taskID: "task-visual-click",
- worldModel: HarnessWorldModel(),
- grantedPermissions: [.screenCapture, .accessibility, .input]
- )
-
- let command = try #require(await backend.executedCommands().first)
- #expect(clickResult.status == .succeeded)
- #expect(command.kind == .tap)
- #expect(command.metadata["inputStrategy"] == "visual-coordinate")
- #expect(command.metadata["visualFallback"] == "aiOrObservedBounds")
- #expect(command.targetBounds == HotLoopRect(x: 150, y: 260, width: 100, height: 40, space: .screen))
- #expect(definition.workflowSteps.contains { $0.metadata["plan.tool"] == "ui.clickTarget" })
- }
-
- @Test @MainActor
- func currentModelStepCanDriveTextEntryWhenPlanTemplateDoesNotMatch() async throws {
- let catalog = LocalAppTaskCatalog(
- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
- availabilityProvider: StaticLocalAppAvailabilityProvider(
- installedBundleIdentifiers: ["com.apple.Music"]
- )
- )
- let intent = TaskIntent(
- intentID: "local_app_interaction-justin-bieber",
- taskType: "local_app_interaction",
- targetApp: LocalAppTarget(appName: "Music", titleContains: "Music"),
- entities: [
- "appName": "Music",
- "goal": "play media",
- "query": "Justin Bieber"
- ],
- normalizedEntities: [
- "appName": "Music",
- "goal": "play media",
- "query": "Justin Bieber"
- ],
- confidence: 0.93,
- parserSource: .localModel,
- actionPlan: LocalAppActionPlan(
- tools: [.openOrFocusApp, .observeApp, .focusSearch, .setText, .pressReturn, .verifyCommand],
- inputEntity: "query",
- controlID: "model-search",
- focusKey: "Command+F"
- ),
- metadata: ["requestedItemName": "Music"]
- )
- let resolution = catalog.resolve(intent: intent)
- var metadata = LocalAppObservationGeometry.targetBoundsMetadata(
- WindowTargetBounds(x: 100, y: 200, width: 500, height: 300)
- )
- metadata.merge(LocalAppObservationGeometry.controlMetadata(
- controlID: "search",
- frame: HotLoopRect(x: 50, y: 60, width: 100, height: 40, space: .window),
- source: .localUIUnderstanding,
- label: "Search",
- kind: .searchField,
- confidence: 0.82,
- extra: ["directInputActionsAllowed": "true"]
- )) { current, _ in current }
- let observation = LocalAppTaskObservation(
- appIsRunning: true,
- appIsFocused: true,
- availableControls: ["search": true],
- visibleText: ["visibleText": "Search"],
- confidence: 0.82,
- metadata: metadata
- )
- let backend = RecordingLocalAppTaskInputBackend()
- let executor = LocalAppHarnessStepExecutor(
- command: "play some justin bieber",
- traceID: "trace-model-step-fallback",
- resolution: resolution,
- appController: FakeLocalAppTaskAppController(
- launchObservation: observation,
- finalObservation: observation
- ),
- actionEngineFactory: { _ in
- ActionEngineGuardrail(
- configuration: ActionEngineConfiguration(liveInputEnabled: true),
- inputBackend: backend
- )
- }
- )
- let registry = HarnessToolRegistry()
- await executor.registerTools(in: registry)
-
- _ = await registry.execute(
- HarnessToolCall(id: "observe", name: LocalAppActionPlanTool.observeApp.rawValue),
- taskID: "task-model-step-fallback",
- worldModel: HarnessWorldModel(),
- grantedPermissions: [.screenCapture, .accessibility, .input]
- )
- _ = await registry.execute(
- HarnessToolCall(
- id: "focus",
- name: LocalAppActionPlanTool.focusSearch.rawValue,
- input: [
- "controlID": "search",
- "focusKey": "Command+F",
- "modelStepID": "focus-search"
- ]
- ),
- taskID: "task-model-step-fallback",
- worldModel: HarnessWorldModel(),
- grantedPermissions: [.screenCapture, .accessibility, .input]
- )
- let setTextResult = await registry.execute(
- HarnessToolCall(
- id: "set-text",
- name: LocalAppActionPlanTool.setText.rawValue,
- input: [
- "inputEntity": "query",
- "controlID": "search",
- "modelStepID": "set-query"
- ]
- ),
- taskID: "task-model-step-fallback",
- worldModel: HarnessWorldModel(),
- grantedPermissions: [.screenCapture, .accessibility, .input]
- )
- let submitResult = await registry.execute(
- HarnessToolCall(
- id: "submit",
- name: LocalAppActionPlanTool.pressReturn.rawValue,
- input: [
- "controlID": "search",
- "focusKey": "search",
- "modelStepID": "submit"
- ]
- ),
- taskID: "task-model-step-fallback",
- worldModel: HarnessWorldModel(),
- grantedPermissions: [.screenCapture, .accessibility, .input]
- )
-
- let commands = await backend.executedCommands()
- #expect(setTextResult.status == .succeeded)
- #expect(submitResult.status == .succeeded)
- #expect(commands.map(\.kind) == [.tap, .key, .key])
- #expect(commands[1].key == "Justin Bieber")
- #expect(commands[1].metadata["inputStrategy"] == "model-planned-tool-call")
- #expect(commands[1].metadata["workflowStepID"] == "set-query")
- #expect(commands[1].metadata["controlID"] == "search")
- #expect(commands[2].key == "Return")
- #expect(commands[2].metadata["workflowStepID"] == "submit")
- }
-
@Test @MainActor
func documentApprovalRunnerExecutesOnlyApprovedFields() async throws {
let backend = RecordingLocalAppTaskInputBackend()
@@ -1265,13 +624,6 @@ struct LocalAppTaskTests {
#expect(controller.launchCount == 1)
}
- private func catalog() -> LocalAppTaskCatalog {
- LocalAppTaskCatalog(
- taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,
- availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: [])
- )
- }
-
private func weatherIntent(
rawCity: String,
city: String,
@@ -1294,43 +646,6 @@ struct LocalAppTaskTests {
)
}
- private func genericLocalAppInteractionIntent(
- appName: String,
- query: String,
- planTools: [LocalAppActionPlanTool]?,
- confidence: Double = 0.93
- ) -> TaskIntent {
- let actionPlan = planTools.map {
- LocalAppActionPlan(
- tools: $0,
- inputEntity: "query",
- controlID: "search",
- focusKey: "Command+F"
- )
- }
- return TaskIntent(
- intentID: "local_app_interaction-\(slug(query))",
- taskType: "local_app_interaction",
- targetApp: LocalAppTarget(appName: appName, titleContains: appName),
- entities: [
- "appName": appName,
- "goal": "play media",
- "query": query
- ],
- normalizedEntities: [
- "appName": appName,
- "goal": "play media",
- "query": query
- ],
- confidence: confidence,
- parserSource: .localModel,
- actionPlan: actionPlan,
- metadata: [
- "requestedItemName": appName
- ]
- )
- }
-
private func documentFormFillIntent(confidence: Double = 0.9) -> TaskIntent {
let definition = BuiltInLocalAppTaskDefinitions.documentFormFill
return TaskIntent(
@@ -1384,11 +699,6 @@ struct LocalAppTaskTests {
) { current, _ in current }
return metadata
}
-
- private func temporaryStoreDirectory() -> URL {
- FileManager.default.temporaryDirectory
- .appendingPathComponent("donkey-task-memory-\(UUID().uuidString)", isDirectory: true)
- }
}
private final class RecordingApplicationCatalogScanner: LocalApplicationCatalogScanning, @unchecked Sendable {
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/TestLocalAppTaskDefinitions.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/TestLocalAppTaskDefinitions.swift
index cdc90209..1bd35a27 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/TestLocalAppTaskDefinitions.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/TestLocalAppTaskDefinitions.swift
@@ -62,10 +62,27 @@ extension BuiltInLocalAppTaskDefinitions {
)
}
+ static var genericLocalAppInteraction: LocalAppTaskDefinition {
+ LocalAppTaskDefinition(
+ taskType: "local_app_interaction",
+ targetApp: LocalAppTarget(appName: "Local App Interaction"),
+ triggerTerms: [],
+ entityRules: [],
+ workflowSteps: commonWorkflowPrefix,
+ observationStrategies: [.accessibility, .windowMetadata],
+ verificationEntityName: nil,
+ metadata: [
+ "catalogEntry": "local app interaction",
+ "displayTitle": "local app interaction",
+ "modelPlanned": "true",
+ "dynamicTarget": "true"
+ ]
+ )
+ }
+
static var testFixtures: [LocalAppTaskDefinition] {
[
- LocalAppTaskCatalog.genericLocalItemOpenDefinition,
- LocalAppTaskCatalog.genericLocalAppInteractionDefinition,
+ genericLocalAppInteraction,
weatherLookup,
documentFormFill
]