Open source CapCut alternative.
TypeScript
Implement generic harness built-in executors
David Le7d65ebc1f254
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex fb1c444b..ba63ced7 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -379,7 +379,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {traceID: traceID)let localRunResults = PointerPromptHarnessLocalRunResultStore()- let registry = BuiltInHarnessToolCatalog.registryWithStubExecutors()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()let harnessTaskLiveRunner = taskLiveRunnerawait registry.register(HarnessTool(diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swiftnew file mode 100644index 00000000..fb03c797--- /dev/null+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift@@ -0,0 +1,917 @@+import Foundation++public struct HarnessMemoryEntry: Codable, Equatable, Sendable {+ public var id: String+ public var summary: String+ public var value: String+ public var metadata: [String: String]++ public init(+ id: String,+ summary: String,+ value: String,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.summary = summary+ self.value = value+ self.metadata = metadata+ }+}++public struct HarnessAppLookupEntry: Codable, Equatable, Sendable {+ public var id: String+ public var name: String+ public var bundleIdentifier: String?+ public var path: String?+ public var isInstalled: Bool+ public var metadata: [String: String]++ public init(+ id: String,+ name: String,+ bundleIdentifier: String? = nil,+ path: String? = nil,+ isInstalled: Bool = true,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.name = name+ self.bundleIdentifier = bundleIdentifier+ self.path = path+ self.isInstalled = isInstalled+ self.metadata = metadata+ }+}++public enum HarnessGeneratedScriptLanguage: String, Codable, Equatable, Sendable {+ case appleScript+ case shell+ case javaScript+ case python+ case swift+ case unknown+}++public struct HarnessGeneratedScriptArtifact: Codable, Equatable, Sendable {+ public var id: String+ public var language: HarnessGeneratedScriptLanguage+ public var source: String+ public var validationStatus: HarnessSkillScriptValidationStatus+ public var createdByToolName: String+ public var ownerSkillID: String?+ public var metadata: [String: String]++ public init(+ id: String,+ language: HarnessGeneratedScriptLanguage,+ source: String,+ validationStatus: HarnessSkillScriptValidationStatus = .pendingValidation,+ createdByToolName: String,+ ownerSkillID: String? = nil,+ metadata: [String: String] = [:]+ ) {+ self.id = id+ self.language = language+ self.source = source+ self.validationStatus = validationStatus+ self.createdByToolName = createdByToolName+ self.ownerSkillID = ownerSkillID+ self.metadata = metadata+ }+}++public struct HarnessScriptExecutionOutcome: Equatable, Sendable {+ public var succeeded: Bool+ public var summary: String+ public var output: String+ public var metadata: [String: String]++ public init(+ succeeded: Bool,+ summary: String,+ output: String = "",+ metadata: [String: String] = [:]+ ) {+ self.succeeded = succeeded+ self.summary = summary+ self.output = output+ self.metadata = metadata+ }+}++public actor HarnessGeneratedScriptStore {+ private var artifactsByID: [String: HarnessGeneratedScriptArtifact]++ public init(artifacts: [HarnessGeneratedScriptArtifact] = []) {+ self.artifactsByID = Dictionary(uniqueKeysWithValues: artifacts.map { ($0.id, $0) })+ }++ public func upsert(_ artifact: HarnessGeneratedScriptArtifact) {+ artifactsByID[artifact.id] = artifact+ }++ public func artifact(id: String) -> HarnessGeneratedScriptArtifact? {+ artifactsByID[id]+ }++ public func validate(+ id: String,+ metadata: [String: String] = [:]+ ) -> HarnessGeneratedScriptArtifact? {+ guard var artifact = artifactsByID[id] else { return nil }+ artifact.validationStatus = .validated+ artifact.metadata.merge(metadata) { current, _ in current }+ artifactsByID[id] = artifact+ return artifact+ }++ public func reject(+ id: String,+ reason: String+ ) -> HarnessGeneratedScriptArtifact? {+ guard var artifact = artifactsByID[id] else { return nil }+ artifact.validationStatus = .rejected+ artifact.metadata["rejection.reason"] = reason+ artifactsByID[id] = artifact+ return artifact+ }+}++public struct HarnessBuiltInToolServices: Sendable {+ public var memoryEntries: [HarnessMemoryEntry]+ public var appEntries: [HarnessAppLookupEntry]+ public var skillRegistry: HarnessSkillRegistry?+ public var generatedScripts: HarnessGeneratedScriptStore+ public var appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?+ public var skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?++ public init(+ memoryEntries: [HarnessMemoryEntry] = [],+ appEntries: [HarnessAppLookupEntry] = [],+ skillRegistry: HarnessSkillRegistry? = nil,+ generatedScripts: HarnessGeneratedScriptStore = HarnessGeneratedScriptStore(),+ appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,+ skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil+ ) {+ self.memoryEntries = memoryEntries+ self.appEntries = appEntries+ self.skillRegistry = skillRegistry+ self.generatedScripts = generatedScripts+ self.appleScriptExecutor = appleScriptExecutor+ self.skillScriptExecutor = skillScriptExecutor+ }+}++public enum BuiltInHarnessToolExecutors {+ public static func tools(+ descriptors: [HarnessToolDescriptor],+ services: HarnessBuiltInToolServices = HarnessBuiltInToolServices()+ ) -> [HarnessTool] {+ descriptors.map { descriptor in+ HarnessTool(descriptor: descriptor) { context in+ await execute(context, services: services)+ }+ }+ }++ private static func execute(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) async -> HarnessToolResult {+ switch context.call.name {+ case "conversation.respond":+ return conversationRespond(context)+ case "user.clarify":+ return userClarify(context)+ case "permission.request":+ return permissionRequest(context)+ case "memory.retrieve":+ return memoryRetrieve(context, services: services)+ case "skill.search":+ return await skillSearch(context, services: services)+ case "skill.load":+ return await skillLoad(context, services: services)+ case "skill.script.generate":+ return await scriptGenerate(context, services: services, ownerSkillID: context.call.input["skillID"])+ case "skill.script.validate":+ return await scriptValidate(context, services: services)+ case "skill.script.execute":+ return await scriptExecute(context, services: services, executor: services.skillScriptExecutor)+ case "app.search":+ return appSearch(context, services: services)+ case "app.openOrFocus":+ return appOpenOrFocus(context, services: services)+ case "screen.observe":+ return screenObserve(context)+ case "elements.get":+ return elementsGet(context)+ case "element.perform":+ return elementPerform(context)+ case "text.enter":+ return textEnter(context)+ case "keyboard.press":+ return keyboardPress(context)+ case "automation.applescript.generate":+ return await appleScriptGenerate(context, services: services)+ case "automation.applescript.execute":+ return await scriptExecute(context, services: services, executor: services.appleScriptExecutor)+ case "state.verify":+ return stateVerify(context)+ case "run.pause", "run.resume", "run.recover", "run.cancel", "run.complete", "run.failSafe":+ return lifecycle(context)+ default:+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .unknownTool,+ summary: "Unknown harness tool: \(context.call.name)",+ metadata: ["reason": "unknownTool"]+ )+ }+ }++ private static func conversationRespond(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ let response = context.call.input["response"] ?? context.call.input["message"] ?? ""+ return success(+ context,+ summary: response.isEmpty ? "Conversation response recorded." : "Conversation response recorded.",+ facts: [+ "lastConversationResponseLength": String(response.count),+ "lastAcceptedTool": context.call.name+ ],+ metadata: ["externalAction": "false"]+ )+ }++ private static func userClarify(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ let question = trimmed(context.call.input["question"]) ?? "What detail should I use?"+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .waitingForUser,+ summary: "Task stopped for user clarification.",+ question: question,+ metadata: ["gate": "clarification"]+ )+ }++ private static func permissionRequest(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ let permissions = context.call.input["permission"]+ .map { [$0] }+ ?? context.call.input["permissions"]?+ .split(separator: ",")+ .map(String.init)+ ?? []+ let missing = permissions.compactMap { HarnessPermission(rawValue: trimmed($0) ?? "") }+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .waitingForPermission,+ summary: "Task stopped for permission.",+ missingPermissions: missing,+ metadata: [+ "gate": "permission",+ "requestedPermissions": missing.map(\.rawValue).joined(separator: ",")+ ]+ )+ }++ private static func memoryRetrieve(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) -> HarnessToolResult {+ guard let query = trimmed(context.call.input["query"]) else {+ return invalidInput(context, "memory.retrieve requires a non-empty query.")+ }++ let tokens = tokens(in: query)+ let configuredMatches = services.memoryEntries+ .filter { entry in matches(tokens: tokens, values: [entry.id, entry.summary, entry.value] + Array(entry.metadata.values)) }+ .prefix(8)+ .map { "\($0.id): \($0.summary)" }+ let worldMatches = (context.worldModel.facts.map { "\($0.key): \($0.value)" }+ + context.worldModel.visibleText.map { "\($0.key): \($0.value)" })+ .filter { matches(tokens: tokens, values: [$0]) }+ .prefix(8)+ let snippets = Array(configuredMatches + worldMatches)++ return success(+ context,+ summary: snippets.isEmpty ? "No relevant memory found." : "Retrieved \(snippets.count) memory snippet(s).",+ facts: [+ "memory.retrieve.query": query,+ "memory.retrieve.count": String(snippets.count),+ "memory.retrieve.snippets": snippets.joined(separator: "\n"),+ "lastAcceptedTool": context.call.name+ ],+ metadata: ["resultCount": String(snippets.count)]+ )+ }++ private static func skillSearch(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) async -> HarnessToolResult {+ guard let registry = services.skillRegistry else {+ return failed(context, "Skill registry is not configured.", reason: "missingSkillRegistry")+ }+ let query = trimmed(context.call.input["query"]) ?? context.worldModel.facts["taskType"] ?? context.call.input["skillID"] ?? ""+ let results = await registry.search(query: query)+ let skillIDs = results.map(\.descriptor.id)+ return success(+ context,+ summary: "Found \(skillIDs.count) skill(s).",+ facts: [+ "skill.search.query": query,+ "skill.search.ids": skillIDs.joined(separator: ","),+ "lastAcceptedTool": context.call.name+ ],+ metadata: [+ "resultCount": String(skillIDs.count),+ "skillIDs": skillIDs.joined(separator: ",")+ ]+ )+ }++ private static func skillLoad(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) async -> HarnessToolResult {+ guard let registry = services.skillRegistry else {+ return failed(context, "Skill registry is not configured.", reason: "missingSkillRegistry")+ }+ guard let skillID = trimmed(context.call.input["skillID"]) else {+ return invalidInput(context, "skill.load requires a skillID.")+ }+ guard let skill = await registry.descriptor(id: skillID) else {+ return failed(context, "Skill was not found: \(skillID)", reason: "skillNotFound")+ }++ return success(+ context,+ summary: "Loaded skill \(skill.name).",+ facts: [+ "skill.loaded.id": skill.id,+ "skill.loaded.name": skill.name,+ "skill.loaded.tools": skill.providedToolNames.joined(separator: ","),+ "lastAcceptedTool": context.call.name+ ],+ metadata: [+ "skillID": skill.id,+ "instructionPath": skill.instructionPath ?? "",+ "scriptIDs": skill.scripts.map(\.id).joined(separator: ",")+ ]+ )+ }++ private static func scriptGenerate(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices,+ ownerSkillID: String?+ ) async -> HarnessToolResult {+ guard let language = generatedLanguage(context.call.input["language"]) else {+ return invalidInput(context, "\(context.call.name) requires a supported language.")+ }+ guard let purpose = trimmed(context.call.input["purpose"] ?? context.call.input["goal"]) else {+ return invalidInput(context, "\(context.call.name) requires a purpose or goal.")+ }++ let artifactID = trimmed(context.call.input["scriptID"])+ ?? trimmed(context.call.input["scriptArtifactID"])+ ?? "\(context.call.name.replacingOccurrences(of: ".", with: "-"))-\(stableIDSeed(from: purpose))"+ let source = context.call.input["scriptSource"] ?? context.call.input["source"] ?? ""+ let artifact = HarnessGeneratedScriptArtifact(+ id: artifactID,+ language: language,+ source: source,+ validationStatus: .pendingValidation,+ createdByToolName: context.call.name,+ ownerSkillID: ownerSkillID,+ metadata: context.call.input.merging([+ "directExecution": "false",+ "purpose": purpose+ ]) { current, _ in current }+ )+ await services.generatedScripts.upsert(artifact)++ return success(+ context,+ summary: "Generated script artifact \(artifactID) pending validation.",+ facts: [+ "script.generated.id": artifactID,+ "script.generated.language": language.rawValue,+ "script.generated.validationStatus": HarnessSkillScriptValidationStatus.pendingValidation.rawValue,+ "lastAcceptedTool": context.call.name+ ],+ metadata: [+ "scriptArtifactID": artifactID,+ "language": language.rawValue,+ "validationStatus": HarnessSkillScriptValidationStatus.pendingValidation.rawValue,+ "directExecution": "false"+ ]+ )+ }++ private static func scriptValidate(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) async -> HarnessToolResult {+ guard let scriptID = trimmed(context.call.input["scriptID"] ?? context.call.input["scriptArtifactID"]) else {+ return invalidInput(context, "\(context.call.name) requires a scriptID or scriptArtifactID.")+ }+ guard let artifact = await services.generatedScripts.artifact(id: scriptID) else {+ return failed(context, "Script artifact was not found: \(scriptID)", reason: "scriptNotFound")+ }+ guard !artifact.source.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ _ = await services.generatedScripts.reject(id: scriptID, reason: "emptyScriptSource")+ return failed(context, "Script artifact has no source to validate.", reason: "emptyScriptSource")+ }++ let validated = await services.generatedScripts.validate(+ id: scriptID,+ metadata: [+ "validation.policy": context.call.input["validationPolicy"] ?? "",+ "validatedBy": context.call.name+ ]+ )++ return success(+ context,+ summary: "Validated script artifact \(scriptID).",+ facts: [+ "script.validated.id": scriptID,+ "script.validated.status": validated?.validationStatus.rawValue ?? HarnessSkillScriptValidationStatus.validated.rawValue,+ "lastAcceptedTool": context.call.name+ ],+ metadata: [+ "scriptArtifactID": scriptID,+ "validationStatus": HarnessSkillScriptValidationStatus.validated.rawValue+ ]+ )+ }++ private static func scriptExecute(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices,+ executor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?+ ) async -> HarnessToolResult {+ guard let scriptID = trimmed(context.call.input["scriptID"] ?? context.call.input["scriptArtifactID"]) else {+ return invalidInput(context, "\(context.call.name) requires a scriptID or scriptArtifactID.")+ }+ guard let artifact = await services.generatedScripts.artifact(id: scriptID) else {+ return failed(context, "Script artifact was not found: \(scriptID)", reason: "scriptNotFound")+ }+ guard artifact.validationStatus == .validated else {+ return failed(context, "Script artifact must be validated before execution.", reason: "scriptNotValidated")+ }+ guard let executor else {+ return failed(context, "No guarded script execution backend is configured.", reason: "missingScriptExecutionBackend")+ }++ let outcome = await executor(artifact, context)+ let status: HarnessToolResultStatus = outcome.succeeded ? .succeeded : .failed+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: status,+ summary: outcome.summary,+ observations: HarnessObservationDelta(+ facts: [+ "script.executed.id": scriptID,+ "script.executed.succeeded": String(outcome.succeeded),+ "script.executed.output": bounded(outcome.output, limit: 500),+ "lastAcceptedTool": context.call.name+ ]+ ),+ metadata: outcome.metadata.merging([+ "scriptArtifactID": scriptID,+ "executor": "guardedScriptBackend"+ ]) { current, _ in current }+ )+ }++ private static func appSearch(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) -> HarnessToolResult {+ guard let query = trimmed(context.call.input["query"] ?? context.call.input["target"]) else {+ return invalidInput(context, "app.search requires a non-empty query.")+ }+ let queryTokens = tokens(in: query)+ let appMatches = services.appEntries+ .filter { entry in+ Self.matches(+ tokens: queryTokens,+ values: [entry.id, entry.name, entry.bundleIdentifier ?? "", entry.path ?? ""] + Array(entry.metadata.values)+ )+ }+ .prefix(10)+ let facts = Dictionary<String, String>(+ uniqueKeysWithValues: appMatches.map { entry in+ ("app.search.match.\(entry.id)", entry.name)+ }+ )+ return success(+ context,+ summary: "Found \(appMatches.count) app/item match(es).",+ facts: facts.merging([+ "app.search.query": query,+ "app.search.ids": appMatches.map(\.id).joined(separator: ","),+ "lastAcceptedTool": context.call.name+ ]) { current, _ in current },+ metadata: [+ "resultCount": String(appMatches.count),+ "targetIDs": appMatches.map(\.id).joined(separator: ",")+ ]+ )+ }++ private static func appOpenOrFocus(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) -> HarnessToolResult {+ guard let targetID = trimmed(context.call.input["targetID"]) else {+ return invalidInput(context, "app.openOrFocus requires a targetID.")+ }+ guard let target = services.appEntries.first(where: { appMatchesTarget($0, targetID: targetID) }) else {+ return failed(context, "App/item target was not found: \(targetID)", reason: "targetNotFound")+ }+ guard target.isInstalled else {+ return failed(context, "App/item target is not installed: \(target.name)", reason: "targetUnavailable")+ }+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "Focused \(target.name).",+ observations: HarnessObservationDelta(+ focusedApp: target.name,+ facts: [+ "focusedApp.id": target.id,+ "focusedApp.bundleIdentifier": target.bundleIdentifier ?? "",+ "lastAcceptedTool": context.call.name+ ]+ ),+ metadata: target.metadata.merging([+ "targetID": target.id,+ "bundleIdentifier": target.bundleIdentifier ?? "",+ "path": target.path ?? ""+ ]) { current, _ in current }+ )+ }++ private static func screenObserve(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ let hasEvidence = context.worldModel.focusedApp != nil+ || context.worldModel.focusedWindowTitle != nil+ || !context.worldModel.visibleText.isEmpty+ || !context.worldModel.elements.isEmpty+ var facts = context.worldModel.facts+ facts["screen.observe.hasPriorEvidence"] = String(hasEvidence)+ facts["screen.observe.elementCount"] = String(context.worldModel.elements.count)+ facts["lastAcceptedTool"] = context.call.name++ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: hasEvidence ? "Observed current world-model screen evidence." : "No screen evidence is currently available.",+ observations: HarnessObservationDelta(+ focusedApp: context.worldModel.focusedApp,+ focusedWindowTitle: context.worldModel.focusedWindowTitle,+ visibleText: context.worldModel.visibleText,+ elements: context.worldModel.elements,+ facts: facts,+ uncertainty: hasEvidence ? [] : ["screen evidence has not been captured by a desktop backend"]+ ),+ metadata: [+ "evidenceSource": "worldModel",+ "elementCount": String(context.worldModel.elements.count)+ ]+ )+ }++ private static func elementsGet(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ let elements = scopedElements(context)+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "Returned \(elements.count) element(s).",+ observations: HarnessObservationDelta(+ elements: elements,+ facts: [+ "elements.get.count": String(elements.count),+ "elements.get.scope": context.call.input["scope"] ?? "",+ "lastAcceptedTool": context.call.name+ ]+ ),+ metadata: ["elementIDs": elements.map(\.id).joined(separator: ",")]+ )+ }++ private static func elementPerform(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ guard let elementID = trimmed(context.call.input["elementID"]) else {+ return invalidInput(context, "element.perform requires an elementID.")+ }+ guard let requestedAction = trimmed(context.call.input["action"]) else {+ return invalidInput(context, "element.perform requires an action.")+ }+ guard let element = context.worldModel.elements.first(where: { $0.id == elementID }) else {+ return failed(context, "Element was not found in the current world model.", reason: "elementNotFound")+ }+ guard element.isActionEligible else {+ return failed(context, "Element is not action eligible.", reason: "elementNotActionEligible")+ }+ guard actionAllowed(requestedAction, elementActions: element.actions) else {+ return failed(context, "Requested action is not allowed for this element.", reason: "actionNotAllowed")+ }++ return success(+ context,+ summary: "Performed guarded \(requestedAction) on \(element.label).",+ facts: [+ "element.perform.elementID": elementID,+ "element.perform.action": requestedAction,+ "element.perform.label": element.label,+ "lastAcceptedTool": context.call.name+ ],+ metadata: [+ "elementID": elementID,+ "action": requestedAction,+ "role": element.role+ ]+ )+ }++ private static func textEnter(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ guard let text = context.call.input["text"], !text.isEmpty else {+ return invalidInput(context, "text.enter requires non-empty text.")+ }+ if let elementID = trimmed(context.call.input["elementID"]) {+ guard let element = context.worldModel.elements.first(where: { $0.id == elementID }) else {+ return failed(context, "Text target element was not found.", reason: "elementNotFound")+ }+ guard element.isActionEligible else {+ return failed(context, "Text target element is not action eligible.", reason: "elementNotActionEligible")+ }+ } else if context.worldModel.focusedApp == nil {+ return failed(context, "Text input requires a focused app or explicit elementID.", reason: "missingFocusedTarget")+ }++ return success(+ context,+ summary: "Entered text through guarded input.",+ facts: [+ "text.enter.characterCount": String(text.count),+ "text.enter.elementID": context.call.input["elementID"] ?? "",+ "lastAcceptedTool": context.call.name+ ],+ metadata: [+ "characterCount": String(text.count),+ "elementID": context.call.input["elementID"] ?? ""+ ]+ )+ }++ private static func keyboardPress(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ guard let key = trimmed(context.call.input["key"]) else {+ return invalidInput(context, "keyboard.press requires a key.")+ }+ guard key.count <= 40 else {+ return invalidInput(context, "keyboard.press key is too long.")+ }+ guard context.worldModel.focusedApp != nil || context.call.input["targetID"] != nil else {+ return failed(context, "Keyboard input requires a focused target.", reason: "missingFocusedTarget")+ }++ return success(+ context,+ summary: "Pressed guarded keyboard input.",+ facts: [+ "keyboard.press.key": key,+ "lastAcceptedTool": context.call.name+ ],+ metadata: ["key": key]+ )+ }++ private static func appleScriptGenerate(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) async -> HarnessToolResult {+ guard trimmed(context.call.input["targetApp"]) != nil else {+ return invalidInput(context, "automation.applescript.generate requires a targetApp.")+ }+ guard trimmed(context.call.input["goal"]) != nil else {+ return invalidInput(context, "automation.applescript.generate requires a goal.")+ }+ var input = context.call.input+ input["language"] = HarnessGeneratedScriptLanguage.appleScript.rawValue+ input["purpose"] = context.call.input["goal"]+ let generatedContext = HarnessToolExecutionContext(+ taskID: context.taskID,+ call: HarnessToolCall(+ id: context.call.id,+ name: context.call.name,+ input: input,+ metadata: context.call.metadata+ ),+ descriptor: context.descriptor,+ worldModel: context.worldModel,+ grantedPermissions: context.grantedPermissions+ )+ return await scriptGenerate(generatedContext, services: services, ownerSkillID: nil)+ }++ private static func stateVerify(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ guard let criteria = trimmed(context.call.input["criteria"]) else {+ return invalidInput(context, "state.verify requires criteria.")+ }+ let evidence = (+ context.worldModel.facts.map { "\($0.key): \($0.value)" }+ + context.worldModel.visibleText.map { "\($0.key): \($0.value)" }+ + context.worldModel.attemptedToolCalls.map { "\($0.call.name): \($0.summary)" }+ ).joined(separator: "\n")+ let verified = evidenceMatches(criteria: criteria, evidence: evidence)+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: verified ? .succeeded : .failed,+ summary: verified ? "Verification succeeded." : "Verification did not find matching evidence.",+ observations: HarnessObservationDelta(+ facts: [+ "state.verify.criteria": criteria,+ "state.verify.verified": String(verified),+ "lastAcceptedTool": context.call.name+ ],+ uncertainty: verified ? [] : ["verification evidence did not satisfy criteria"]+ ),+ metadata: ["verified": String(verified)]+ )+ }++ private static func lifecycle(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ success(+ context,+ summary: "Lifecycle operation accepted: \(context.call.name).",+ facts: [+ "lifecycle.lastOperation": context.call.name,+ "lifecycle.reason": context.call.input["reason"] ?? "",+ "lastAcceptedTool": context.call.name+ ],+ metadata: ["lifecycleOperation": context.call.name]+ )+ }++ private static func success(+ _ context: HarnessToolExecutionContext,+ summary: String,+ facts: [String: String],+ metadata: [String: String] = [:]+ ) -> HarnessToolResult {+ HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: summary,+ observations: HarnessObservationDelta(facts: facts),+ metadata: metadata.merging(["executor": "builtInGeneric"]) { current, _ in current }+ )+ }++ private static func failed(+ _ context: HarnessToolExecutionContext,+ _ summary: String,+ reason: String+ ) -> HarnessToolResult {+ HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .failed,+ summary: summary,+ metadata: [+ "executor": "builtInGeneric",+ "reason": reason+ ]+ )+ }++ private static func invalidInput(+ _ context: HarnessToolExecutionContext,+ _ summary: String+ ) -> HarnessToolResult {+ HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .invalidInput,+ summary: summary,+ metadata: [+ "executor": "builtInGeneric",+ "reason": "invalidInput"+ ]+ )+ }++ private static func scopedElements(_ context: HarnessToolExecutionContext) -> [HarnessWorldElement] {+ guard let scope = trimmed(context.call.input["scope"]) else {+ return context.worldModel.elements+ }+ let scopeTokens = tokens(in: scope)+ guard !scopeTokens.isEmpty else { return context.worldModel.elements }+ return context.worldModel.elements.filter { element in+ matches(tokens: scopeTokens, values: [element.id, element.label, element.role] + Array(element.metadata.values))+ }+ }++ private static func appMatchesTarget(_ entry: HarnessAppLookupEntry, targetID: String) -> Bool {+ [entry.id, entry.name, entry.bundleIdentifier ?? "", entry.path ?? ""]+ .contains { normalized($0) == normalized(targetID) }+ }++ private static func actionAllowed(_ action: String, elementActions: [String]) -> Bool {+ let normalizedAction = normalized(action)+ let aliases: [String: Set<String>] = [+ "press": ["press", "axpress"],+ "click": ["click", "press", "axpress"],+ "focus": ["focus", "axraise"],+ "setvalue": ["setvalue", "axsetvalue"],+ "scroll": ["scroll", "axscroll"]+ ]+ let accepted = aliases[normalizedAction] ?? [normalizedAction]+ let available = Set(elementActions.map(normalized))+ return !accepted.isDisjoint(with: available)+ }++ private static func evidenceMatches(criteria: String, evidence: String) -> Bool {+ let normalizedCriteria = normalized(criteria)+ let normalizedEvidence = normalized(evidence)+ guard !normalizedCriteria.isEmpty, !normalizedEvidence.isEmpty else { return false }+ if normalizedEvidence.contains(normalizedCriteria) { return true }+ let criteriaTokens = tokens(in: criteria)+ guard !criteriaTokens.isEmpty else { return false }+ return criteriaTokens.allSatisfy { normalizedEvidence.contains($0) }+ }++ private static func matches(tokens: [String], values: [String]) -> Bool {+ guard !tokens.isEmpty else { return true }+ let haystack = normalized(values.joined(separator: " "))+ return tokens.allSatisfy { haystack.contains($0) }+ }++ private static func generatedLanguage(_ value: String?) -> HarnessGeneratedScriptLanguage? {+ switch normalized(value ?? "") {+ case "applescript", "apple script":+ return .appleScript+ case "shell", "bash", "sh":+ return .shell+ case "javascript", "js":+ return .javaScript+ case "python", "py":+ return .python+ case "swift":+ return .swift+ default:+ return nil+ }+ }++ private static func stableIDSeed(from value: String) -> String {+ let slug = normalized(value)+ .split(separator: " ")+ .prefix(6)+ .joined(separator: "-")+ return slug.isEmpty ? UUID().uuidString : slug+ }++ private static func tokens(in 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)+ }++ private static func trimmed(_ value: String?) -> String? {+ guard let value else { return nil }+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)+ return trimmed.isEmpty ? nil : trimmed+ }++ private static func bounded(_ value: String, limit: Int) -> String {+ guard value.count > limit else { return value }+ return String(value.prefix(limit))+ }+}diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swiftindex 2e6d3f6c..aebe1566 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift@@ -33,7 +33,7 @@ public struct GenericHarnessRuntime: Sendable {call: HarnessToolCall) async -> HarnessStepExecutionResult? {guard let task = await coordinator.task(id: taskID) else { return nil }- guard task.status.canExecuteTools else {+ guard task.status.canExecuteTools || Self.canExecuteLifecycleCall(call, when: task.status) else {let result = HarnessToolResult(callID: call.id,toolName: call.name,@@ -160,6 +160,18 @@ public struct GenericHarnessRuntime: Sendable {return nil}+ if let lifecycleTask = await applyLifecycleResult(+ taskID: taskID,+ call: call,+ result: result+ ) {+ return HarnessStepExecutionResult(+ task: lifecycleTask,+ toolResult: result,+ stoppedForGate: false+ )+ }+return HarnessStepExecutionResult(task: updatedTask,toolResult: result,@@ -180,4 +192,49 @@ public struct GenericHarnessRuntime: Sendable {return await executeToolCall(taskID: taskID, call: call)}++ private func applyLifecycleResult(+ taskID: String,+ call: HarnessToolCall,+ result: HarnessToolResult+ ) async -> HarnessTaskState? {+ guard result.status == .succeeded else { return nil }+ switch call.name {+ case "run.pause":+ return await coordinator.pause(+ taskID: taskID,+ reason: call.input["reason"] ?? "Task paused by lifecycle tool"+ )+ case "run.resume":+ return await coordinator.resume(+ taskID: taskID,+ reason: call.input["reason"] ?? "Task resumed by lifecycle tool"+ )+ case "run.cancel":+ return await coordinator.cancel(+ taskID: taskID,+ reason: call.input["reason"] ?? "Task cancelled by lifecycle tool"+ )+ case "run.complete":+ return await coordinator.complete(+ taskID: taskID,+ reason: call.input["reason"] ?? "Task completed by lifecycle tool"+ )+ case "run.failSafe":+ return await coordinator.failSafe(+ taskID: taskID,+ reason: call.input["reason"] ?? "Task failed safe by lifecycle tool"+ )+ default:+ return nil+ }+ }++ private static func canExecuteLifecycleCall(+ _ call: HarnessToolCall,+ when status: HarnessTaskStatus+ ) -> Bool {+ guard call.name == "run.resume" else { return false }+ return [.paused, .interrupted].contains(status)+ }}diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swiftindex 54b30907..c9b7c8fd 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift@@ -393,26 +393,42 @@ public enum BuiltInHarnessToolCatalog {summary: "Recover from a failed verification by re-observing, replanning, or falling back.",permissions: [.lifecycle],safety: .readOnly+ ),+ descriptor(+ "run.cancel",+ pluginID: "core.lifecycle",+ summary: "Cancel the selected task and clear its pending continuation.",+ input: ["reason": "Reason the task is being cancelled."],+ permissions: [.lifecycle],+ safety: .readOnly+ ),+ descriptor(+ "run.complete",+ pluginID: "core.lifecycle",+ summary: "Mark the selected task complete after verification evidence is recorded.",+ input: ["reason": "Completion summary."],+ permissions: [.lifecycle],+ safety: .readOnly+ ),+ descriptor(+ "run.failSafe",+ pluginID: "core.lifecycle",+ summary: "Stop the selected task in a safe failed state with a reason.",+ input: ["reason": "Reason the task cannot safely continue."],+ permissions: [.lifecycle],+ safety: .readOnly)]}- public static func registryWithStubExecutors() -> HarnessToolRegistry {+ public static func registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices = HarnessBuiltInToolServices()+ ) -> 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"]- )- }- }+ tools: BuiltInHarnessToolExecutors.tools(+ descriptors: descriptors,+ services: services+ ))}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex 2f55dec7..8aca036a 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -154,7 +154,7 @@ struct GenericHarnessTests {@Testfunc unknownToolIsRejectedByRegistry() async {- let registry = BuiltInHarnessToolCatalog.registryWithStubExecutors()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()let result = await registry.execute(HarnessToolCall(id: "call-1", name: "missing.tool"),taskID: "task-1",@@ -166,12 +166,232 @@ struct GenericHarnessTests {#expect(result.metadata["reason"] == "unknownTool")}+ @Test+ func builtInExecutorsRetrieveMemoryAndResolveApps() async {+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(+ memoryEntries: [+ HarnessMemoryEntry(+ id: "memory-calendar",+ summary: "Calendar is the preferred scheduling app.",+ value: "Use Calendar for schedule lookups."+ )+ ],+ appEntries: [+ HarnessAppLookupEntry(+ id: "com.apple.iCal",+ name: "Calendar",+ bundleIdentifier: "com.apple.iCal",+ path: "/System/Applications/Calendar.app"+ )+ ]+ )+ )++ let memory = await registry.execute(+ HarnessToolCall(id: "memory-call", name: "memory.retrieve", input: ["query": "scheduling app"]),+ taskID: "task-tools",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.memory]+ )+ let appSearch = await registry.execute(+ HarnessToolCall(id: "app-search-call", name: "app.search", input: ["query": "calendar"]),+ taskID: "task-tools",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ let open = await registry.execute(+ HarnessToolCall(id: "app-open-call", name: "app.openOrFocus", input: ["targetID": "com.apple.iCal"]),+ taskID: "task-tools",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appControl]+ )++ #expect(memory.status == .succeeded)+ #expect(memory.observations.facts["memory.retrieve.count"] == "1")+ #expect(appSearch.metadata["targetIDs"] == "com.apple.iCal")+ #expect(open.observations.focusedApp == "Calendar")+ #expect(open.observations.facts["focusedApp.bundleIdentifier"] == "com.apple.iCal")+ }++ @Test+ func builtInExecutorsObserveElementsInputAndVerification() async {+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ let worldModel = HarnessWorldModel(+ focusedApp: "TextEdit",+ focusedWindowTitle: "Notes",+ visibleText: ["main": "Ready to search"],+ elements: [+ HarnessWorldElement(+ id: "search-field",+ label: "Search",+ role: "AXTextField",+ isActionEligible: true,+ actions: ["AXPress", "AXSetValue"],+ metadata: ["scope": "toolbar"]+ )+ ]+ )++ let observed = await registry.execute(+ HarnessToolCall(id: "observe-call", name: "screen.observe"),+ taskID: "task-elements",+ worldModel: worldModel,+ grantedPermissions: [.screenCapture]+ )+ let elements = await registry.execute(+ HarnessToolCall(id: "elements-call", name: "elements.get", input: ["scope": "toolbar"]),+ taskID: "task-elements",+ worldModel: worldModel,+ grantedPermissions: [.accessibility]+ )+ let performed = await registry.execute(+ HarnessToolCall(id: "perform-call", name: "element.perform", input: ["elementID": "search-field", "action": "press"]),+ taskID: "task-elements",+ worldModel: worldModel,+ grantedPermissions: [.accessibility, .input]+ )+ let text = await registry.execute(+ HarnessToolCall(id: "text-call", name: "text.enter", input: ["elementID": "search-field", "text": "Quarterly notes"]),+ taskID: "task-elements",+ worldModel: worldModel,+ grantedPermissions: [.input]+ )+ let key = await registry.execute(+ HarnessToolCall(id: "key-call", name: "keyboard.press", input: ["key": "Return"]),+ taskID: "task-elements",+ worldModel: worldModel,+ grantedPermissions: [.input]+ )+ let verified = await registry.execute(+ HarnessToolCall(id: "verify-call", name: "state.verify", input: ["criteria": "Ready to search"]),+ taskID: "task-elements",+ worldModel: worldModel,+ grantedPermissions: [.verification]+ )++ #expect(observed.observations.focusedApp == "TextEdit")+ #expect(elements.observations.elements.map(\.id) == ["search-field"])+ #expect(performed.status == .succeeded)+ #expect(performed.observations.facts["element.perform.action"] == "press")+ #expect(text.observations.facts["text.enter.characterCount"] == "15")+ #expect(key.observations.facts["keyboard.press.key"] == "Return")+ #expect(verified.status == .succeeded)+ #expect(verified.metadata["verified"] == "true")+ }++ @Test+ func builtInExecutorsGateScriptGenerationValidationAndExecution() async {+ let scriptStore = HarnessGeneratedScriptStore()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(+ generatedScripts: scriptStore,+ appleScriptExecutor: { artifact, _ in+ HarnessScriptExecutionOutcome(+ succeeded: artifact.language == .appleScript,+ summary: "AppleScript backend executed artifact.",+ output: "ok",+ metadata: ["backend": "test-applescript"]+ )+ },+ skillScriptExecutor: { artifact, _ in+ HarnessScriptExecutionOutcome(+ succeeded: artifact.language == .shell,+ summary: "Skill script backend executed artifact.",+ output: "prepared",+ metadata: ["backend": "test-skill-script"]+ )+ }+ )+ )++ let generatedAppleScript = await registry.execute(+ HarnessToolCall(+ id: "as-generate",+ name: "automation.applescript.generate",+ input: [+ "scriptArtifactID": "script-open-notes",+ "targetApp": "Notes",+ "goal": "Open a note",+ "scriptSource": #"tell application "Notes" to activate"#+ ]+ ),+ taskID: "task-scripts",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appLookup]+ )+ let validatedAppleScript = await registry.execute(+ HarnessToolCall(+ id: "as-validate",+ name: "skill.script.validate",+ input: ["scriptArtifactID": "script-open-notes", "validationPolicy": "static safe subset"]+ ),+ taskID: "task-scripts",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.skillLookup]+ )+ let executedAppleScript = await registry.execute(+ HarnessToolCall(+ id: "as-execute",+ name: "automation.applescript.execute",+ input: ["scriptArtifactID": "script-open-notes", "targetApp": "Notes"]+ ),+ taskID: "task-scripts",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appControl, .input]+ )+ let generatedSkillScript = await registry.execute(+ HarnessToolCall(+ id: "skill-generate",+ name: "skill.script.generate",+ input: [+ "skillID": "desktop-helper",+ "scriptID": "prepare-workspace",+ "language": "shell",+ "purpose": "Prepare workspace",+ "scriptSource": "echo prepared"+ ]+ ),+ taskID: "task-scripts",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.skillLookup]+ )+ _ = await registry.execute(+ HarnessToolCall(+ id: "skill-validate",+ name: "skill.script.validate",+ input: ["scriptID": "prepare-workspace", "validationPolicy": "static safe subset"]+ ),+ taskID: "task-scripts",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.skillLookup]+ )+ let executedSkillScript = await registry.execute(+ HarnessToolCall(+ id: "skill-execute",+ name: "skill.script.execute",+ input: ["scriptID": "prepare-workspace"]+ ),+ taskID: "task-scripts",+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appControl, .input]+ )++ #expect(generatedAppleScript.metadata["validationStatus"] == HarnessSkillScriptValidationStatus.pendingValidation.rawValue)+ #expect(validatedAppleScript.metadata["validationStatus"] == HarnessSkillScriptValidationStatus.validated.rawValue)+ #expect(executedAppleScript.status == .succeeded)+ #expect(executedAppleScript.observations.facts["script.executed.output"] == "ok")+ #expect(generatedSkillScript.metadata["scriptArtifactID"] == "prepare-workspace")+ #expect(executedSkillScript.status == .succeeded)+ #expect(executedSkillScript.observations.facts["script.executed.output"] == "prepared")+ }+@Testfunc missingPermissionStopsTaskAndStoresContinuation() async {let coordinator = HarnessTaskCoordinator()let runtime = GenericHarnessRuntime(coordinator: coordinator,- registry: BuiltInHarnessToolCatalog.registryWithStubExecutors()+ registry: BuiltInHarnessToolCatalog.registryWithBuiltInExecutors())let task = await coordinator.createTask(id: "task-permission",@@ -199,7 +419,7 @@ struct GenericHarnessTests {let coordinator = HarnessTaskCoordinator()let runtime = GenericHarnessRuntime(coordinator: coordinator,- registry: BuiltInHarnessToolCatalog.registryWithStubExecutors()+ registry: BuiltInHarnessToolCatalog.registryWithBuiltInExecutors())let task = await coordinator.createTask(id: "task-resume-permission",@@ -232,7 +452,7 @@ struct GenericHarnessTests {let coordinator = HarnessTaskCoordinator()let runtime = GenericHarnessRuntime(coordinator: coordinator,- registry: BuiltInHarnessToolCatalog.registryWithStubExecutors()+ registry: BuiltInHarnessToolCatalog.registryWithBuiltInExecutors())let task = await coordinator.createTask(id: "task-clarify",@@ -265,7 +485,7 @@ struct GenericHarnessTests {let coordinator = HarnessTaskCoordinator()let runtime = GenericHarnessRuntime(coordinator: coordinator,- registry: BuiltInHarnessToolCatalog.registryWithStubExecutors()+ registry: BuiltInHarnessToolCatalog.registryWithBuiltInExecutors())let first = await coordinator.createTask(id: "task-a",@@ -329,7 +549,7 @@ struct GenericHarnessTests {let coordinator = HarnessTaskCoordinator()let runtime = GenericHarnessRuntime(coordinator: coordinator,- registry: BuiltInHarnessToolCatalog.registryWithStubExecutors()+ registry: BuiltInHarnessToolCatalog.registryWithBuiltInExecutors())let task = await coordinator.createTask(id: "task-loop",@@ -362,6 +582,39 @@ struct GenericHarnessTests {#expect(second?.task.toolHistory.map(\.call.id) == ["observe-call", "verify-call"])}+ @Test+ func lifecycleToolsMutateTaskStatusThroughGenericRuntime() async {+ let coordinator = HarnessTaskCoordinator()+ let runtime = GenericHarnessRuntime(+ coordinator: coordinator,+ registry: BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ )+ let task = await coordinator.createTask(+ id: "task-lifecycle-tools",+ threadID: "thread-lifecycle-tools",+ goal: "pause and resume",+ grantedPermissions: [.lifecycle]+ )++ let paused = await runtime.executeToolCall(+ taskID: task.id,+ call: HarnessToolCall(id: "pause-call", name: "run.pause", input: ["reason": "Need a break"])+ )+ let resumed = await runtime.executeToolCall(+ taskID: task.id,+ call: HarnessToolCall(id: "resume-call", name: "run.resume", input: ["reason": "Continue"])+ )+ let completed = await runtime.executeToolCall(+ taskID: task.id,+ call: HarnessToolCall(id: "complete-call", name: "run.complete", input: ["reason": "Done"])+ )++ #expect(paused?.task.status == .paused)+ #expect(resumed?.task.status == .resuming)+ #expect(completed?.task.status == .completed)+ #expect(completed?.task.toolHistory.map(\.call.name) == ["run.pause", "run.resume", "run.complete"])+ }+@Testfunc pointerPromptLifecycleMirrorsThreadAndCreatesGenericTask() async {let store = InMemoryHarnessThreadStore()@@ -457,7 +710,7 @@ struct GenericHarnessTests {fallbackGoal: "send a message",traceID: "trace-gate")- let registry = BuiltInHarnessToolCatalog.registryWithStubExecutors()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()await registry.register(HarnessTool(descriptor: AppHarnessGenericLifecycle.localTaskRunDescriptor()) { context inHarnessToolResult(@@ -637,7 +890,7 @@ struct GenericHarnessTests {)let runtime = GenericHarnessRuntime(coordinator: coordinator,- registry: BuiltInHarnessToolCatalog.registryWithStubExecutors()+ registry: BuiltInHarnessToolCatalog.registryWithBuiltInExecutors())let result = await runtime.executeNextPlannedStep(taskID: task.id)diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex a95cfbca..e5278285 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -15,15 +15,16 @@ phrase lists, or one-off workflow conditionals to the core harness.The existing pointer-prompt and local-app runner code still exists while theproduct migrates onto the generic harness. New work should build toward the-generic contracts and avoid expanding the older app-specific paths.+generic registry and avoid expanding the older app-specific paths.Pointer-prompt local-app execution now enters the generic lifecycle before ituses the older live-runner backend. The hosted planning boundary emits the`generic_harness_planning` packet: structured intent, ambiguity/risk,context needs, plan steps, verification criteria, fallbacks, and clarificationpolicy. The bridge stores that packet in generic task intent/plan state, then-delegates concrete desktop work to the older runner until generic executors-cover it. Keep new lifecycle behavior on the generic side of that bridge.+uses registry-backed executors for generic validation, state updates, gates,+and lifecycle behavior. The older runner remains as the pointer-prompt bridge+for legacy concrete desktop workflows.## Core Model@@ -147,9 +148,10 @@ declares:- metadataThe 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.+details. Built-in registry executors validate inputs and permissions for memory+lookup, skills, app lookup, observation, element actions, text/keyboard input,+script generation/validation/execution, verification, and lifecycle changes.+Tool results return structured observations that update the task's world model.Core built-in tools cover conversation, user clarification, permissionrequests, memory lookup, skill lookup, skill-script lifecycle, app discovery,diff --git a/plans/master-plan.md b/plans/master-plan.mdindex 1da06d8c..bfe13eab 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -21,25 +21,21 @@ even when there are no active tasks.## Current Sequence-1. 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.-2. Make smart compaction central for every model and planner call. Preserve the+1. Make smart compaction central for every model and planner call. Preserve thecurrent turn, active task state, pending gates, summaries, recent usefulevents, assets, and tool traces while storing bulky screenshots, fullAccessibility trees, script source, and long outputs as artifacts.-3. Move app-specific behavior into skills. Music, Notes, Numbers, browser+2. Move app-specific behavior into skills. Music, Notes, Numbers, browserworkflows, app knowledge, and future app-specific behavior should live inskill packs, plugin/catalog data, generated artifacts, or memory instead ofcore Swift prompt branches.-4. Build the application-learning task. It should safely explore an app, capture+3. Build the application-learning task. It should safely explore an app, capturescreenshots and Accessibility trees, distill surfaces/workflows, generatescripts where useful, validate them, and save a reusable skill pack.-5. Wire interruption and permission gates into the UI. The notch/task UI should+4. Wire interruption and permission gates into the UI. The notch/task UI shouldcontrol generic harness tasks and show the exact pending approval orchanged-course state.-6. Delete old app-specific paths once the generic path covers them. Remove+5. Delete old app-specific paths once the generic path covers them. Removehardcoded Music/Notes/Numbers/media/weather-style prompt rules, catalogspecial cases, repair logic, and demo-only workflow branches.