Open source CapCut alternative.
TypeScript
Add generic harness foundation
David Le92887668fbe7
diff --git a/apps/Donkey/Package.swift b/apps/Donkey/Package.swiftindex 2b158e92..7a2a86a1 100644--- a/apps/Donkey/Package.swift+++ b/apps/Donkey/Package.swift@@ -19,6 +19,10 @@ let package = Package(.library(name: "DonkeyContracts",targets: ["DonkeyContracts"]+ ),+ .library(+ name: "DonkeyHarness",+ targets: ["DonkeyHarness"])],dependencies: [@@ -28,6 +32,10 @@ let package = Package(.target(name: "DonkeyContracts"),+ .target(+ name: "DonkeyHarness",+ dependencies: ["DonkeyContracts"]+ ),.target(name: "DonkeyRuntime",dependencies: ["DonkeyContracts"],@@ -79,6 +87,7 @@ let package = Package(dependencies: ["DonkeyAI","DonkeyContracts",+ "DonkeyHarness","DonkeyRuntime","DonkeyUI"],diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swiftnew file mode 100644index 00000000..2997bc3d--- /dev/null+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swift@@ -0,0 +1,367 @@+import DonkeyContracts+import Foundation++public enum HarnessStage: String, Codable, CaseIterable, Equatable, Sendable {+ case intake+ case intentAnalysis+ case contextGathering+ case worldModel+ case planning+ case execution+ case verification+ case recovery+ case clarification+ case permissionGate+ case lifecycle+}++public enum HarnessTaskStatus: String, Codable, CaseIterable, Equatable, Sendable {+ case running+ case paused+ case waitingForUser+ case waitingForPermission+ case interrupted+ case resuming+ case completed+ case failedSafe+ case cancelled++ public var canExecuteTools: Bool {+ self == .running || self == .resuming+ }+}++public enum HarnessTurnRelationship: String, Codable, Equatable, Sendable {+ case startsNewTask+ case modifiesCurrentTask+ case cancelsTask+ case pausesTask+ case resumesTask+ case answersClarification+ case grantsPermission+ case conversation+}++public enum HarnessAmbiguityClass: String, Codable, Equatable, Sendable {+ case safe+ case recoverable+ case dangerous+}++public enum HarnessRiskLevel: String, Codable, Equatable, Sendable {+ case low+ case medium+ case high+}++public enum HarnessPermission: String, Codable, CaseIterable, Hashable, Sendable {+ case conversation+ case memory+ case appLookup+ case appControl+ case screenCapture+ case accessibility+ case input+ case verification+ case lifecycle+ case userPrompt+ case skillLookup+}++public enum HarnessToolSafetyClass: String, Codable, Equatable, Sendable {+ case readOnly+ case reversible+ case guardedInput+ case destructive+ case sensitive+}++public enum HarnessToolResultStatus: String, Codable, Equatable, Sendable {+ case succeeded+ case failed+ case unknownTool+ case invalidInput+ case permissionDenied+ case waitingForUser+ case waitingForPermission+}++public struct HarnessIntentAnalysis: Codable, Equatable, Sendable {+ public var goal: String+ public var entities: [String: String]+ public var ambiguityClass: HarnessAmbiguityClass+ public var riskLevel: HarnessRiskLevel+ public var missingInformation: [String]+ public var shouldAskBeforeActing: Bool+ public var confidence: Double+ public var metadata: [String: String]++ public init(+ goal: String,+ entities: [String: String] = [:],+ ambiguityClass: HarnessAmbiguityClass = .recoverable,+ riskLevel: HarnessRiskLevel = .medium,+ missingInformation: [String] = [],+ shouldAskBeforeActing: Bool = false,+ confidence: Double = 0,+ metadata: [String: String] = [:]+ ) {+ self.goal = goal+ self.entities = entities+ self.ambiguityClass = ambiguityClass+ self.riskLevel = riskLevel+ self.missingInformation = missingInformation+ self.shouldAskBeforeActing = shouldAskBeforeActing+ self.confidence = min(max(confidence, 0), 1)+ self.metadata = metadata+ }+}++public struct HarnessContextSnapshot: Codable, Equatable, Sendable {+ public var turn: AppHarnessTurn?+ public var threadID: String?+ public var memory: [String]+ public var availableToolNames: [String]+ public var availableSkillIDs: [String]+ public var policy: [String: String]+ public var metadata: [String: String]++ public init(+ turn: AppHarnessTurn? = nil,+ threadID: String? = nil,+ memory: [String] = [],+ availableToolNames: [String] = [],+ availableSkillIDs: [String] = [],+ policy: [String: String] = [:],+ metadata: [String: String] = [:]+ ) {+ self.turn = turn+ self.threadID = threadID+ self.memory = memory+ self.availableToolNames = availableToolNames+ self.availableSkillIDs = availableSkillIDs+ self.policy = policy+ self.metadata = metadata+ }+}++public struct HarnessWorldModel: Codable, Equatable, Sendable {+ public var focusedApp: String?+ public var focusedWindowTitle: String?+ public var visibleText: [String: String]+ public var elements: [HarnessWorldElement]+ public var attemptedToolCalls: [HarnessToolCallRecord]+ public var facts: [String: String]+ public var uncertainty: [String]+ public var updatedAt: Date++ public init(+ focusedApp: String? = nil,+ focusedWindowTitle: String? = nil,+ visibleText: [String: String] = [:],+ elements: [HarnessWorldElement] = [],+ attemptedToolCalls: [HarnessToolCallRecord] = [],+ facts: [String: String] = [:],+ uncertainty: [String] = [],+ updatedAt: Date = Date()+ ) {+ self.focusedApp = focusedApp+ self.focusedWindowTitle = focusedWindowTitle+ self.visibleText = visibleText+ self.elements = elements+ self.attemptedToolCalls = attemptedToolCalls+ self.facts = facts+ self.uncertainty = uncertainty+ self.updatedAt = updatedAt+ }++ public func merging(result: HarnessToolResult) -> HarnessWorldModel {+ var model = self+ model.visibleText.merge(result.observations.visibleText) { _, new in new }+ model.facts.merge(result.observations.facts) { _, new in new }+ model.uncertainty = Array(Set(model.uncertainty + result.observations.uncertainty)).sorted()+ if !result.observations.elements.isEmpty {+ model.elements = result.observations.elements+ }+ if let focusedApp = result.observations.focusedApp {+ model.focusedApp = focusedApp+ }+ if let focusedWindowTitle = result.observations.focusedWindowTitle {+ model.focusedWindowTitle = focusedWindowTitle+ }+ model.updatedAt = result.completedAt+ return model+ }+}++public struct HarnessWorldElement: Codable, Equatable, Sendable {+ public var id: String+ public var label: String+ public var role: String+ public var isActionEligible: Bool+ public var actions: [String]+ public var metadata: [String: String]++ public init(+ id: String,+ label: String,+ role: String,+ isActionEligible: Bool,+ actions: [String] = [],+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.label = label+ self.role = role+ self.isActionEligible = isActionEligible+ self.actions = actions+ self.metadata = metadata+ }+}++public struct HarnessPlan: Codable, Equatable, Sendable {+ public var goal: String+ public var steps: [HarnessPlanStep]+ public var successCriteria: [String]+ public var fallbackPolicy: [String]+ public var clarificationPolicy: [String]+ public var confidence: Double+ public var metadata: [String: String]++ public init(+ goal: String,+ steps: [HarnessPlanStep],+ successCriteria: [String] = [],+ fallbackPolicy: [String] = [],+ clarificationPolicy: [String] = [],+ confidence: Double = 0,+ metadata: [String: String] = [:]+ ) {+ self.goal = goal+ self.steps = steps+ self.successCriteria = successCriteria+ self.fallbackPolicy = fallbackPolicy+ self.clarificationPolicy = clarificationPolicy+ self.confidence = min(max(confidence, 0), 1)+ self.metadata = metadata+ }+}++public struct HarnessPlanStep: Codable, Equatable, Sendable {+ public var id: String+ public var summary: String+ public var toolCall: HarnessToolCall?+ public var expectedObservation: String?+ public var metadata: [String: String]++ public init(+ id: String,+ summary: String,+ toolCall: HarnessToolCall? = nil,+ expectedObservation: String? = nil,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.summary = summary+ self.toolCall = toolCall+ self.expectedObservation = expectedObservation+ self.metadata = metadata+ }+}++public struct HarnessToolCall: Codable, Equatable, Sendable {+ public var id: String+ public var name: String+ public var input: [String: String]+ public var metadata: [String: String]++ public init(+ id: String = UUID().uuidString,+ name: String,+ input: [String: String] = [:],+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.name = name+ self.input = input+ self.metadata = metadata+ }+}++public struct HarnessToolCallRecord: Codable, Equatable, Sendable {+ public var call: HarnessToolCall+ public var resultStatus: HarnessToolResultStatus+ public var summary: String+ public var recordedAt: Date++ public init(+ call: HarnessToolCall,+ resultStatus: HarnessToolResultStatus,+ summary: String,+ recordedAt: Date = Date()+ ) {+ self.call = call+ self.resultStatus = resultStatus+ self.summary = summary+ self.recordedAt = recordedAt+ }+}++public struct HarnessObservationDelta: Codable, Equatable, Sendable {+ public var focusedApp: String?+ public var focusedWindowTitle: String?+ public var visibleText: [String: String]+ public var elements: [HarnessWorldElement]+ public var facts: [String: String]+ public var uncertainty: [String]++ public init(+ focusedApp: String? = nil,+ focusedWindowTitle: String? = nil,+ visibleText: [String: String] = [:],+ elements: [HarnessWorldElement] = [],+ facts: [String: String] = [:],+ uncertainty: [String] = []+ ) {+ self.focusedApp = focusedApp+ self.focusedWindowTitle = focusedWindowTitle+ self.visibleText = visibleText+ self.elements = elements+ self.facts = facts+ self.uncertainty = uncertainty+ }+}++public struct HarnessToolResult: Codable, Equatable, Sendable {+ public var callID: String+ public var toolName: String+ public var status: HarnessToolResultStatus+ public var summary: String+ public var observations: HarnessObservationDelta+ public var missingPermissions: [HarnessPermission]+ public var question: String?+ public var completedAt: Date+ public var metadata: [String: String]++ public init(+ callID: String,+ toolName: String,+ status: HarnessToolResultStatus,+ summary: String,+ observations: HarnessObservationDelta = HarnessObservationDelta(),+ missingPermissions: [HarnessPermission] = [],+ question: String? = nil,+ completedAt: Date = Date(),+ metadata: [String: String] = [:]+ ) {+ self.callID = callID+ self.toolName = toolName+ self.status = status+ self.summary = summary+ self.observations = observations+ self.missingPermissions = missingPermissions+ self.question = question+ self.completedAt = completedAt+ self.metadata = metadata+ }+}diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swiftnew file mode 100644index 00000000..03f10bb3--- /dev/null+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift@@ -0,0 +1,346 @@+import DonkeyContracts+import Foundation++public struct HarnessPendingContinuation: Codable, Equatable, Sendable {+ public var checkpointID: String+ public var stage: HarnessStage+ public var reason: String+ public var question: String?+ public var missingPermissions: [HarnessPermission]+ public var pendingToolCall: HarnessToolCall?+ public var createdAt: Date+ public var metadata: [String: String]++ public init(+ checkpointID: String = UUID().uuidString,+ stage: HarnessStage,+ reason: String,+ question: String? = nil,+ missingPermissions: [HarnessPermission] = [],+ pendingToolCall: HarnessToolCall? = nil,+ createdAt: Date = Date(),+ metadata: [String: String] = [:]+ ) {+ self.checkpointID = checkpointID+ self.stage = stage+ self.reason = reason+ self.question = question+ self.missingPermissions = missingPermissions+ self.pendingToolCall = pendingToolCall+ self.createdAt = createdAt+ self.metadata = metadata+ }+}++public struct HarnessTaskState: Codable, Equatable, Sendable {+ public var id: String+ public var threadID: String+ public var goal: String+ public var status: HarnessTaskStatus+ public var intent: HarnessIntentAnalysis?+ public var context: HarnessContextSnapshot+ public var worldModel: HarnessWorldModel+ public var plan: HarnessPlan?+ public var grantedPermissions: Set<HarnessPermission>+ public var toolHistory: [HarnessToolCallRecord]+ public var pendingContinuation: HarnessPendingContinuation?+ public var createdAt: Date+ public var updatedAt: Date+ public var metadata: [String: String]++ public init(+ id: String = UUID().uuidString,+ threadID: String,+ goal: String,+ status: HarnessTaskStatus = .running,+ intent: HarnessIntentAnalysis? = nil,+ context: HarnessContextSnapshot = HarnessContextSnapshot(),+ worldModel: HarnessWorldModel = HarnessWorldModel(),+ plan: HarnessPlan? = nil,+ grantedPermissions: Set<HarnessPermission> = [],+ toolHistory: [HarnessToolCallRecord] = [],+ pendingContinuation: HarnessPendingContinuation? = nil,+ createdAt: Date = Date(),+ updatedAt: Date = Date(),+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.threadID = threadID+ self.goal = goal+ self.status = status+ self.intent = intent+ self.context = context+ self.worldModel = worldModel+ self.plan = plan+ self.grantedPermissions = grantedPermissions+ self.toolHistory = toolHistory+ self.pendingContinuation = pendingContinuation+ self.createdAt = createdAt+ self.updatedAt = updatedAt+ self.metadata = metadata+ }+}++public struct HarnessTaskEvent: Codable, Equatable, Sendable {+ public var id: String+ public var taskID: String+ public var status: HarnessTaskStatus+ public var summary: String+ public var createdAt: Date+ public var metadata: [String: String]++ public init(+ id: String = UUID().uuidString,+ taskID: String,+ status: HarnessTaskStatus,+ summary: String,+ createdAt: Date = Date(),+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.taskID = taskID+ self.status = status+ self.summary = summary+ self.createdAt = createdAt+ self.metadata = metadata+ }+}++public actor HarnessTaskCoordinator {+ private var tasksByID: [String: HarnessTaskState] = [:]+ private var eventsByTaskID: [String: [HarnessTaskEvent]] = [:]++ public init() {}++ @discardableResult+ public func createTask(+ id: String = UUID().uuidString,+ threadID: String,+ goal: String,+ intent: HarnessIntentAnalysis? = nil,+ context: HarnessContextSnapshot = HarnessContextSnapshot(),+ grantedPermissions: Set<HarnessPermission> = []+ ) -> HarnessTaskState {+ let task = HarnessTaskState(+ id: id,+ threadID: threadID,+ goal: goal,+ intent: intent,+ context: context,+ grantedPermissions: grantedPermissions+ )+ tasksByID[id] = task+ appendEvent(taskID: id, status: task.status, summary: "Task created")+ return task+ }++ public func task(id: String) -> HarnessTaskState? {+ tasksByID[id]+ }++ public func activeTasks() -> [HarnessTaskState] {+ tasksByID.values+ .filter { [.running, .paused, .waitingForUser, .waitingForPermission, .interrupted, .resuming].contains($0.status) }+ .sorted { $0.createdAt < $1.createdAt }+ }++ public func events(taskID: String) -> [HarnessTaskEvent] {+ eventsByTaskID[taskID] ?? []+ }++ public func updateIntent(+ taskID: String,+ intent: HarnessIntentAnalysis+ ) -> HarnessTaskState? {+ mutate(taskID: taskID, summary: "Intent updated") { task in+ task.intent = intent+ task.goal = intent.goal+ }+ }++ public func updatePlan(+ taskID: String,+ plan: HarnessPlan+ ) -> HarnessTaskState? {+ mutate(taskID: taskID, summary: "Plan updated") { task in+ task.plan = plan+ }+ }++ public func updateWorldModel(+ taskID: String,+ worldModel: HarnessWorldModel+ ) -> HarnessTaskState? {+ mutate(taskID: taskID, summary: "World model updated") { task in+ task.worldModel = worldModel+ }+ }++ public func pause(taskID: String, reason: String = "User paused task") -> HarnessTaskState? {+ setStatus(taskID: taskID, status: .paused, summary: reason)+ }++ public func resume(taskID: String, reason: String = "Task resumed") -> HarnessTaskState? {+ mutate(taskID: taskID, status: .resuming, summary: reason) { task in+ task.pendingContinuation = nil+ }+ }++ public func cancel(taskID: String, reason: String = "Task cancelled") -> HarnessTaskState? {+ mutate(taskID: taskID, status: .cancelled, summary: reason) { task in+ task.pendingContinuation = nil+ }+ }++ public func complete(taskID: String, reason: String = "Task completed") -> HarnessTaskState? {+ mutate(taskID: taskID, status: .completed, summary: reason) { task in+ task.pendingContinuation = nil+ }+ }++ public func failSafe(taskID: String, reason: String) -> HarnessTaskState? {+ mutate(taskID: taskID, status: .failedSafe, summary: reason) { task in+ task.pendingContinuation = nil+ }+ }++ public func interrupt(+ taskID: String,+ newGoal: String,+ turn: AppHarnessTurn? = nil,+ reason: String = "Task interrupted by user"+ ) -> HarnessTaskState? {+ mutate(taskID: taskID, status: .interrupted, summary: reason) { task in+ task.goal = newGoal+ if let turn {+ task.context.turn = turn+ }+ task.plan = nil+ task.pendingContinuation = HarnessPendingContinuation(+ stage: .planning,+ reason: "courseChanged",+ metadata: ["newGoal": newGoal]+ )+ }+ }++ public func waitForUser(+ taskID: String,+ question: String,+ pendingToolCall: HarnessToolCall? = nil,+ reason: String = "Task needs user clarification"+ ) -> HarnessTaskState? {+ mutate(taskID: taskID, status: .waitingForUser, summary: reason) { task in+ task.pendingContinuation = HarnessPendingContinuation(+ stage: .clarification,+ reason: reason,+ question: question,+ pendingToolCall: pendingToolCall+ )+ }+ }++ public func waitForPermission(+ taskID: String,+ missingPermissions: [HarnessPermission],+ pendingToolCall: HarnessToolCall,+ reason: String = "Task needs permission"+ ) -> HarnessTaskState? {+ mutate(taskID: taskID, status: .waitingForPermission, summary: reason) { task in+ task.pendingContinuation = HarnessPendingContinuation(+ stage: .permissionGate,+ reason: reason,+ missingPermissions: missingPermissions,+ pendingToolCall: pendingToolCall+ )+ }+ }++ public func provideUserResponse(+ taskID: String,+ response: String+ ) -> HarnessTaskState? {+ mutate(taskID: taskID, status: .resuming, summary: "User response received") { task in+ task.context.memory.append(response)+ task.worldModel.facts["lastUserClarification"] = response+ task.pendingContinuation = nil+ }+ }++ public func grantPermissions(+ taskID: String,+ permissions: Set<HarnessPermission>+ ) -> HarnessTaskState? {+ mutate(taskID: taskID, status: .resuming, summary: "Permission granted") { task in+ task.grantedPermissions.formUnion(permissions)+ task.pendingContinuation = nil+ }+ }++ public func recordToolResult(+ taskID: String,+ call: HarnessToolCall,+ result: HarnessToolResult+ ) -> HarnessTaskState? {+ mutate(taskID: taskID, status: nil, summary: "Tool result recorded") { task in+ task.toolHistory.append(+ HarnessToolCallRecord(+ call: call,+ resultStatus: result.status,+ summary: result.summary,+ recordedAt: result.completedAt+ )+ )+ task.worldModel = task.worldModel.merging(result: result)+ task.worldModel.attemptedToolCalls = task.toolHistory+ }+ }++ private func setStatus(+ taskID: String,+ status: HarnessTaskStatus,+ summary: String+ ) -> HarnessTaskState? {+ mutate(taskID: taskID, status: status, summary: summary) { _ in }+ }++ private func mutate(+ taskID: String,+ status: HarnessTaskStatus? = nil,+ summary: String,+ mutation: (inout HarnessTaskState) -> Void+ ) -> HarnessTaskState? {+ guard var task = tasksByID[taskID] else { return nil }+ if let status {+ task.status = status+ }+ mutation(&task)+ task.updatedAt = Date()+ tasksByID[taskID] = task+ appendEvent(+ taskID: taskID,+ status: task.status,+ summary: summary+ )+ return task+ }++ private func appendEvent(+ taskID: String,+ status: HarnessTaskStatus,+ summary: String,+ metadata: [String: String] = [:]+ ) {+ var events = eventsByTaskID[taskID] ?? []+ events.append(+ HarnessTaskEvent(+ taskID: taskID,+ status: status,+ summary: summary,+ metadata: metadata+ )+ )+ eventsByTaskID[taskID] = events+ }+}+diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swiftnew file mode 100644index 00000000..3aff0f53--- /dev/null+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift@@ -0,0 +1,154 @@+import Foundation++public struct HarnessStepExecutionResult: Equatable, Sendable {+ public var task: HarnessTaskState+ public var toolResult: HarnessToolResult?+ public var stoppedForGate: Bool++ public init(+ task: HarnessTaskState,+ toolResult: HarnessToolResult? = nil,+ stoppedForGate: Bool = false+ ) {+ self.task = task+ self.toolResult = toolResult+ self.stoppedForGate = stoppedForGate+ }+}++public struct GenericHarnessRuntime: Sendable {+ public var coordinator: HarnessTaskCoordinator+ public var registry: HarnessToolRegistry++ public init(+ coordinator: HarnessTaskCoordinator,+ registry: HarnessToolRegistry+ ) {+ self.coordinator = coordinator+ self.registry = registry+ }++ public func executeToolCall(+ taskID: String,+ call: HarnessToolCall+ ) async -> HarnessStepExecutionResult? {+ guard let task = await coordinator.task(id: taskID) else { return nil }+ guard task.status.canExecuteTools else {+ let result = HarnessToolResult(+ callID: call.id,+ toolName: call.name,+ status: .failed,+ summary: "Task is stopped and cannot execute tools.",+ metadata: [+ "taskStatus": task.status.rawValue,+ "reason": "taskNotExecutable"+ ]+ )+ return HarnessStepExecutionResult(+ task: task,+ toolResult: result,+ stoppedForGate: true+ )+ }++ if call.name == "user.clarify" {+ let question = call.input["question"] ?? "What detail should I use?"+ guard let stoppedTask = await coordinator.waitForUser(+ taskID: taskID,+ question: question,+ pendingToolCall: call+ ) else {+ return nil+ }+ let result = HarnessToolResult(+ callID: call.id,+ toolName: call.name,+ status: .waitingForUser,+ summary: "Task stopped for user clarification.",+ question: question,+ metadata: ["gate": "clarification"]+ )+ return HarnessStepExecutionResult(+ task: stoppedTask,+ toolResult: result,+ stoppedForGate: true+ )+ }++ if call.name == "permission.request" {+ let permission = call.input["permission"].flatMap(HarnessPermission.init(rawValue:))+ let missing = permission.map { [$0] } ?? []+ guard let stoppedTask = await coordinator.waitForPermission(+ taskID: taskID,+ missingPermissions: missing,+ pendingToolCall: call+ ) else {+ return nil+ }+ let result = HarnessToolResult(+ callID: call.id,+ toolName: call.name,+ status: .waitingForPermission,+ summary: "Task stopped for permission.",+ missingPermissions: missing,+ metadata: ["gate": "permission"]+ )+ return HarnessStepExecutionResult(+ task: stoppedTask,+ toolResult: result,+ stoppedForGate: true+ )+ }++ let result = await registry.execute(+ call,+ taskID: taskID,+ worldModel: task.worldModel,+ grantedPermissions: task.grantedPermissions+ )++ if result.status == .permissionDenied {+ guard let stoppedTask = await coordinator.waitForPermission(+ taskID: taskID,+ missingPermissions: result.missingPermissions,+ pendingToolCall: call+ ) else {+ return nil+ }+ return HarnessStepExecutionResult(+ task: stoppedTask,+ toolResult: result,+ stoppedForGate: true+ )+ }++ guard let updatedTask = await coordinator.recordToolResult(+ taskID: taskID,+ call: call,+ result: result+ ) else {+ return nil+ }++ return HarnessStepExecutionResult(+ task: updatedTask,+ toolResult: result,+ stoppedForGate: false+ )+ }++ public func executeNextPlannedStep(taskID: String) async -> HarnessStepExecutionResult? {+ guard let task = await coordinator.task(id: taskID),+ let step = task.plan?.steps.first(where: { step in+ guard let call = step.toolCall else { return false }+ return !task.toolHistory.contains { $0.call.id == call.id }+ }),+ let call = step.toolCall+ else {+ return nil+ }++ return await executeToolCall(taskID: taskID, call: call)+ }+}+diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swiftnew file mode 100644index 00000000..9aeff254--- /dev/null+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift@@ -0,0 +1,471 @@+import Foundation++public enum HarnessSkillSourceKind: String, Codable, Equatable, Sendable {+ case builtIn+ case plugin+ case userDirectory+ case workspace+ case remoteCatalog+}++public struct HarnessSkillDescriptor: Codable, Equatable, Sendable {+ public var id: String+ public var name: String+ public var summary: String+ public var description: String+ public var sourceKind: HarnessSkillSourceKind+ public var instructionPath: String?+ public var tags: [String]+ public var providedToolNames: [String]+ public var scripts: [HarnessSkillScriptDescriptor]+ public var requiredPermissions: [HarnessPermission]+ public var metadata: [String: String]++ public init(+ id: String,+ name: String,+ summary: String,+ description: String = "",+ sourceKind: HarnessSkillSourceKind,+ instructionPath: String? = nil,+ tags: [String] = [],+ providedToolNames: [String] = [],+ scripts: [HarnessSkillScriptDescriptor] = [],+ requiredPermissions: [HarnessPermission] = [],+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.name = name+ self.summary = summary+ self.description = description+ self.sourceKind = sourceKind+ self.instructionPath = instructionPath+ self.tags = Array(Set(tags)).sorted()+ self.providedToolNames = Array(Set(providedToolNames)).sorted()+ self.scripts = scripts.sorted { $0.id < $1.id }+ self.requiredPermissions = requiredPermissions+ self.metadata = metadata+ }+}++public enum HarnessSkillScriptLanguage: String, Codable, Equatable, Sendable {+ case appleScript+ case shell+ case javaScript+ case python+ case swift+ case unknown+}++public enum HarnessSkillScriptValidationStatus: String, Codable, Equatable, Sendable {+ case generated+ case pendingValidation+ case validated+ case rejected+}++public struct HarnessSkillScriptDescriptor: Codable, Equatable, Sendable {+ public var id: String+ public var language: HarnessSkillScriptLanguage+ public var purpose: String+ public var relativePath: String+ public var generatedBy: String?+ public var validationStatus: HarnessSkillScriptValidationStatus+ public var requiredPermissions: [HarnessPermission]+ public var safetyClass: HarnessToolSafetyClass+ public var metadata: [String: String]++ public init(+ id: String,+ language: HarnessSkillScriptLanguage,+ purpose: String,+ relativePath: String,+ generatedBy: String? = nil,+ validationStatus: HarnessSkillScriptValidationStatus = .pendingValidation,+ requiredPermissions: [HarnessPermission] = [],+ safetyClass: HarnessToolSafetyClass = .sensitive,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.language = language+ self.purpose = purpose+ self.relativePath = relativePath+ self.generatedBy = generatedBy+ self.validationStatus = validationStatus+ self.requiredPermissions = requiredPermissions+ self.safetyClass = safetyClass+ self.metadata = metadata+ }+}++public struct HarnessSkillSearchResult: Codable, Equatable, Sendable {+ public var descriptor: HarnessSkillDescriptor+ public var score: Int+ public var matchedFields: [String]++ public init(+ descriptor: HarnessSkillDescriptor,+ score: Int,+ matchedFields: [String]+ ) {+ self.descriptor = descriptor+ self.score = score+ self.matchedFields = Array(Set(matchedFields)).sorted()+ }+}++public actor HarnessSkillRegistry {+ private var skillsByID: [String: HarnessSkillDescriptor]++ public init(skills: [HarnessSkillDescriptor] = []) {+ self.skillsByID = Dictionary(uniqueKeysWithValues: skills.map { ($0.id, $0) })+ }++ public func register(_ skill: HarnessSkillDescriptor) {+ skillsByID[skill.id] = skill+ }++ public func register(contentsOf skills: [HarnessSkillDescriptor]) {+ for skill in skills {+ skillsByID[skill.id] = skill+ }+ }++ public func descriptor(id: String) -> HarnessSkillDescriptor? {+ skillsByID[id]+ }++ public func descriptors() -> [HarnessSkillDescriptor] {+ skillsByID.values.sorted {+ if $0.name == $1.name {+ return $0.id < $1.id+ }+ return $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending+ }+ }++ public func search(+ query: String,+ limit: Int = 8+ ) -> [HarnessSkillSearchResult] {+ let tokens = Self.tokens(query)+ guard !tokens.isEmpty else {+ return Array(descriptors().prefix(max(0, limit))).map {+ HarnessSkillSearchResult(descriptor: $0, score: 0, matchedFields: [])+ }+ }++ return skillsByID.values.compactMap { skill in+ let scored = Self.score(skill: skill, tokens: tokens)+ guard scored.score > 0 else { return nil }+ return HarnessSkillSearchResult(+ descriptor: skill,+ score: scored.score,+ matchedFields: scored.fields+ )+ }+ .sorted {+ if $0.score == $1.score {+ return $0.descriptor.name < $1.descriptor.name+ }+ return $0.score > $1.score+ }+ .prefix(max(0, limit))+ .map { $0 }+ }++ private static func score(+ skill: HarnessSkillDescriptor,+ tokens: [String]+ ) -> (score: Int, fields: [String]) {+ var score = 0+ var fields: [String] = []+ for token in tokens {+ if normalized(skill.name).contains(token) {+ score += 8+ fields.append("name")+ }+ if normalized(skill.id).contains(token) {+ score += 6+ fields.append("id")+ }+ if normalized(skill.summary).contains(token) {+ score += 4+ fields.append("summary")+ }+ if normalized(skill.description).contains(token) {+ score += 2+ fields.append("description")+ }+ if skill.tags.contains(where: { normalized($0).contains(token) }) {+ score += 3+ fields.append("tags")+ }+ if skill.providedToolNames.contains(where: { normalized($0).contains(token) }) {+ score += 3+ fields.append("tools")+ }+ }+ return (score, fields)+ }++ private static func tokens(_ value: String) -> [String] {+ normalized(value)+ .split(separator: " ")+ .map(String.init)+ }++ private static func normalized(_ value: String) -> String {+ value.lowercased()+ .map { character in+ character.isLetter || character.isNumber ? character : " "+ }+ .reduce(into: "") { result, character in+ if character == " ", result.last == " " {+ return+ }+ result.append(character)+ }+ .trimmingCharacters(in: .whitespacesAndNewlines)+ }+}++public struct HarnessSkillFileSystemSource: Sendable {+ public var roots: [URL]+ public var maxDepth: Int++ public init(+ roots: [URL],+ maxDepth: Int = 4+ ) {+ self.roots = roots+ self.maxDepth = max(0, maxDepth)+ }++ public func discover() -> [HarnessSkillDescriptor] {+ roots.flatMap { root in+ discover(in: root)+ }+ .sorted {+ if $0.name == $1.name {+ return $0.id < $1.id+ }+ return $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending+ }+ }++ private func discover(in root: URL) -> [HarnessSkillDescriptor] {+ let fileManager = FileManager.default+ var isDirectory: ObjCBool = false+ guard fileManager.fileExists(atPath: root.path, isDirectory: &isDirectory),+ isDirectory.boolValue+ else {+ return []+ }++ var descriptors: [HarnessSkillDescriptor] = []+ if let rootSkill = descriptor(forSkillMarkdownAt: root.appendingPathComponent("SKILL.md")) {+ descriptors.append(rootSkill)+ }++ guard let enumerator = fileManager.enumerator(+ at: root,+ includingPropertiesForKeys: [.isDirectoryKey],+ options: [.skipsHiddenFiles, .skipsPackageDescendants]+ ) else {+ return descriptors+ }++ for case let url as URL in enumerator {+ let depth = relativeDepth(of: url, from: root)+ if depth > maxDepth {+ enumerator.skipDescendants()+ continue+ }+ guard url.lastPathComponent == "SKILL.md",+ url != root.appendingPathComponent("SKILL.md"),+ let descriptor = descriptor(forSkillMarkdownAt: url)+ else {+ continue+ }+ descriptors.append(descriptor)+ }++ return descriptors+ }++ private func descriptor(forSkillMarkdownAt url: URL) -> HarnessSkillDescriptor? {+ let fileManager = FileManager.default+ guard fileManager.fileExists(atPath: url.path),+ let contents = try? String(contentsOf: url, encoding: .utf8)+ else {+ return nil+ }++ let directory = url.deletingLastPathComponent()+ let directoryName = directory.lastPathComponent+ let name = firstMarkdownHeading(in: contents) ?? titleCased(directoryName)+ let summary = metadataLine(named: "description", in: contents)+ ?? firstNonEmptyBodyLine(in: contents)+ ?? "Skill instructions for \(name)."+ let tags = metadataList(named: "tags", in: contents)+ let toolNames = metadataList(named: "tools", in: contents)+ let id = metadataLine(named: "id", in: contents)+ ?? slug(directoryName.isEmpty ? name : directoryName)++ return HarnessSkillDescriptor(+ id: id,+ name: name,+ summary: summary,+ description: contents,+ sourceKind: .userDirectory,+ instructionPath: url.path,+ tags: tags,+ providedToolNames: toolNames,+ scripts: scriptDescriptors(in: directory),+ metadata: [+ "source": "filesystem",+ "directory": directory.path+ ]+ )+ }++ private func metadataLine(named key: String, in contents: String) -> String? {+ let normalizedKey = key.lowercased()+ for line in contents.split(whereSeparator: \.isNewline).map(String.init).prefix(40) {+ let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)+ let lowered = trimmed.lowercased()+ guard lowered.hasPrefix("\(normalizedKey):") else { continue }+ let value = String(trimmed.dropFirst(key.count + 1))+ .trimmingCharacters(in: .whitespacesAndNewlines)+ return value.isEmpty ? nil : value+ }+ return nil+ }++ private func metadataList(named key: String, in contents: String) -> [String] {+ guard let line = metadataLine(named: key, in: contents) else { return [] }+ return line+ .split(separator: ",")+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter { !$0.isEmpty }+ }++ private func firstMarkdownHeading(in contents: String) -> String? {+ for line in contents.split(whereSeparator: \.isNewline).map(String.init).prefix(20) {+ let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)+ guard trimmed.hasPrefix("# ") else { continue }+ let heading = String(trimmed.dropFirst(2)).trimmingCharacters(in: .whitespacesAndNewlines)+ return heading.isEmpty ? nil : heading+ }+ return nil+ }++ private func firstNonEmptyBodyLine(in contents: String) -> String? {+ for line in contents.split(whereSeparator: \.isNewline).map(String.init).prefix(80) {+ let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)+ if trimmed.isEmpty || trimmed.hasPrefix("#") || trimmed.contains(":") {+ continue+ }+ return trimmed+ }+ return nil+ }++ private func scriptDescriptors(in skillDirectory: URL) -> [HarnessSkillScriptDescriptor] {+ let scriptsDirectory = skillDirectory.appendingPathComponent("scripts", isDirectory: true)+ var isDirectory: ObjCBool = false+ guard FileManager.default.fileExists(atPath: scriptsDirectory.path, isDirectory: &isDirectory),+ isDirectory.boolValue,+ let enumerator = FileManager.default.enumerator(+ at: scriptsDirectory,+ includingPropertiesForKeys: [.isRegularFileKey],+ options: [.skipsHiddenFiles, .skipsPackageDescendants]+ )+ else {+ return []+ }++ return enumerator.compactMap { item -> HarnessSkillScriptDescriptor? in+ guard let url = item as? URL,+ let values = try? url.resourceValues(forKeys: [.isRegularFileKey]),+ values.isRegularFile == true,+ let language = scriptLanguage(for: url)+ else {+ return nil+ }++ let relativePath = relativePath(of: url, from: skillDirectory)+ let basename = url.deletingPathExtension().lastPathComponent+ return HarnessSkillScriptDescriptor(+ id: slug(relativePath),+ language: language,+ purpose: titleCased(basename),+ relativePath: relativePath,+ validationStatus: .pendingValidation,+ requiredPermissions: requiredPermissions(for: language),+ safetyClass: language == .appleScript ? .guardedInput : .sensitive,+ metadata: [+ "source": "filesystem",+ "scriptDirectory": scriptsDirectory.path+ ]+ )+ }+ .sorted { $0.id < $1.id }+ }++ private func scriptLanguage(for url: URL) -> HarnessSkillScriptLanguage? {+ switch url.pathExtension.lowercased() {+ case "applescript", "scpt":+ return .appleScript+ case "sh", "bash", "zsh":+ return .shell+ case "js", "mjs":+ return .javaScript+ case "py":+ return .python+ case "swift":+ return .swift+ default:+ return nil+ }+ }++ private func requiredPermissions(for language: HarnessSkillScriptLanguage) -> [HarnessPermission] {+ switch language {+ case .appleScript:+ return [.appControl, .input]+ case .shell, .javaScript, .python, .swift:+ return [.input]+ case .unknown:+ return []+ }+ }++ private func relativePath(of url: URL, from root: URL) -> String {+ let rootPath = root.standardizedFileURL.path+ let path = url.standardizedFileURL.path+ guard path.hasPrefix(rootPath) else { return url.lastPathComponent }+ return String(path.dropFirst(rootPath.count))+ .trimmingCharacters(in: CharacterSet(charactersIn: "/"))+ }++ private func relativeDepth(of url: URL, from root: URL) -> Int {+ let rootComponents = root.standardizedFileURL.pathComponents+ let components = url.standardizedFileURL.pathComponents+ return max(0, components.count - rootComponents.count)+ }++ private func titleCased(_ value: String) -> String {+ value+ .split { !$0.isLetter && !$0.isNumber }+ .map { word in word.prefix(1).uppercased() + word.dropFirst() }+ .joined(separator: " ")+ }++ private func slug(_ value: String) -> String {+ value.lowercased()+ .split { !$0.isLetter && !$0.isNumber }+ .joined(separator: "-")+ }+}diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessThreadStore.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessThreadStore.swiftnew file mode 100644index 00000000..7696322d--- /dev/null+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessThreadStore.swift@@ -0,0 +1,407 @@+import DonkeyContracts+import Foundation++public enum HarnessThreadEventRole: String, Codable, Equatable, Sendable {+ case user+ case assistant+ case system+ case tool+ case lifecycle+ case summary+}++public struct HarnessThread: Codable, Equatable, Sendable {+ public var id: String+ public var title: String+ public var status: HarnessTaskStatus+ public var activeTaskIDs: [String]+ public var createdAt: Date+ public var updatedAt: Date+ public var metadata: [String: String]++ public init(+ id: String = UUID().uuidString,+ title: String,+ status: HarnessTaskStatus = .running,+ activeTaskIDs: [String] = [],+ createdAt: Date = Date(),+ updatedAt: Date = Date(),+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.title = title+ self.status = status+ self.activeTaskIDs = activeTaskIDs+ self.createdAt = createdAt+ self.updatedAt = updatedAt+ self.metadata = metadata+ }+}++public struct HarnessThreadEvent: Codable, Equatable, Sendable, Identifiable {+ public var id: String+ public var threadID: String+ public var taskID: String?+ public var role: HarnessThreadEventRole+ public var text: String+ public var sequence: Int+ public var isPinned: Bool+ public var createdAt: Date+ public var metadata: [String: String]++ public init(+ id: String = UUID().uuidString,+ threadID: String,+ taskID: String? = nil,+ role: HarnessThreadEventRole,+ text: String,+ sequence: Int,+ isPinned: Bool = false,+ createdAt: Date = Date(),+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.threadID = threadID+ self.taskID = taskID+ self.role = role+ self.text = text+ self.sequence = sequence+ self.isPinned = isPinned+ self.createdAt = createdAt+ self.metadata = metadata+ }+}++public struct HarnessThreadAsset: Codable, Equatable, Sendable, Identifiable {+ public var id: String+ public var threadID: String+ public var taskID: String?+ public var eventID: String?+ public var displayName: String+ public var contentType: String+ public var urlString: String+ public var byteCount: Int64?+ public var createdAt: Date+ public var metadata: [String: String]++ public init(+ id: String = UUID().uuidString,+ threadID: String,+ taskID: String? = nil,+ eventID: String? = nil,+ displayName: String,+ contentType: String,+ urlString: String,+ byteCount: Int64? = nil,+ createdAt: Date = Date(),+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.threadID = threadID+ self.taskID = taskID+ self.eventID = eventID+ self.displayName = displayName+ self.contentType = contentType+ self.urlString = urlString+ self.byteCount = byteCount+ self.createdAt = createdAt+ self.metadata = metadata+ }+}++public protocol HarnessThreadStoring: Sendable {+ func upsertThread(_ thread: HarnessThread) async+ func thread(id: String) async -> HarnessThread?+ func recentThreads(limit: Int) async -> [HarnessThread]+ func appendEvent(_ event: HarnessThreadEvent) async+ func events(threadID: String) async -> [HarnessThreadEvent]+ func appendAsset(_ asset: HarnessThreadAsset) async+ func assets(threadID: String) async -> [HarnessThreadAsset]+}++public actor InMemoryHarnessThreadStore: HarnessThreadStoring {+ private var threadsByID: [String: HarnessThread] = [:]+ private var eventsByThreadID: [String: [HarnessThreadEvent]] = [:]+ private var assetsByThreadID: [String: [HarnessThreadAsset]] = [:]++ public init() {}++ public func upsertThread(_ thread: HarnessThread) {+ threadsByID[thread.id] = thread+ }++ public func thread(id: String) -> HarnessThread? {+ threadsByID[id]+ }++ public func recentThreads(limit: Int) -> [HarnessThread] {+ threadsByID.values+ .sorted { $0.updatedAt > $1.updatedAt }+ .prefix(max(0, limit))+ .map { $0 }+ }++ public func appendEvent(_ event: HarnessThreadEvent) {+ var events = eventsByThreadID[event.threadID] ?? []+ events.append(event)+ events.sort {+ if $0.sequence == $1.sequence {+ return $0.createdAt < $1.createdAt+ }+ return $0.sequence < $1.sequence+ }+ eventsByThreadID[event.threadID] = events+ }++ public func events(threadID: String) -> [HarnessThreadEvent] {+ eventsByThreadID[threadID] ?? []+ }++ public func appendAsset(_ asset: HarnessThreadAsset) {+ var assets = assetsByThreadID[asset.threadID] ?? []+ assets.append(asset)+ assets.sort { $0.createdAt < $1.createdAt }+ assetsByThreadID[asset.threadID] = assets+ }++ public func assets(threadID: String) -> [HarnessThreadAsset] {+ assetsByThreadID[threadID] ?? []+ }+}++public struct HarnessCompactionPolicy: Codable, Equatable, Sendable {+ public var maxEvents: Int+ public var maxPinnedEvents: Int+ public var maxToolEvents: Int+ public var maxAssets: Int+ public var maxEventCharacters: Int+ public var maxPromptCharacters: Int+ public var preserveWaitingState: Bool++ public init(+ maxEvents: Int = 12,+ maxPinnedEvents: Int = 6,+ maxToolEvents: Int = 4,+ maxAssets: Int = 6,+ maxEventCharacters: Int = 1_000,+ maxPromptCharacters: Int = 8_000,+ preserveWaitingState: Bool = true+ ) {+ self.maxEvents = max(0, maxEvents)+ self.maxPinnedEvents = max(0, maxPinnedEvents)+ self.maxToolEvents = max(0, maxToolEvents)+ self.maxAssets = max(0, maxAssets)+ self.maxEventCharacters = max(1, maxEventCharacters)+ self.maxPromptCharacters = max(1, maxPromptCharacters)+ self.preserveWaitingState = preserveWaitingState+ }+}++public struct HarnessCompactedThreadContext: Codable, Equatable, Sendable {+ public var thread: HarnessThread+ public var currentTurn: AppHarnessTurn?+ public var events: [HarnessThreadEvent]+ public var assets: [HarnessThreadAsset]+ public var activeTasks: [HarnessTaskState]+ public var promptText: String+ public var compactionRecords: [AppHarnessContextCompactionRecord]+ public var metadata: [String: String]++ public init(+ thread: HarnessThread,+ currentTurn: AppHarnessTurn? = nil,+ events: [HarnessThreadEvent],+ assets: [HarnessThreadAsset],+ activeTasks: [HarnessTaskState],+ promptText: String,+ compactionRecords: [AppHarnessContextCompactionRecord],+ metadata: [String: String] = [:]+ ) {+ self.thread = thread+ self.currentTurn = currentTurn+ self.events = events+ self.assets = assets+ self.activeTasks = activeTasks+ self.promptText = promptText+ self.compactionRecords = compactionRecords+ self.metadata = metadata+ }+}++public struct HarnessThreadCompactor: Sendable {+ public var policy: HarnessCompactionPolicy++ public init(policy: HarnessCompactionPolicy = HarnessCompactionPolicy()) {+ self.policy = policy+ }++ public func compact(+ thread: HarnessThread,+ currentTurn: AppHarnessTurn? = nil,+ events: [HarnessThreadEvent],+ assets: [HarnessThreadAsset],+ activeTasks: [HarnessTaskState]+ ) -> HarnessCompactedThreadContext {+ var records: [AppHarnessContextCompactionRecord] = []+ let selectedEvents = compactEvents(events, records: &records)+ let selectedAssets = Array(assets.sorted { $0.createdAt > $1.createdAt }.prefix(policy.maxAssets))+ .sorted { $0.createdAt < $1.createdAt }+ records.append(+ AppHarnessContextCompactionRecord(+ itemKind: .asset,+ originalCount: assets.count,+ includedCount: selectedAssets.count,+ droppedCount: max(0, assets.count - selectedAssets.count)+ )+ )++ let selectedTasks = compactTasks(activeTasks, records: &records)+ let unboundedPrompt = promptText(+ thread: thread,+ currentTurn: currentTurn,+ events: selectedEvents,+ assets: selectedAssets,+ activeTasks: selectedTasks+ )+ let boundedPrompt = bounded(unboundedPrompt, maxCharacters: policy.maxPromptCharacters)+ records.append(+ AppHarnessContextCompactionRecord(+ itemKind: .currentTurn,+ originalCount: unboundedPrompt.count,+ includedCount: boundedPrompt.count,+ truncatedCount: unboundedPrompt.count > boundedPrompt.count ? 1 : 0,+ metadata: ["unit": "characters"]+ )+ )++ return HarnessCompactedThreadContext(+ thread: thread,+ currentTurn: currentTurn,+ events: selectedEvents,+ assets: selectedAssets,+ activeTasks: selectedTasks,+ promptText: boundedPrompt,+ compactionRecords: records,+ metadata: [+ "threadStore": "generic-harness",+ "compactor": "smart-priority-v1",+ "promptTruncated": String(unboundedPrompt.count > boundedPrompt.count),+ "eventCount": String(selectedEvents.count),+ "assetCount": String(selectedAssets.count),+ "activeTaskCount": String(selectedTasks.count)+ ]+ )+ }++ private func compactEvents(+ _ events: [HarnessThreadEvent],+ records: inout [AppHarnessContextCompactionRecord]+ ) -> [HarnessThreadEvent] {+ let sorted = events.sorted {+ if $0.sequence == $1.sequence {+ return $0.createdAt < $1.createdAt+ }+ return $0.sequence < $1.sequence+ }+ let pinned = sorted.filter(\.isPinned).suffix(policy.maxPinnedEvents)+ let summaries = sorted.filter { $0.role == .summary }.suffix(2)+ let toolEvents = sorted.filter { $0.role == .tool }.suffix(policy.maxToolEvents)+ let recent = sorted.suffix(policy.maxEvents)+ let selectedIDs = Set((pinned + summaries + toolEvents + recent).map(\.id))+ let selected = sorted+ .filter { selectedIDs.contains($0.id) }+ .map { event in+ var event = event+ event.text = bounded(event.text, maxCharacters: policy.maxEventCharacters)+ return event+ }+ records.append(+ AppHarnessContextCompactionRecord(+ itemKind: .recentEvent,+ originalCount: events.count,+ includedCount: selected.count,+ droppedCount: max(0, events.count - selected.count),+ truncatedCount: selected.filter { selectedEvent in+ events.first(where: { $0.id == selectedEvent.id })?.text.count ?? 0 > selectedEvent.text.count+ }.count,+ metadata: [+ "strategy": "pinned+summary+tool+recent",+ "maxEvents": String(policy.maxEvents),+ "maxPinnedEvents": String(policy.maxPinnedEvents),+ "maxToolEvents": String(policy.maxToolEvents)+ ]+ )+ )+ return selected+ }++ private func compactTasks(+ _ tasks: [HarnessTaskState],+ records: inout [AppHarnessContextCompactionRecord]+ ) -> [HarnessTaskState] {+ let selected = tasks.filter { task in+ guard policy.preserveWaitingState else { return true }+ return [.running, .paused, .waitingForUser, .waitingForPermission, .interrupted, .resuming].contains(task.status)+ }+ records.append(+ AppHarnessContextCompactionRecord(+ itemKind: .targetState,+ originalCount: tasks.count,+ includedCount: selected.count,+ droppedCount: max(0, tasks.count - selected.count),+ metadata: ["strategy": "preserveActiveAndWaitingTasks"]+ )+ )+ return selected+ }++ private func promptText(+ thread: HarnessThread,+ currentTurn: AppHarnessTurn?,+ events: [HarnessThreadEvent],+ assets: [HarnessThreadAsset],+ activeTasks: [HarnessTaskState]+ ) -> String {+ var lines: [String] = [+ "Thread: \(thread.title)",+ "Thread status: \(thread.status.rawValue)"+ ]+ if let currentTurn {+ lines.append("Current turn: \(currentTurn.text)")+ }+ if !activeTasks.isEmpty {+ lines.append("Active tasks:")+ for task in activeTasks {+ lines.append("- \(task.id) status=\(task.status.rawValue) goal=\(task.goal)")+ if let continuation = task.pendingContinuation {+ lines.append(" pending=\(continuation.stage.rawValue) reason=\(continuation.reason)")+ if let question = continuation.question {+ lines.append(" question=\(question)")+ }+ if !continuation.missingPermissions.isEmpty {+ lines.append(" missingPermissions=\(continuation.missingPermissions.map(\.rawValue).joined(separator: ","))")+ }+ }+ }+ }+ if !events.isEmpty {+ lines.append("Thread events:")+ for event in events {+ lines.append("- [\(event.sequence)] \(event.role.rawValue): \(event.text)")+ }+ }+ if !assets.isEmpty {+ lines.append("Assets:")+ for asset in assets {+ lines.append("- \(asset.displayName) \(asset.contentType) \(asset.urlString)")+ }+ }+ return lines.joined(separator: "\n")+ }++ private func bounded(_ value: String, maxCharacters: Int) -> String {+ guard value.count > maxCharacters else { return value }+ return String(value.prefix(maxCharacters))+ }+}+diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swiftnew file mode 100644index 00000000..54b30907--- /dev/null+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift@@ -0,0 +1,444 @@+import Foundation++public struct HarnessToolDescriptor: Codable, Equatable, Sendable {+ public var name: String+ public var pluginID: String+ public var summary: String+ public var inputSchema: [String: String]+ public var outputSchema: [String: String]+ public var requiredPermissions: [HarnessPermission]+ public var safetyClass: HarnessToolSafetyClass+ public var requiredContext: [String]+ public var verificationHints: [String]+ public var metadata: [String: String]++ public init(+ name: String,+ pluginID: String,+ summary: String,+ inputSchema: [String: String] = [:],+ outputSchema: [String: String] = [:],+ requiredPermissions: [HarnessPermission] = [],+ safetyClass: HarnessToolSafetyClass,+ requiredContext: [String] = [],+ verificationHints: [String] = [],+ metadata: [String: String] = [:]+ ) {+ self.name = name+ self.pluginID = pluginID+ self.summary = summary+ self.inputSchema = inputSchema+ self.outputSchema = outputSchema+ self.requiredPermissions = requiredPermissions+ self.safetyClass = safetyClass+ self.requiredContext = requiredContext+ self.verificationHints = verificationHints+ self.metadata = metadata+ }+}++public struct HarnessToolExecutionContext: Sendable {+ public var taskID: String+ public var call: HarnessToolCall+ public var descriptor: HarnessToolDescriptor+ public var worldModel: HarnessWorldModel+ public var grantedPermissions: Set<HarnessPermission>++ public init(+ taskID: String,+ call: HarnessToolCall,+ descriptor: HarnessToolDescriptor,+ worldModel: HarnessWorldModel,+ grantedPermissions: Set<HarnessPermission>+ ) {+ self.taskID = taskID+ self.call = call+ self.descriptor = descriptor+ self.worldModel = worldModel+ self.grantedPermissions = grantedPermissions+ }+}++public typealias HarnessToolExecutor = @Sendable (HarnessToolExecutionContext) async -> HarnessToolResult++public struct HarnessTool: Sendable {+ public var descriptor: HarnessToolDescriptor+ public var execute: HarnessToolExecutor++ public init(+ descriptor: HarnessToolDescriptor,+ execute: @escaping HarnessToolExecutor+ ) {+ self.descriptor = descriptor+ self.execute = execute+ }+}++public actor HarnessToolRegistry {+ private var toolsByName: [String: HarnessTool]++ public init(tools: [HarnessTool] = []) {+ self.toolsByName = Dictionary(uniqueKeysWithValues: tools.map { ($0.descriptor.name, $0) })+ }++ public func register(_ tool: HarnessTool) {+ toolsByName[tool.descriptor.name] = tool+ }++ public func descriptor(named name: String) -> HarnessToolDescriptor? {+ toolsByName[name]?.descriptor+ }++ public func descriptors() -> [HarnessToolDescriptor] {+ toolsByName.values+ .map(\.descriptor)+ .sorted { $0.name < $1.name }+ }++ public func execute(+ _ call: HarnessToolCall,+ taskID: String,+ worldModel: HarnessWorldModel,+ grantedPermissions: Set<HarnessPermission>+ ) async -> HarnessToolResult {+ guard let tool = toolsByName[call.name] else {+ return HarnessToolResult(+ callID: call.id,+ toolName: call.name,+ status: .unknownTool,+ summary: "Unknown harness tool: \(call.name)",+ metadata: ["reason": "unknownTool"]+ )+ }++ let missingPermissions = tool.descriptor.requiredPermissions.filter {+ !grantedPermissions.contains($0)+ }+ guard missingPermissions.isEmpty else {+ return HarnessToolResult(+ callID: call.id,+ toolName: call.name,+ status: .permissionDenied,+ summary: "Tool requires permission before it can run.",+ missingPermissions: missingPermissions,+ metadata: [+ "reason": "missingPermission",+ "requiredPermissions": missingPermissions.map(\.rawValue).joined(separator: ",")+ ]+ )+ }++ return await tool.execute(+ HarnessToolExecutionContext(+ taskID: taskID,+ call: call,+ descriptor: tool.descriptor,+ worldModel: worldModel,+ grantedPermissions: grantedPermissions+ )+ )+ }+}++public enum BuiltInHarnessToolCatalog {+ public static var descriptors: [HarnessToolDescriptor] {+ [+ descriptor(+ "conversation.respond",+ pluginID: "core.conversation",+ summary: "Respond conversationally without taking external action.",+ permissions: [.conversation],+ safety: .readOnly+ ),+ descriptor(+ "user.clarify",+ pluginID: "core.user",+ summary: "Ask the user a specific missing question and stop the task until the answer arrives.",+ input: ["question": "Specific question to ask the user."],+ permissions: [.userPrompt],+ safety: .readOnly+ ),+ descriptor(+ "permission.request",+ pluginID: "core.permission",+ summary: "Ask for a missing runtime permission and stop the task until approval arrives.",+ input: ["permission": "Permission name requested by the tool or plan."],+ permissions: [.userPrompt],+ safety: .readOnly+ ),+ descriptor(+ "memory.retrieve",+ pluginID: "core.memory",+ summary: "Retrieve task-relevant memory after intent is structured.",+ input: ["query": "Structured memory query or target scope."],+ output: ["memory": "Bounded memory snippets."],+ permissions: [.memory],+ safety: .readOnly+ ),+ descriptor(+ "skill.search",+ pluginID: "core.skills",+ summary: "Search registered and discovered skills by structured task need before planning tool use.",+ input: ["query": "Structured skill need, target domain, or capability."],+ output: ["skills": "Ranked skill descriptors with instruction paths and provided tools."],+ permissions: [.skillLookup],+ safety: .readOnly,+ verification: ["planner receives only skill descriptors until a skill is explicitly loaded"]+ ),+ descriptor(+ "skill.load",+ pluginID: "core.skills",+ summary: "Load the selected skill instructions into bounded planning context.",+ input: ["skillID": "Registered skill identifier."],+ output: ["instructions": "Bounded skill instruction excerpt and metadata."],+ permissions: [.skillLookup],+ safety: .readOnly,+ requiredContext: ["registered skill descriptor"]+ ),+ descriptor(+ "skill.script.generate",+ pluginID: "core.skills",+ summary: "Ask a model boundary to generate a reusable script artifact inside a skill pack.",+ input: [+ "skillID": "Skill pack that should own the generated script.",+ "language": "Script language such as AppleScript, shell, JavaScript, Python, or Swift.",+ "purpose": "Reusable task capability the script should provide.",+ "constraints": "Allowed actions, inputs, outputs, and safety boundaries.",+ "verification": "How future agents should verify the script worked."+ ],+ output: [+ "scriptID": "Registered skill script identifier.",+ "relativePath": "Skill-relative script path.",+ "scriptSource": "Generated script source for validation/review."+ ],+ permissions: [.skillLookup],+ safety: .sensitive,+ requiredContext: ["loaded skill descriptor", "structured task capability", "model generation boundary"],+ verification: ["script artifact is stored as pendingValidation and is not executable yet"],+ metadata: [+ "modelBoundary": "required",+ "directExecution": "false"+ ]+ ),+ descriptor(+ "skill.script.validate",+ pluginID: "core.skills",+ summary: "Validate or reject a generated skill script before any execution path may use it.",+ input: [+ "skillID": "Skill pack that owns the script.",+ "scriptID": "Generated script identifier.",+ "validationPolicy": "Static checks, allowed APIs, target app, permissions, and review state."+ ],+ output: ["validationStatus": "validated or rejected with reason."],+ permissions: [.skillLookup],+ safety: .readOnly,+ requiredContext: ["generated script artifact", "validation policy"],+ verification: ["validated scripts record provenance and policy metadata"]+ ),+ descriptor(+ "skill.script.execute",+ pluginID: "core.skills",+ summary: "Execute a validated script from a loaded skill through the appropriate guarded backend.",+ input: [+ "skillID": "Skill pack that owns the script.",+ "scriptID": "Validated script identifier.",+ "input": "Structured script input."+ ],+ output: ["result": "Execution trace and structured observations."],+ permissions: [.appControl, .input],+ safety: .guardedInput,+ requiredContext: ["loaded skill descriptor", "validated script descriptor", "permission gate"],+ verification: ["post-execution verifier confirms expected outcome"],+ metadata: [+ "requiresValidatedScript": "true",+ "directModelScriptExecution": "false"+ ]+ ),+ descriptor(+ "app.search",+ pluginID: "core.computer-use",+ summary: "Search installed apps, running apps, files, folders, default handlers, and capability catalog entries.",+ input: ["query": "Structured app/item/capability query."],+ output: ["matches": "Ranked local apps/items/capabilities."],+ permissions: [.appLookup],+ safety: .readOnly+ ),+ descriptor(+ "app.openOrFocus",+ pluginID: "core.computer-use",+ summary: "Open or focus a validated local app or item.",+ input: ["targetID": "Resolved app or local item target."],+ output: ["focusedApp": "Focused application after the action."],+ permissions: [.appControl],+ safety: .reversible,+ verification: ["focused app or opened local item is observed"]+ ),+ descriptor(+ "screen.observe",+ pluginID: "core.computer-use",+ summary: "Observe current screen/window state with bounded Accessibility and screenshot evidence.",+ output: ["worldModel": "Visible text, window facts, and evidence metadata."],+ permissions: [.screenCapture],+ safety: .readOnly+ ),+ descriptor(+ "elements.get",+ pluginID: "core.computer-use",+ summary: "Return visible UI elements, preferring Accessibility-backed actionable elements.",+ input: ["scope": "Target app/window or visible screen scope."],+ output: ["elements": "Element IDs, labels, roles, actions, and eligibility."],+ permissions: [.accessibility],+ safety: .readOnly+ ),+ descriptor(+ "element.perform",+ pluginID: "core.computer-use",+ summary: "Perform a guarded action on an Accessibility-backed element.",+ input: [+ "elementID": "Stable element ID from elements.get.",+ "action": "Press, setValue, focus, scroll, or equivalent guarded action."+ ],+ output: ["result": "Action trace and post-action observations."],+ permissions: [.accessibility, .input],+ safety: .guardedInput,+ requiredContext: ["focused target", "action-eligible element"],+ verification: ["post-action observation confirms expected state"]+ ),+ descriptor(+ "text.enter",+ pluginID: "core.computer-use",+ summary: "Enter exact text into the currently focused or resolved text element.",+ input: ["text": "Exact text to enter."],+ permissions: [.input],+ safety: .guardedInput,+ requiredContext: ["focused text field or explicit element ID"]+ ),+ descriptor(+ "keyboard.press",+ pluginID: "core.computer-use",+ summary: "Press a validated keyboard key or shortcut.",+ input: ["key": "Key or shortcut to press."],+ permissions: [.input],+ safety: .guardedInput,+ requiredContext: ["focused target"]+ ),+ descriptor(+ "automation.applescript.generate",+ pluginID: "core.automation",+ summary: "Ask a model boundary to generate a bounded AppleScript artifact for a resolved app task.",+ input: [+ "targetApp": "Resolved app name and bundle identifier.",+ "goal": "Structured task goal.",+ "entities": "Resolved task entities.",+ "allowedActions": "Allowed AppleScript actions and constraints.",+ "verification": "Expected verification signal after execution."+ ],+ output: [+ "scriptArtifactID": "Generated script artifact identifier.",+ "scriptSource": "Bounded AppleScript source for validation/review."+ ],+ permissions: [.appLookup],+ safety: .sensitive,+ requiredContext: ["structured intent", "resolved target app", "allowed backend policy"],+ verification: ["script source validates against target app and allowed action metadata"],+ metadata: [+ "modelBoundary": "required",+ "directExecution": "false"+ ]+ ),+ descriptor(+ "automation.applescript.execute",+ pluginID: "core.automation",+ summary: "Execute a validated/generated/user-reviewed AppleScript artifact through the guarded automation backend.",+ input: [+ "scriptArtifactID": "Generated or reviewed script artifact identifier.",+ "targetApp": "Resolved app name and bundle identifier."+ ],+ output: ["result": "Execution trace and structured observation."],+ permissions: [.appControl, .input],+ safety: .guardedInput,+ requiredContext: ["validated script artifact", "focused or resolvable target app"],+ verification: ["post-execution verifier confirms expected outcome"],+ metadata: [+ "requiresGeneratedArtifact": "true",+ "requiresValidation": "true"+ ]+ ),+ descriptor(+ "state.verify",+ pluginID: "core.verification",+ summary: "Verify the expected outcome using world-model evidence and task-specific success criteria.",+ input: ["criteria": "Expected visible state, tool result, app state, or artifact state."],+ output: ["verified": "Boolean-like verification result with evidence."],+ permissions: [.verification],+ safety: .readOnly+ ),+ descriptor(+ "run.pause",+ pluginID: "core.lifecycle",+ summary: "Pause a running task.",+ permissions: [.lifecycle],+ safety: .readOnly+ ),+ descriptor(+ "run.resume",+ pluginID: "core.lifecycle",+ summary: "Resume a paused or waiting task from its checkpoint.",+ permissions: [.lifecycle],+ safety: .readOnly+ ),+ descriptor(+ "run.recover",+ pluginID: "core.lifecycle",+ summary: "Recover from a failed verification by re-observing, replanning, or falling back.",+ permissions: [.lifecycle],+ safety: .readOnly+ )+ ]+ }++ public static func registryWithStubExecutors() -> HarnessToolRegistry {+ HarnessToolRegistry(+ tools: descriptors.map { descriptor in+ HarnessTool(descriptor: descriptor) { context in+ HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "\(context.call.name) accepted by generic harness stub executor.",+ observations: HarnessObservationDelta(+ facts: ["lastAcceptedTool": context.call.name]+ ),+ metadata: ["executor": "stub"]+ )+ }+ }+ )+ }++ private static func descriptor(+ _ name: String,+ pluginID: String,+ summary: String,+ input: [String: String] = [:],+ output: [String: String] = [:],+ permissions: [HarnessPermission],+ safety: HarnessToolSafetyClass,+ requiredContext: [String] = [],+ verification: [String] = [],+ metadata: [String: String] = [:]+ ) -> HarnessToolDescriptor {+ HarnessToolDescriptor(+ name: name,+ pluginID: pluginID,+ summary: summary,+ inputSchema: input,+ outputSchema: output,+ requiredPermissions: permissions,+ safetyClass: safety,+ requiredContext: requiredContext,+ verificationHints: verification,+ metadata: metadata+ )+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftnew file mode 100644index 00000000..011d4ca2--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -0,0 +1,464 @@+import DonkeyContracts+import DonkeyHarness+import Foundation+import Testing++@Suite+struct GenericHarnessTests {+ @Test+ func builtInRegistryContainsGenericToolsAndAppleScriptAutomationTools() async {+ let descriptors = BuiltInHarnessToolCatalog.descriptors+ let names = Set(descriptors.map(\.name))++ #expect(names.contains("app.search"))+ #expect(names.contains("elements.get"))+ #expect(names.contains("element.perform"))+ #expect(names.contains("skill.search"))+ #expect(names.contains("skill.load"))+ #expect(names.contains("skill.script.generate"))+ #expect(names.contains("skill.script.validate"))+ #expect(names.contains("skill.script.execute"))+ #expect(names.contains("automation.applescript.generate"))+ #expect(names.contains("automation.applescript.execute"))++ let generate = descriptors.first { $0.name == "automation.applescript.generate" }+ #expect(generate?.metadata["modelBoundary"] == "required")+ #expect(generate?.metadata["directExecution"] == "false")+ #expect(generate?.requiredContext.contains("structured intent") == true)++ let execute = descriptors.first { $0.name == "automation.applescript.execute" }+ #expect(execute?.metadata["requiresGeneratedArtifact"] == "true")+ #expect(execute?.requiredPermissions == [.appControl, .input])++ let skillSearch = descriptors.first { $0.name == "skill.search" }+ #expect(skillSearch?.requiredPermissions == [.skillLookup])+ #expect(skillSearch?.pluginID == "core.skills")++ let scriptGenerate = descriptors.first { $0.name == "skill.script.generate" }+ #expect(scriptGenerate?.metadata["modelBoundary"] == "required")+ #expect(scriptGenerate?.metadata["directExecution"] == "false")++ let scriptExecute = descriptors.first { $0.name == "skill.script.execute" }+ #expect(scriptExecute?.metadata["requiresValidatedScript"] == "true")+ #expect(scriptExecute?.requiredPermissions == [.appControl, .input])+ }++ @Test+ func skillRegistryCanRegisterAndSearchSkills() async {+ let registry = HarnessSkillRegistry()+ await registry.register(+ HarnessSkillDescriptor(+ id: "desktop-browser",+ name: "Desktop Browser",+ summary: "Operate browser tabs and inspect web pages.",+ description: "Use for browser automation, screenshots, forms, and navigation.",+ sourceKind: .plugin,+ tags: ["browser", "computer-use"],+ providedToolNames: ["screen.observe", "element.perform"],+ scripts: [+ HarnessSkillScriptDescriptor(+ id: "open-devtools",+ language: .appleScript,+ purpose: "Open browser developer tools",+ relativePath: "scripts/open-devtools.applescript",+ generatedBy: "skill.script.generate",+ validationStatus: .validated,+ requiredPermissions: [.appControl, .input],+ safetyClass: .guardedInput+ )+ ]+ )+ )++ let results = await registry.search(query: "browser automation")++ #expect(results.first?.descriptor.id == "desktop-browser")+ #expect(results.first?.matchedFields.contains("name") == true || results.first?.matchedFields.contains("summary") == true)+ #expect(results.first?.descriptor.providedToolNames.contains("element.perform") == true)+ #expect(results.first?.descriptor.scripts.first?.id == "open-devtools")+ }++ @Test+ func skillFileSystemSourceDiscoversSkillMarkdownFiles() async throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("donkey-harness-skill-test-\(UUID().uuidString)", isDirectory: true)+ let skillDirectory = root.appendingPathComponent("spreadsheet-helper", isDirectory: true)+ try FileManager.default.createDirectory(+ at: skillDirectory,+ withIntermediateDirectories: true+ )+ try FileManager.default.createDirectory(+ at: skillDirectory.appendingPathComponent("scripts", isDirectory: true),+ withIntermediateDirectories: true+ )+ try """+ id: spreadsheet-helper+ description: Build and inspect spreadsheet documents.+ tags: sheets, documents+ tools: memory.retrieve, automation.applescript.generate++ # Spreadsheet Helper++ Use when a task needs spreadsheet reasoning or document automation.+ """.write(+ to: skillDirectory.appendingPathComponent("SKILL.md"),+ atomically: true,+ encoding: .utf8+ )+ try """+ tell application "Numbers"+ activate+ end tell+ """.write(+ to: skillDirectory.appendingPathComponent("scripts/open-numbers.applescript"),+ atomically: true,+ encoding: .utf8+ )+ try """+ #!/usr/bin/env bash+ echo preparing+ """.write(+ to: skillDirectory.appendingPathComponent("scripts/prepare.sh"),+ atomically: true,+ encoding: .utf8+ )+ try """+ print("inspect")+ """.write(+ to: skillDirectory.appendingPathComponent("scripts/inspect.py"),+ atomically: true,+ encoding: .utf8+ )+ defer {+ try? FileManager.default.removeItem(at: root)+ }++ let source = HarnessSkillFileSystemSource(roots: [root])+ let skills = source.discover()++ #expect(skills.count == 1)+ #expect(skills.first?.id == "spreadsheet-helper")+ #expect(skills.first?.name == "Spreadsheet Helper")+ #expect(skills.first?.tags == ["documents", "sheets"])+ #expect(skills.first?.providedToolNames == ["automation.applescript.generate", "memory.retrieve"])+ #expect(skills.first?.scripts.count == 3)+ let scriptsByID = Dictionary(uniqueKeysWithValues: (skills.first?.scripts ?? []).map { ($0.id, $0) })+ #expect(scriptsByID["scripts-open-numbers"]?.language == .appleScript)+ #expect(scriptsByID["scripts-open-numbers"]?.validationStatus == .pendingValidation)+ #expect(scriptsByID["scripts-open-numbers"]?.requiredPermissions == [.appControl, .input])+ #expect(scriptsByID["scripts-prepare"]?.language == .shell)+ #expect(scriptsByID["scripts-inspect"]?.language == .python)+ #expect(skills.first?.instructionPath?.hasSuffix("SKILL.md") == true)+ }++ @Test+ func unknownToolIsRejectedByRegistry() async {+ let registry = BuiltInHarnessToolCatalog.registryWithStubExecutors()+ let result = await registry.execute(+ HarnessToolCall(id: "call-1", name: "missing.tool"),+ taskID: "task-1",+ worldModel: HarnessWorldModel(),+ grantedPermissions: []+ )++ #expect(result.status == .unknownTool)+ #expect(result.metadata["reason"] == "unknownTool")+ }++ @Test+ func missingPermissionStopsTaskAndStoresContinuation() async {+ let coordinator = HarnessTaskCoordinator()+ let runtime = GenericHarnessRuntime(+ coordinator: coordinator,+ registry: BuiltInHarnessToolCatalog.registryWithStubExecutors()+ )+ let task = await coordinator.createTask(+ id: "task-permission",+ threadID: "thread-1",+ goal: "click a button"+ )++ let call = HarnessToolCall(+ id: "call-click",+ name: "element.perform",+ input: ["elementID": "button-1", "action": "press"]+ )+ let result = await runtime.executeToolCall(taskID: task.id, call: call)++ #expect(result?.stoppedForGate == true)+ #expect(result?.task.status == .waitingForPermission)+ #expect(result?.task.pendingContinuation?.stage == .permissionGate)+ #expect(result?.task.pendingContinuation?.pendingToolCall?.id == "call-click")+ #expect(result?.task.pendingContinuation?.missingPermissions == [.accessibility, .input])+ #expect(result?.toolResult?.status == .permissionDenied)+ }++ @Test+ func permissionApprovalResumesFromCheckpointAndAllowsToolExecution() async {+ let coordinator = HarnessTaskCoordinator()+ let runtime = GenericHarnessRuntime(+ coordinator: coordinator,+ registry: BuiltInHarnessToolCatalog.registryWithStubExecutors()+ )+ let task = await coordinator.createTask(+ id: "task-resume-permission",+ threadID: "thread-1",+ goal: "click a button"+ )+ let call = HarnessToolCall(+ id: "call-click",+ name: "element.perform",+ input: ["elementID": "button-1", "action": "press"]+ )++ _ = await runtime.executeToolCall(taskID: task.id, call: call)+ let resumed = await coordinator.grantPermissions(+ taskID: task.id,+ permissions: [.accessibility, .input]+ )+ let executed = await runtime.executeToolCall(taskID: task.id, call: call)++ #expect(resumed?.status == .resuming)+ #expect(resumed?.pendingContinuation == nil)+ #expect(executed?.stoppedForGate == false)+ #expect(executed?.toolResult?.status == .succeeded)+ #expect(executed?.task.worldModel.facts["lastAcceptedTool"] == "element.perform")+ #expect(executed?.task.toolHistory.count == 1)+ }++ @Test+ func clarificationStopsTaskAndUserResponseResumesIt() async {+ let coordinator = HarnessTaskCoordinator()+ let runtime = GenericHarnessRuntime(+ coordinator: coordinator,+ registry: BuiltInHarnessToolCatalog.registryWithStubExecutors()+ )+ let task = await coordinator.createTask(+ id: "task-clarify",+ threadID: "thread-1",+ goal: "send a message",+ grantedPermissions: [.userPrompt]+ )+ let call = HarnessToolCall(+ id: "call-clarify",+ name: "user.clarify",+ input: ["question": "Which Alex should I message?"]+ )++ let stopped = await runtime.executeToolCall(taskID: task.id, call: call)+ let resumed = await coordinator.provideUserResponse(+ taskID: task.id,+ response: "Alex Chen"+ )++ #expect(stopped?.task.status == .waitingForUser)+ #expect(stopped?.task.pendingContinuation?.question == "Which Alex should I message?")+ #expect(stopped?.toolResult?.status == .waitingForUser)+ #expect(resumed?.status == .resuming)+ #expect(resumed?.pendingContinuation == nil)+ #expect(resumed?.worldModel.facts["lastUserClarification"] == "Alex Chen")+ }++ @Test+ func multipleTasksKeepSeparateWorldModelsPlansAndToolHistory() async {+ let coordinator = HarnessTaskCoordinator()+ let runtime = GenericHarnessRuntime(+ coordinator: coordinator,+ registry: BuiltInHarnessToolCatalog.registryWithStubExecutors()+ )+ let first = await coordinator.createTask(+ id: "task-a",+ threadID: "thread-a",+ goal: "search apps",+ grantedPermissions: [.appLookup]+ )+ let second = await coordinator.createTask(+ id: "task-b",+ threadID: "thread-b",+ goal: "observe screen",+ grantedPermissions: [.screenCapture]+ )++ _ = await runtime.executeToolCall(+ taskID: first.id,+ call: HarnessToolCall(id: "call-a", name: "app.search", input: ["query": "Calendar"])+ )+ _ = await runtime.executeToolCall(+ taskID: second.id,+ call: HarnessToolCall(id: "call-b", name: "screen.observe")+ )++ let updatedFirst = await coordinator.task(id: first.id)+ let updatedSecond = await coordinator.task(id: second.id)+ let active = await coordinator.activeTasks()++ #expect(active.map(\.id).contains("task-a"))+ #expect(active.map(\.id).contains("task-b"))+ #expect(updatedFirst?.worldModel.facts["lastAcceptedTool"] == "app.search")+ #expect(updatedSecond?.worldModel.facts["lastAcceptedTool"] == "screen.observe")+ #expect(updatedFirst?.toolHistory.first?.call.id == "call-a")+ #expect(updatedSecond?.toolHistory.first?.call.id == "call-b")+ }++ @Test+ func interruptChangesCourseWithoutLosingTaskIdentity() async {+ let coordinator = HarnessTaskCoordinator()+ let task = await coordinator.createTask(+ id: "task-interrupt",+ threadID: "thread-1",+ goal: "draft an email"+ )++ let interrupted = await coordinator.interrupt(+ taskID: task.id,+ newGoal: "draft a shorter email",+ turn: AppHarnessTurn(text: "actually make it short", source: .followUp, taskID: task.id, isFollowUp: true)+ )++ #expect(interrupted?.id == task.id)+ #expect(interrupted?.status == .interrupted)+ #expect(interrupted?.goal == "draft a shorter email")+ #expect(interrupted?.plan == nil)+ #expect(interrupted?.pendingContinuation?.metadata["newGoal"] == "draft a shorter email")+ #expect(interrupted?.context.turn?.text == "actually make it short")+ }++ @Test+ func plannedLoopExecutesOneToolAtATime() async {+ let coordinator = HarnessTaskCoordinator()+ let runtime = GenericHarnessRuntime(+ coordinator: coordinator,+ registry: BuiltInHarnessToolCatalog.registryWithStubExecutors()+ )+ let task = await coordinator.createTask(+ id: "task-loop",+ threadID: "thread-1",+ goal: "observe then verify",+ grantedPermissions: [.screenCapture, .verification]+ )+ let plan = HarnessPlan(+ goal: "observe then verify",+ steps: [+ HarnessPlanStep(+ id: "observe",+ summary: "Observe screen",+ toolCall: HarnessToolCall(id: "observe-call", name: "screen.observe")+ ),+ HarnessPlanStep(+ id: "verify",+ summary: "Verify state",+ toolCall: HarnessToolCall(id: "verify-call", name: "state.verify")+ )+ ]+ )+ _ = await coordinator.updatePlan(taskID: task.id, plan: plan)++ let first = await runtime.executeNextPlannedStep(taskID: task.id)+ let second = await runtime.executeNextPlannedStep(taskID: task.id)++ #expect(first?.toolResult?.toolName == "screen.observe")+ #expect(second?.toolResult?.toolName == "state.verify")+ #expect(second?.task.toolHistory.map(\.call.id) == ["observe-call", "verify-call"])+ }++ @Test+ func threadStorePersistsThreadsEventsAndAssetsByThreadID() async {+ let store = InMemoryHarnessThreadStore()+ let thread = HarnessThread(+ id: "thread-1",+ title: "Plan a desktop task",+ activeTaskIDs: ["task-1"]+ )+ await store.upsertThread(thread)+ await store.appendEvent(+ HarnessThreadEvent(+ threadID: thread.id,+ taskID: "task-1",+ role: .user,+ text: "learn this app",+ sequence: 1+ )+ )+ await store.appendAsset(+ HarnessThreadAsset(+ threadID: thread.id,+ taskID: "task-1",+ displayName: "screen.png",+ contentType: "image/png",+ urlString: "file:///tmp/screen.png"+ )+ )++ let loadedThread = await store.thread(id: thread.id)+ let events = await store.events(threadID: thread.id)+ let assets = await store.assets(threadID: thread.id)++ #expect(loadedThread?.title == "Plan a desktop task")+ #expect(events.map(\.text) == ["learn this app"])+ #expect(assets.first?.displayName == "screen.png")+ }++ @Test+ func smartCompactionPreservesPinnedSummariesRecentEventsAndWaitingTaskState() async {+ let thread = HarnessThread(id: "thread-compact", title: "Long task")+ let events = (1...20).map { index in+ HarnessThreadEvent(+ id: "event-\(index)",+ threadID: thread.id,+ role: index == 2 ? .summary : (index.isMultiple(of: 5) ? .tool : .user),+ text: index == 20 ? String(repeating: "latest ", count: 200) : "event \(index)",+ sequence: index,+ isPinned: index == 1+ )+ }+ let waitingTask = HarnessTaskState(+ id: "task-waiting",+ threadID: thread.id,+ goal: "learn app",+ status: .waitingForUser,+ pendingContinuation: HarnessPendingContinuation(+ stage: .clarification,+ reason: "Need scope",+ question: "Which part of the app should I learn first?"+ )+ )+ let completedTask = HarnessTaskState(+ id: "task-complete",+ threadID: thread.id,+ goal: "old task",+ status: .completed+ )+ let compactor = HarnessThreadCompactor(+ policy: HarnessCompactionPolicy(+ maxEvents: 4,+ maxPinnedEvents: 2,+ maxToolEvents: 1,+ maxAssets: 1,+ maxEventCharacters: 40,+ maxPromptCharacters: 1_200+ )+ )++ let compacted = compactor.compact(+ thread: thread,+ currentTurn: AppHarnessTurn(text: "continue", source: .followUp, taskID: waitingTask.id, isFollowUp: true),+ events: events,+ assets: [+ HarnessThreadAsset(threadID: thread.id, displayName: "old.png", contentType: "image/png", urlString: "file:///tmp/old.png"),+ HarnessThreadAsset(threadID: thread.id, displayName: "new.png", contentType: "image/png", urlString: "file:///tmp/new.png")+ ],+ activeTasks: [waitingTask, completedTask]+ )++ #expect(compacted.events.contains { $0.id == "event-1" })+ #expect(compacted.events.contains { $0.role == .summary })+ #expect(compacted.events.contains { $0.id == "event-20" })+ #expect(compacted.events.first(where: { $0.id == "event-20" })?.text.count == 40)+ #expect(compacted.assets.count == 1)+ #expect(compacted.activeTasks.map(\.id) == ["task-waiting"])+ #expect(compacted.promptText.contains("waitingForUser"))+ #expect(compacted.promptText.contains("Which part of the app should I learn first?"))+ #expect(compacted.metadata["compactor"] == "smart-priority-v1")+ #expect(compacted.compactionRecords.contains { $0.itemKind == .recentEvent && $0.droppedCount > 0 })+ }+}diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 72d2dd5e..60bf3f21 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -2,400 +2,320 @@## What It Is-The agent harness is Donkey's boundary between the user's conversation and the-systems that can act on the Mac. It owns the question: "What should this turn do-next?" Sometimes the answer is normal conversation. Sometimes it is a-clarifying question. Sometimes it is a reviewed plan. Sometimes it is a guarded-local-app action.--A task is not just an executable command. A task is a durable conversation-thread with user turns, assistant turns, assets, memory, trace ids, and optional-action runs attached to it. This matters because a user can say "hi", ask what-Donkey can do, upload a file, revise a previous request, approve a form-fill-plan, or ask Donkey to operate another app. Those are all valid task-thread-turns, but only some of them should touch the action runtime.--The harness makes that distinction before execution. Non-actionable turns should-produce assistant responses. Ambiguous actionable turns should ask for the-specific missing information. Validated actionable turns may enter the local-app-runner, review UI, planner, or action engine. A greeting or capability question-must not become a failed task card.--## How A Turn Flows--Every prompt submission, voice transcript, follow-up, and asset event enters the-same harness intake path. Intake first attaches the turn to the right durable-thread, records the event, and builds a compact context packet. From there the-harness routes the turn by meaning, not by the fact that text was submitted.--The normal flow is:--1. Receive a turn from the pointer prompt, voice transcription, file drop, or a- task follow-up.-2. Attach it to an existing or new task thread and persist the user-visible- event.-3. Build a bounded context packet for this decision.-4. Classify the turn as conversation, clarification, review, actionable intent,- planning/recovery, memory, or no-op.-5. Produce a conversational response, ask for missing details, open review, or- execute a validated action.-6. Persist assistant/tool/lifecycle events and update the notch with the thread- state and any action state.--The harness loop looks like this:+The agent harness is Donkey's app-agnostic runtime boundary for turning a user+turn into durable task progress. It owns the lifecycle around intent,+context-gathering, world modeling, planning, tool execution, verification,+recovery, permission gates, clarification, pause/resume, interruption, and+multi-task coordination.++The generic harness contracts live in `apps/Donkey/Sources/DonkeyHarness/`.+New agent capabilities should plug into that module through tools, skills,+scripts, plugins, catalogs, or memory. Do not add app-specific branches,+phrase lists, or one-off workflow conditionals to the core harness.++The existing pointer-prompt and local-app runner code still exists while the+product migrates onto the generic harness. New work should build toward the+generic contracts and avoid expanding the older app-specific paths.++## Core Model++Every task has its own durable state:++- task id and thread id+- current goal+- structured intent analysis+- gathered context+- world model+- plan+- granted permissions+- tool history+- pending continuation+- lifecycle status++Supported task statuses are:++- `running`+- `paused`+- `waitingForUser`+- `waitingForPermission`+- `interrupted`+- `resuming`+- `completed`+- `failedSafe`+- `cancelled`++Multiple tasks may be active at once. Mutable execution state must stay+task-local unless it is stored in an explicit task-safe service. A pause,+clarification gate, permission gate, or cancellation affects only the selected+task; it must not block unrelated active tasks.++## Thread Storage++Threads are the durable conversation record. The generic harness defines a+thread-store boundary for threads, events, and assets. In tests this is backed+by an in-memory store; the app should back the same contract with the local+Donkey database. The older pointer-prompt UI currently persists its tasks and+events in the user's Application Support directory, but new harness code should+depend on the generic store contract rather than reaching into that UI-specific+store directly.++A thread record stores the user-visible conversation and the active task ids.+Task state stores execution details such as world model, plan, permissions,+tool history, and pending continuations. Keeping those separate lets one thread+coordinate multiple active tasks without mixing their execution state.++## Smart Compaction++The harness should never send raw unbounded history to a model. Before a model+call or planner step, the thread compactor builds a bounded context packet. It+keeps the current turn, active and waiting task state, pending questions or+permissions, pinned events, durable summaries, the most recent useful events,+recent tool summaries, and a bounded asset list.++Large event bodies are truncated. Raw screenshots, full Accessibility trees,+script source, and long tool outputs should be saved as artifacts or structured+records and summarized into the prompt. Compaction metadata records what was+included, dropped, or truncated so the decision remains inspectable.++## Turn Flow++The desired loop is:```text- pointer prompt / file drop / follow-up voice audio- | |- v v- +-------------------+ +--------------------------+- | user-visible turn | | hosted model call |- +-------------------+ | voice transcription |- | +--------------------------+- | |- | transcript turn- | |- +---------------+----------------+- |- v- +------------------------+- | intake + thread attach |- +------------------------+- |- v- +------------------------+- | bounded context packet |- +------------------------+- |- +-----------------------+-----------------------+- | | |- v v v-+--------------------+ +--------------------+ +----------------------+-| deterministic | | hosted model call | | provider LLM call |-| parser/fallback | | intent/follow-up | | response/planner/ |-| | | classifier | | memory proposals |-+--------------------+ +--------------------+ +----------------------+- | | |- +-----------------------+-----------------------+- |- v- +------------------------+- | AppHarnessDecision |- +------------------------+- | |- v v- +-------------------------+ +------------------------+- | respond / clarify / | | catalog validation |- | review / no-op | +------------------------+- +-------------------------+ |- | v- | +------------------------+- | | observe target app |- | +------------------------+- | |- | v- | +------------------------+- | | hosted/tool calls |- | | screenshot/context |- | | understanding |- | +------------------------+- | |- | v- | +------------------------+- | | project, approve, |- | | execute, verify |- | +------------------------+- | |- +-------------+-----------+- |- v- +------------------------+- | persist events + notch |- +------------------------+- |- v- next turn+intake+-> intent analysis+-> context gathering+-> world model update+-> planning+-> execute one validated tool step+-> verify+-> recover, continue, clarify, or complete```-The harness should make conversation feel continuous even when execution happens-inside the thread. The user should not need to know whether a turn was answered-by a chat response, a hosted model classifier, a typed runtime artifact, or a-guarded runtime path.--Model calls live behind typed harness boundaries. Voice transcription,-task-intent classification, follow-up classification, computer-use decisions,-and planner/helper calls go through authenticated hosted model routes. The Mac-app selects only the supported Donkey capability route and sends the typed job-context; it must not name hosted providers, provider API endpoints, or concrete-model ids for normal hosted calls. The backend chooses the provider and model-for that route. Observation helpers inside the local-task branch produce-evidence, not direct input actions. Any semantic user-intent distinction,-including whether a turn is a visual-only agent visualization request, belongs-behind one of these typed model or catalog boundaries.--Routing outcomes carry a structured `AppHarnessDecision`. The decision names the-next supported harness action:-respond, ask for clarification, open review, run a local task, or no-op. This-keeps model-assisted routing in a typed decision space instead of treating free-text as an implicit action signal.--## Intent Classification Rules--The core rule is model-first: never string-match raw user input to infer what-the user wants. Natural language has too many variations for phrase lists,-prefixes, suffixes, regexes, greeting classifiers, or app-name checks to be a-reliable decision boundary. Pass the turn through an LLM or another typed-model/runtime boundary first. Once structured output exists, deterministic code-may validate and match typed fields.--User intent must not be inferred with ad hoc phrase, prefix, suffix, substring,-or regex checks against natural-language command text. Donkey has hosted-classifiers, task definitions, runtime catalogs, and agent memory context for-this job. Use them.-The fast classifier may know typed capability buckets such as task ids,-capability ids, agent memory entry kinds, and model output statuses. It must not-recover those buckets by reading natural-language words out of the user's-prompt.--Allowed deterministic checks are narrow primitives whose correctness does not-depend on open-ended language semantics: empty input, exact schema validation,-explicit metadata flags, and bounded normalization of lookup text after a typed-decision has already selected a lookup path. These checks must stay generic and-must not encode app-specific-or workflow-specific user phrasing.--Disallowed checks include code that decides a user's semantic intent from-phrases like "show me how", "within", "play", "open", or app names outside a-declared task definition or model output. If behavior depends on what the user-means, add or reuse a typed classifier/resolver and test it with structured-model output. Do not patch another string list.--Do not look for words inside user command strings to decide what the user wants.-This includes local deterministic parser fallbacks, command trigger arrays,-prefix/suffix tests, and conversation/greeting/help classifiers. A typed model-or explicit runtime artifact must produce the intent first. Exact string checks-remain acceptable for non-semantic technical validation such as JSON schema-fields, CLI arguments, AppleScript syntax/output validation, filesystem paths,-accessibility constants, colors, and safety metadata.--Generic local-item lookup must follow the same rule. Do not add static command-verb, lookup prefix, or lookup suffix arrays to guess that text means "open this-app/file/folder." A typed model or catalog artifact selects the local-item-lookup capability and extracts the requested item name; after that, the runtime-may normalize that item name and resolve it through agent memory, Spotlight, and-bounded filesystem lookup.--Agent action visualization is the canonical example. The harness may show an-animated overlay cursor after a normal local-app run emits an-`AgentVisualizationPlan`, or after a model-backed resolver returns the same plan-shape in `visualOnly` mode. It must not use hardcoded prompt prefixes to decide-that a turn is visualization-only, and it must not parse app names or goals out-of text with local string slicing.--## Context Engineering--The harness builds context deliberately for each job. It should never dump raw,-unbounded thread history into a model or runtime adapter. Context packets should-be compact, source-linked, and explicit about what is known, what is missing,-what can be acted on, and what policies apply.--A useful context packet includes the current turn, a bounded summary of recent-thread events, relevant assets, active action state, selected app/window facts-when available, task definitions, app-finder catalog entries, supported-capabilities, permission policy, safety state, and trace ids. The packet should-be shaped for the consumer:-conversation response, intent classification, planner hint, review-plan-creation, memory retrieval, observation, and recovery do not need the same-fields. Query-matched memory for natural-language prompt text should not be-added before intent classification; retrieve memory after the typed model-output provides a structured target or scope.--Remote-bound context must be redacted before provider calls. Local-only context-can include richer app and observation facts, but should still stay bounded and-inspectable. Memory retrieval should use target/scope/kind filters, FTS/vector-relevance thresholds, and prompt-character budgets before summaries are added.--Context compaction is typed and inspectable. Current turns, policy, active-target state, runtime capabilities, and trace identifiers are preserved first.-Transient retry/correction events are dropped before durable thread events,-and packet metadata records what was included, dropped, or truncated by item-kind.--## Routing Outcomes--Conversation is a first-class outcome. Turns that do not produce a typed local-task intent stay in the task thread and get an assistant response instead of a-failed local-app run. Conversation classification may be model-backed or derived-from explicit runtime/model statuses, but it must not use greeting/help/small-talk phrase lists.--Clarification is for typed actionable intent with missing required information.-When the model returns a supported task but marks a required entity as missing,-the harness should ask for that exact entity or invite an upload. The prompt-should name the missing detail rather than using generic copy like "Need more-detail".--Action execution is for validated, supported tasks. The hosted model classifier-or explicit runtime metadata produces a `TaskIntent`. Execution may only-continue after catalog validation confirms the target app/task, required-entities, app availability, and safety policy. The default runtime-capabilities are generic local-item open plus generic model-planned local-app-interaction; the latter materializes a transient task definition from an-allowlisted typed `actionPlan` before execution. Typed focus-control steps with-declared keyboard shortcuts may execute after the target app is focused;-pointer/control targeting still requires grounded bounds. Weather lookup, media-playback, and document form-fill are benchmark fixtures for tests and replay-evaluation, not runtime defaults. Runtime defaults come from the SQLite-backed-agent memory store, which is seeded with generic capabilities and enriched by-model-generated or user-reviewed task definition files.--Review is required when the harness can propose work but should not perform it-blindly. Document form-fill is the main supported example: Donkey can inspect-fields and propose mappings, but only user-approved fields are sent to guarded-Accessibility execution.--Planning and recovery are advisory. Slow planner output can help with app-knowledge lookup or recovery, but planner text must not become direct input.-Planner hints expire, validate against known actions, and remain separate from-task-intent parsing.--## Execution Boundary--The harness is allowed to coordinate execution, but it should not bypass the-runtime safety model. Local-app work flows through typed contracts, catalog-resolution, observation, evidence-backed action planning, guardrails, and-verification before or during live control.--Local-app workflow progress is tracked outside prompt/context text. Each run-records typed stage state for intent parsing, task/app resolution, observation,-internal planning, approval/review, guarded execution, and verification.-Evidence planning remains a background runtime concern: the handler should not-publish a pre-execution visualization for normal live work. The runner derives-agent visualization steps from observed evidence and action traces, and cursor-playback requires Accessibility or action-trace targets. The model can be told-about this state, but the runner owns it.--Live input remains guarded. The action engine checks permission policy, target-focus, rate limits, hold duration, and backend evidence before issuing input.-The macOS AppleScript, keyboard, and Accessibility backends are intentionally-narrow. They exist for validated local-app workflows, not arbitrary UI-automation. Prefer app-native AppleScript for scriptable app tasks before-falling back to Accessibility or keyboard input. AppleScript commands may be-generated from task metadata or compact model-provided source/templates, but-they still run only after catalog validation and through the guarded controller-backend.--App automation scripts must be generated artifacts, not product code fixtures.-Do not add hardcoded app-specific AppleScript bodies, UI-scripting sequences, or-workflow scripts to Swift as static strings. The harness may keep generic-rendering/execution utilities such as string escaping, template interpolation,-schema validation, AppleScript syntax/language validation, and guarded backend-dispatch. The actual app-control script for a task must come from a typed-model/script-generation step, agent memory metadata, or a user-reviewed task-definition, and it must be logged with the model/schema/action metadata that-produced it.--If an app task needs AppleScript, the supported shape is: classify the task,-resolve the target app and entities, ask the model or task-definition layer for-a bounded script or template, validate that it matches the resolved task and-allowed backend, then execute it through the AppleScript backend. Adding a-`musicPlaybackScript`, `openFooScript`, or similar app-named helper is a harness-bug, even if the script happens to work on one machine.--Observation prefers Accessibility and app/window metadata. Bounded screenshots-are fallback observation context only; they do not emit direct input actions.-The local UI element detection service keeps this boundary explicit: it merges-Accessibility candidates with optional hover-probe evidence, then marks each-element as overlay-only, read-only evidence, cursor-visualization evidence, or-guarded-action eligible. Native screenshot CV remains a local experimental-detector, but it is not part of the live Donkey Vision overlay pipeline and-does not authorize live clicks or text entry.-The off-the-shelf vision pipeline remains stubbed and must not produce OCR,-shape, color, layout, segmentation, or tap-target candidates until a new-measured implementation replaces it. Hover-only evidence can guide debug-overlays or visualization, but it does not authorize live clicks or text entry.-Captured screenshots, Accessibility snapshots, and manual capture artifacts are-trace evidence, not a general live vision loop.-Verification and screenshot fallback behavior should be derived from task-metadata and runtime item metadata, not one-off branches for individual apps.--Prompt understanding is hosted by default. The Mac app sends redacted,-bounded context to the Donkey backend Responses proxy and never stores provider-API keys locally. Supported prompt handling must not depend on local model-packages, local model weights, or `DONKEY_LOCAL_LLM_RUNNER`. Provider-backed-planners and memory proposals remain helper paths that write through-deterministic approval into agent memory and must fail without stopping local-control on existing validated state.--Computer-use decisions are hosted too. Browser interaction and Mac desktop-interaction are separate backend tool registrations with different hosted-providers: `donkey_gemini_browser_interaction` for browser environments through-Gemini, and `donkey_openai_mac_desktop_interaction` for guarded macOS desktop-actions through OpenAI's Responses `computer` tool. General inference and-browser computer-use use Gemini; macOS desktop computer-use uses OpenAI. Hosted-models may propose UI actions, but the Mac client still owns execution,-confirmation gates, focus checks, permission policy, screenshots, and-tool-output feedback.--The developer UI inspection overlay is not an action workflow. It is enabled by-the repo-tracked `apps/Donkey/dev-overlay.json` during debug runs or by a local-`dev-overlay.json` file under Donkey's Application Support directory. Production-builds do not bundle the repo config. When enabled, Donkey Vision always fuses-local Accessibility evidence with hosted AI enrichment and renders distinct-source badges. It only inspects safe visible windows on the selected screen;-optional target filters can narrow it to matching apps, and-`"activeWindowOnly": true` can keep it blank unless a matching app owns the-focused frontmost window. The overlay tracker stabilizes small geometry jitter,-brief disappearances, and one-sample label/source changes before redrawing so-the debugger reflects durable UI changes instead of sampler noise. The hosted AI-path sends app/window-scoped screenshots to the read-only inspection route and-accepts strict JSON element metadata only. If hosted AI returns a-computer/function action for this route, the client rejects the frame and-performs no interaction.--## State And Observability--Task-thread state and action-run state are related but distinct. A thread can be-chatting, waiting for clarification, waiting for review, running an action,-completed, or failed. The notch should communicate that distinction so normal-conversation does not look like a broken command.--The coordinator owns lifecycle and event ordering for action runs. It records-assistant, tool, lifecycle, and reflex events; handles start, pause, resume,-completion, abort, timeout, and failure; and marks aborts/timeouts that require-held-input release. Run artifacts, screenshots, Accessibility captures, latency-reports, memory records, and model-call traces should remain source-linked and-inspectable.--Latency claims must come from monotonic trace data. Provider calls, planner-work, and slow recovery should not be counted as reflex-loop latency unless they-actually block that path.+The harness should not treat desktop work as a single model completion. It+should observe, act, verify, and replan. The planner may propose the next tool+step, but deterministic Swift owns task state, tool validation, permissions,+focus checks, execution, and result recording.++If the user interrupts a task, the harness classifies whether the turn starts a+new task, modifies the current task, cancels, pauses, resumes, answers a+clarification, grants permission, or is conversation. A course change updates+the existing task goal/world model/plan and resumes from the checkpoint instead+of blindly restarting.++## Stop Points++Waiting states are hard stop points.++If a tool lacks permission, the task moves to `waitingForPermission`, stores a+pending continuation, asks for the specific permission, and does not execute+more tools until approval is recorded.++If required information is missing, the task moves to `waitingForUser`, stores+the pending continuation, asks a specific question, and resumes only after the+answer is attached.++Dangerous ambiguity must ask before acting. Safe ambiguity may be inferred.+Recoverable ambiguity should use available tools first, such as memory, app+search, screen observation, or skill lookup, and ask only if uncertainty remains+material.++## Tools And Plugins++Tools are registered through the generic tool registry. A tool descriptor+declares:++- name+- plugin id+- summary+- input/output schema+- required permissions+- safety class+- required context+- verification hints+- metadata++The planner sees tool descriptors and schemas, not Swift implementation+details. The executor validates every tool call against the registry before+dispatch. Tool results return structured observations that update the task's+world model.++Core built-in tools cover conversation, user clarification, permission+requests, memory lookup, skill lookup, skill-script lifecycle, app discovery,+screen observation, UI element discovery and action, text and keyboard input,+AppleScript generation/execution, state verification, and task lifecycle+control.++Additional plugins should register tools through the same interface. App+knowledge belongs in plugins, skills, catalogs, or memory, not in core harness+conditionals.++## Computer Use++Computer use is one tool family inside the harness.++Accessibility is the primary source for actionable UI elements. Screenshots,+vision, OCR, and hover evidence can enrich the world model, labels, and layout,+but they must not authorize live input by themselves.++Element actions execute only after the harness validates:++- target focus+- permission policy+- element eligibility+- allowed action type+- rate limits+- safety class+- verification criteria++Models should choose semantic targets and tool calls. They should not+micromanage pixels. Coordinate input is fallback evidence only and must pass the+same guarded execution checks as other input.++## AppleScript And Scripts++AppleScript is a tool path, not a hardcoded helper path.++AppleScript generation gathers the resolved app, goal, entities, allowed+actions, and verification criteria, then passes that bounded request through a+model/script-generation boundary. It returns a script artifact for validation or+review. It does not execute the script.++AppleScript execution may run only a validated, generated, or user-reviewed+artifact through the guarded automation backend, with target app, permissions,+action metadata, and verification evidence attached.++Do not add app-named Swift helpers such as `musicPlaybackScript` or+`openFooScript`. If an app needs automation knowledge, put it in a skill,+plugin, catalog entry, generated artifact, or user-reviewed definition.++## Skills++Skills are reusable harness extensions. A skill can be registered directly or+discovered from configured roots by finding `SKILL.md` files. The skill+registry indexes:++- id+- name+- summary and description+- source kind+- instruction path+- tags+- provided tools+- scripts+- required permissions+- metadata++Skill lookup lets the planner find relevant instructions by structured task+need. Loading a skill adds selected instructions to bounded planning context.++Skills are shared infrastructure. They should be reusable by any future agent+or task, not private scratch memory for one run.++## Skill Scripts++Skill packs may include generated scripts under a skill-local `scripts/`+directory. Supported script descriptors include AppleScript, shell/Bash,+Python, JavaScript, Swift, and future language types.++Each script descriptor records:++- id+- language+- purpose+- skill-relative path+- generator provenance+- validation status+- required permissions+- safety class+- metadata++Script generation, validation, and execution are separate steps. Generation+creates a reusable artifact through a model boundary and stores it as pending+validation. Validation records whether the script is allowed. Execution may run+only validated scripts through the appropriate guarded backend with normal+permission and verification gates.++A learned application skill can therefore carry instructions, app maps,+workflow recipes, evidence notes, and generated scripts together.++## Learning Applications++"Learn an application" should be implemented as a skill-producing harness task.+It explores an app safely, observes each state, distills durable knowledge, and+saves a reusable application skill pack.++For each meaningful state, the learner should gather:++- screenshot evidence+- Accessibility tree+- focused app/window metadata+- visible text+- actionable elements+- menus, buttons, fields, panels, and tabs+- navigation path+- what changed from the previous state++The learner should default to safe exploration: open menus, inspect tabs,+focus fields, navigate panels, and avoid destructive/send/purchase/save-overwrite+actions unless the user explicitly approves.++The reusable output should be distilled, not just raw captures:++- `SKILL.md` for human/model instructions+- structured app profile JSON+- workflow recipes+- generated scripts in `scripts/`+- verification rules+- safety notes+- optional redacted evidence artifacts++Future agents use the learned app skill by searching for the relevant skill,+loading its bounded instructions, and then using any validated scripts or+workflow tools exposed by that skill.++## Intent Rules++Never infer semantic user intent by string matching raw user input. Do not add+phrase lists, prefixes, suffixes, regexes, app-name checks, greeting/help+classifiers, or natural-language command-text matching to decide what the user+wants.++Pass the turn through an LLM or another typed model/runtime boundary first. Once+structured output exists, deterministic code may validate typed fields, schema+values, tool names, permissions, app identifiers, filesystem paths,+Accessibility constants, and other non-semantic technical data.## Verification-Use `swift test` from `apps/Donkey/` for the supported runtime and harness-coverage.+Use `swift test` from `apps/Donkey/`.-Harness tests should prove that non-actionable turns receive conversational-responses, ambiguous actionable turns ask specific clarification questions,-validated actions still run through catalog and guardrail checks, follow-ups get-the right thread context, and context packets stay bounded and redacted where-needed.+Generic harness tests should cover:-Runtime tests should continue covering coordinator lifecycle ordering, event-persistence, task-intent validation, local-app catalog resolution, observation,-Accessibility control discovery, guarded input, review-first document form-fill,-model routing, memory retrieval, redaction, latency reports, artifacts, window-resolution, and manual capture.+- tool registration and unknown-tool rejection+- permission stop/resume+- clarification stop/resume+- pause, resume, interrupt, cancel, complete, and fail-safe states+- multiple active tasks with isolated state+- one-tool-at-a-time execution loops+- skill registration, search, loading, and filesystem discovery+- script discovery, generation metadata, validation gates, and execution gates-Manual smoke checks remain useful for window enumeration, manual capture, local-runtime setup/status, and dry-run latency reports, but they should support the-documented behavior rather than becoming the behavior definition.+Computer-use tests should cover app search, element retrieval, guarded element+actions, screenshot/Accessibility evidence boundaries, and verification failure+recovery.## Source Entry Points-Start in `apps/Donkey/Sources/Donkey/` for pointer-prompt integration,-`apps/Donkey/Sources/DonkeyContracts/` for shared contracts,-`apps/Donkey/Sources/DonkeyRuntime/` for runtime execution and guardrails, and-`apps/Donkey/Sources/DonkeyAI/` for model routing and adapters. Tests live in-`apps/Donkey/Tests/DonkeyRuntimeTests/`.+Start in:++- `apps/Donkey/Sources/DonkeyHarness/` for generic harness lifecycle, tool+ registry, skill discovery, and script descriptors.+- `apps/Donkey/Sources/DonkeyContracts/` for shared contracts that cross module+ boundaries.+- `apps/Donkey/Sources/DonkeyRuntime/` for guarded runtime execution,+ Accessibility, app/window observation, and input backends.+- `apps/Donkey/Sources/DonkeyAI/` for hosted model routing and adapters.+- `apps/Donkey/Sources/Donkey/` for pointer-prompt integration.++Tests live in `apps/Donkey/Tests/DonkeyRuntimeTests/`.diff --git a/plans/master-plan.md b/plans/master-plan.mdindex 76c0a3bf..1923d60c 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -21,7 +21,39 @@ even when there are no active tasks.## Current Sequence-No active implementation tasks.+1. Route pointer-prompt execution through the generic harness lifecycle. Replace+ the old direct local-app command path with thread load/create, task+ load/create, context compaction, planning, one-tool execution, verification,+ recovery, and stop/resume gates.+2. Back the generic harness thread store with durable local storage. Persist+ threads, events, assets, task snapshots, pending continuations, summaries,+ compacted-context metadata, and active task ids through the generic store+ contract instead of UI-specific persistence.+3. Replace old task-intent model schemas as the primary planning output. Hosted+ model boundaries should produce structured intent, ambiguity/risk,+ context needs, plan steps, verification criteria, fallbacks, and+ clarification policy for the generic harness.+4. Implement real generic tool executors. Cover memory lookup, app lookup,+ screen observation, element discovery, guarded element actions, text and+ keyboard input, AppleScript generation/execution, verification, and lifecycle+ operations behind the registry.+5. Make smart compaction central for every model and planner call. Preserve the+ current turn, active task state, pending gates, summaries, recent useful+ events, assets, and tool traces while storing bulky screenshots, full+ Accessibility trees, script source, and long outputs as artifacts.+6. Move app-specific behavior into skills. Music, Notes, Numbers, browser+ workflows, app knowledge, and future app-specific behavior should live in+ skill packs, plugin/catalog data, generated artifacts, or memory instead of+ core Swift prompt branches.+7. Build the application-learning task. It should safely explore an app, capture+ screenshots and Accessibility trees, distill surfaces/workflows, generate+ scripts where useful, validate them, and save a reusable skill pack.+8. Wire pause, resume, interruption, clarification, and permission gates into+ the UI. The notch/task UI should control generic harness tasks and show the+ exact pending question, approval, paused state, or changed-course state.+9. Delete old app-specific paths once the generic path covers them. Remove+ hardcoded Music/Notes/Numbers/media/weather-style prompt rules, catalog+ special cases, repair logic, and demo-only workflow branches.## Invariants