Open source CapCut alternative.
TypeScript
Route pointer prompt through generic harness
David Le688aaa1c45e1
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex a074e594..2934e689 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -67,7 +67,6 @@ extension PointerPromptCommandHandling {struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {var catalog: LocalAppTaskCatalog- var appHarnessRouter: AppHarnessTurnRoutervar localModelResolver: LocalModelTaskIntentResolvervar liveRunner: LocalAppTaskLiveRunnervar redactor: AIHarnessRedactor@@ -75,7 +74,6 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {var coordinatorRegistry: PointerPromptRunCoordinatorRegistryvar genericHarnessLifecycle: AppHarnessGenericLifecyclevar memoryStore: SQLiteAgentMemoryStore?- var agentVisualizationPlanResolver: any AgentVisualizationPlanResolvinginit(catalog: LocalAppTaskCatalog = .defaultLocal(),@@ -85,11 +83,9 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {memoryRetriever: SemanticRunMemoryRetriever = SemanticRunMemoryRetriever(),coordinatorRegistry: PointerPromptRunCoordinatorRegistry = PointerPromptRunCoordinatorRegistry(),genericHarnessLifecycle: AppHarnessGenericLifecycle = AppHarnessGenericLifecycle(),- memoryStore: SQLiteAgentMemoryStore? = .shared,- agentVisualizationPlanResolver: any AgentVisualizationPlanResolving = DisabledAgentVisualizationPlanResolver()+ memoryStore: SQLiteAgentMemoryStore? = .shared) {self.catalog = catalog- self.appHarnessRouter = AppHarnessTurnRouter(catalog: catalog)self.coordinatorRegistry = coordinatorRegistryself.localModelResolver = localModelResolver ?? LocalModelTaskIntentResolver(catalog: catalog)self.liveRunner = liveRunner ?? LocalAppTaskLiveRunner(@@ -102,7 +98,6 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {self.memoryRetriever = memoryRetrieverself.genericHarnessLifecycle = genericHarnessLifecycleself.memoryStore = memoryStore- self.agentVisualizationPlanResolver = agentVisualizationPlanResolver}func handleSubmittedCommand(@@ -112,57 +107,6 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {let traceID = "pointer-prompt-\(UUID().uuidString)"let taskID = context?.task.id ?? traceIDlogSubmittedCommand(command, traceID: traceID, taskID: taskID, context: context)- let visualizationResolution = await agentVisualizationPlanResolver.resolveVisualizationPlan(- AgentVisualizationPlanResolverRequest(- command: command,- runtimeCapabilities: Self.runtimeCapabilities(for: catalog),- cacheSnippets: [],- sourceTraceID: traceID- )- )- if let resolvedVisualizationPlan = visualizationResolution.visualizationPlan {- let visualizationPlan = groundAgentVisualizationPlan(resolvedVisualizationPlan)- guard let cursorOverlayRequest = visualizationPlan.cursorOverlayRequest() else {- return await continueHandlingNonVisualizationCommand(- command: command,- context: context,- traceID: traceID,- taskID: taskID- )- }- let result = PointerPromptCommandHandlingResult(- status: .completed,- threadStatus: .chatting,- decision: AppHarnessDecision(- kind: .respond,- message: "Showing you.",- traceID: traceID,- metadata: [- "structuredDecision": "true",- "router": "agentVisualization"- ]- ),- summary: "Showing you.",- taskLabel: visualizationPlan.title,- traceID: traceID,- metadata: cursorOverlayRequest.metadata.merging([- "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,- "appHarness.context.traceID": traceID,- "agentVisualization.modelCallID": visualizationResolution.trace.id,- "agentVisualization.modelStatus": visualizationResolution.trace.status.rawValue,- "agentVisualization.validationStatus": visualizationResolution.trace.validationStatus,- "agentVisualization.confidence": Self.formatLatency(visualizationResolution.confidence),- "agentVisualization.reason": visualizationResolution.reason,- "agentVisualization.stepCount": String(visualizationPlan.steps.count)- ]) { current, _ in current },- documentReviewRequest: nil,- agentVisualizationPlan: visualizationPlan,- cursorOverlayRequest: cursorOverlayRequest- )- logHandlingResult(result, stage: "agentVisualization", hint: "Showing a visual-only agent action visualization.")- return result- }-return await continueHandlingNonVisualizationCommand(command: command,context: context,@@ -178,10 +122,6 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {taskID: String) async -> PointerPromptCommandHandlingResult {let harnessRequest = Self.harnessRequest(command: command, context: context)- let routing = appHarnessRouter.route(- request: harnessRequest,- traceID: traceID- )let genericPreparedTurn = await genericHarnessLifecycle.preparePointerPromptTurn(request: harnessRequest,pointerTask: context?.task,@@ -189,59 +129,28 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {availableToolNames: Self.genericHarnessToolNames(),grantedPermissions: Self.pointerPromptGrantedPermissions)- logRouting(command: command, traceID: traceID, taskID: taskID, routing: routing)- switch routing.outcome.decision.kind {- case .respond:- let result = PointerPromptCommandHandlingResult(- status: .completed,- threadStatus: .chatting,- decision: routing.outcome.decision,- summary: routing.outcome.assistantResponse ?? "Tell me what local app task you want to work on.",- taskLabel: nil,- traceID: traceID,- metadata: Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome)- .merging(Self.genericHarnessMetadata(preparedTurn: genericPreparedTurn)) { current, _ in current },- documentReviewRequest: nil,- agentVisualizationPlan: nil,- cursorOverlayRequest: nil- )- _ = await genericHarnessLifecycle.coordinator.complete(- taskID: genericPreparedTurn.task.id,- reason: "Pointer prompt routed to conversation response"- )- logHandlingResult(result, stage: "conversation", hint: routingHint(for: routing))- return result- case .askClarification:- let result = PointerPromptCommandHandlingResult(- status: .needsConfirmation,- threadStatus: .waitingForClarification,- decision: routing.outcome.decision,- summary: routing.outcome.assistantResponse ?? "What detail should I use?",- taskLabel: nil,++ if command.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ let decision = AppHarnessDecision(+ kind: .noOp,traceID: traceID,- metadata: Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome)- .merging(Self.genericHarnessMetadata(preparedTurn: genericPreparedTurn)) { current, _ in current },- documentReviewRequest: nil,- agentVisualizationPlan: nil,- cursorOverlayRequest: nil- )- _ = await genericHarnessLifecycle.coordinator.waitForUser(- taskID: genericPreparedTurn.task.id,- question: result.summary,- reason: "Pointer prompt routing needs clarification"+ metadata: [+ "structuredDecision": "true",+ "router": "emptyTurn"+ ])- logHandlingResult(result, stage: "routing", hint: routingHint(for: routing))- return result- case .noOp:let result = PointerPromptCommandHandlingResult(status: .completed,threadStatus: .chatting,- decision: routing.outcome.decision,+ decision: decision,summary: "",taskLabel: nil,traceID: traceID,- metadata: Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome)- .merging(Self.genericHarnessMetadata(preparedTurn: genericPreparedTurn)) { current, _ in current },+ metadata: [+ "appHarness.decision": decision.kind.rawValue,+ "appHarness.decision.traceID": traceID,+ "appHarness.router": "emptyTurn"+ ].merging(Self.genericHarnessMetadata(preparedTurn: genericPreparedTurn)) { current, _ in current },documentReviewRequest: nil,agentVisualizationPlan: nil,cursorOverlayRequest: nil@@ -252,8 +161,6 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)logHandlingResult(result, stage: "empty", hint: "Empty command; no action was run.")return result- case .openReview, .runLocalTask:- break}let coordinator = await coordinatorRegistry.coordinator(for: taskID)@@ -279,6 +186,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {let localModelResult = await localModelResolver.resolve(command: commandRedaction.redactedText,contextSnippets: redactedContextSnippets,+ availableToolNames: Self.genericHarnessToolNames(),sourceTraceID: traceID)let resolution = localModelResult.resolution@@ -296,10 +204,10 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)let modelObservability = AIModelObservabilityReportBuilder.build(from: [localModelResult.trace])let modelMetadata = [- "appHarness.decision": routing.outcome.decision.kind.rawValue,- "appHarness.context.promptCharacters": String(routing.contextPacket.promptText.count),- "appHarness.context.redactionCount": String(routing.contextPacket.redactionCount),- "intentParser": "hostedModel",+ "appHarness.router": "genericHarnessPlanner",+ "appHarness.context.promptCharacters": String(genericPreparedTurn.compactedContext.promptText.count),+ "appHarness.context.redactionCount": String(redactionCount),+ "intentParser": "hostedHarnessPlanner","latency.commandParseMS": Self.formatLatency(parseLatencyMS),"modelCallID": localModelResult.trace.id,"modelCallStatus": localModelResult.trace.status.rawValue,@@ -319,8 +227,8 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {await coordinator.recordToolEvent(capability: .model,decision: .allow,- toolName: "local-task-intent-parser",- summary: "Parsed local app command",+ toolName: "generic-harness-planner",+ summary: "Planned pointer prompt turn",traceID: traceID,metadata: ["modelCallID": localModelResult.trace.id,@@ -329,6 +237,50 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {])+ if Self.shouldAskClarificationBeforeLocalTask(resolution) {+ let question = Self.clarificationQuestion(for: resolution)+ let decision = AppHarnessDecision(+ kind: .askClarification,+ message: question,+ missingDetail: resolution.metadata["reason"],+ traceID: traceID,+ metadata: [+ "structuredDecision": "true",+ "router": "modelClarification",+ "resolution.status": resolution.status.rawValue+ ]+ )+ let handlingResult = PointerPromptCommandHandlingResult(+ status: .needsConfirmation,+ threadStatus: .waitingForClarification,+ decision: decision,+ summary: question,+ taskLabel: nil,+ traceID: traceID,+ metadata: modelMetadata.merging([+ "appHarness.decision": AppHarnessDecisionKind.askClarification.rawValue,+ "router": "modelClarification",+ "resolution.status": resolution.status.rawValue,+ "resolution.reason": resolution.metadata["reason"] ?? ""+ ]) { _, new in new },+ documentReviewRequest: nil,+ agentVisualizationPlan: nil,+ cursorOverlayRequest: nil+ )+ _ = await genericHarnessLifecycle.coordinator.waitForUser(+ taskID: taskID,+ question: question,+ reason: "Generic harness planner requested clarification"+ )+ await coordinatorRegistry.finish(taskID: taskID)+ logHandlingResult(+ handlingResult,+ stage: "clarification",+ hint: "The harness planner asked for a missing detail before selecting an action tool."+ )+ return handlingResult+ }+if Self.shouldRespondWithoutLocalTask(resolution) {let response = Self.conversationResponse(for: resolution)let decision = AppHarnessDecision(@@ -337,7 +289,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {traceID: traceID,metadata: ["structuredDecision": "true",- "router": "modelNoTaskIntent",+ "router": "modelConversation","resolution.status": resolution.status.rawValue])@@ -350,12 +302,10 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {traceID: traceID,metadata: modelMetadata.merging(["appHarness.decision": AppHarnessDecisionKind.respond.rawValue,- "router": "modelNoTaskIntent",+ "router": "modelConversation","resolution.status": resolution.status.rawValue,"resolution.reason": resolution.metadata["reason"] ?? ""- ]) { _, new in new }.merging(- Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome)- ) { current, _ in current },+ ]) { _, new in new },documentReviewRequest: nil,agentVisualizationPlan: nil,cursorOverlayRequest: nil@@ -373,6 +323,16 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {return handlingResult}+ let decision = AppHarnessDecision(+ kind: .runLocalTask,+ taskIntentID: resolution.intent?.intentID,+ traceID: traceID,+ metadata: [+ "structuredDecision": "true",+ "router": "modelLocalAppTask",+ "resolution.status": resolution.status.rawValue+ ]+ )_ = await genericHarnessLifecycle.planLocalTaskRun(taskID: taskID,resolution: resolution,@@ -391,6 +351,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {traceID: traceID,resolution: resolution,metadata: modelMetadata.merging([+ "appHarness.decision": AppHarnessDecisionKind.runLocalTask.rawValue,"genericHarness.taskID": toolContext.taskID,"genericHarness.toolCallID": toolContext.call.id]) { current, _ in current }@@ -428,13 +389,14 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {let handlingResult = PointerPromptCommandHandlingResult(status: result.status,threadStatus: threadStatus(for: result, runStep: runStep),- decision: routing.outcome.decision,+ decision: decision,summary: summary(for: result, runStep: runStep),taskLabel: taskLabel(for: result),traceID: traceID,- metadata: Self.genericHarnessTaskMetadata(runStep?.task).merging(result.metadata) { current, _ in current }.merging(- Self.contextPacketMetadata(routing.contextPacket, outcome: routing.outcome)- ) { current, _ in current }+ metadata: Self.genericHarnessTaskMetadata(runStep?.task).merging(result.metadata) { current, _ in current }.merging([+ "appHarness.decision": AppHarnessDecisionKind.runLocalTask.rawValue,+ "appHarness.router": "modelLocalAppTask"+ ]) { current, _ in current }.merging(Self.genericHarnessMetadata(preparedTurn: genericPreparedTurn,runStep: runStep,@@ -563,25 +525,6 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)}- private func logRouting(- command: String,- traceID: String,- taskID: String,- routing: AppHarnessRoutingResult- ) {- guard PointerPromptLog.isEnabled else { return }-- let decision = routing.outcome.decision.kind.rawValue- let router = routing.outcome.metadata["router"] ?? "unknown"- let resolution = routing.outcome.resolution?.status.rawValue ?? "none"- let missingDetail = routing.outcome.missingDetail ?? ""- let taskType = routing.outcome.resolution?.definition?.taskType ?? ""- let hint = routingHint(for: routing)- PointerPromptLog.commands.notice(- "command routed traceID=\(traceID, privacy: .public) taskID=\(taskID, privacy: .public) decision=\(decision, privacy: .public) router=\(router, privacy: .public) resolution=\(resolution, privacy: .public) taskType=\(taskType, privacy: .public) missingDetail=\(missingDetail, privacy: .public) hint=\(hint, privacy: .public) command=\(command, privacy: .public)"- )- }-private func logSubmittedCommand(_ command: String,traceID: String,@@ -691,18 +634,6 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {return nil}- private func routingHint(for routing: AppHarnessRoutingResult) -> String {- let router = routing.outcome.metadata["router"] ?? ""- switch router {- case "followUpActionContext":- return "Follow-up turn is being treated as an action for the existing task."- case "modelIntent":- return "Using hosted model intent classification through the Donkey backend."- default:- return "Router path \(router.isEmpty ? "unknown" : router)."- }- }-private func runHint(for result: LocalAppTaskLiveRunResult) -> String {if let reason = result.metadata["reason"], !reason.isEmpty {return "Run reason: \(reason)."@@ -781,6 +712,32 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {&& resolution.metadata["assistantResponse"]?.isEmpty == false}+ private static func shouldAskClarificationBeforeLocalTask(_ resolution: LocalAppTaskCatalogResolution) -> Bool {+ guard resolution.status == .needsConfirmation,+ shouldRespondWithoutLocalTask(resolution) == false+ else {+ return false+ }+ return resolution.intent == nil+ || resolution.intent?.needsConfirmation == true+ || resolution.metadata["responseMode"] == "clarification"+ }++ private static func clarificationQuestion(for resolution: LocalAppTaskCatalogResolution) -> String {+ if let assistantResponse = resolution.metadata["assistantResponse"],+ !assistantResponse.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ return assistantResponse+ }+ if let reason = resolution.metadata["reason"],+ !reason.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ let readableDetail = reason+ .split(separator: "_")+ .joined(separator: " ")+ return "What \(readableDetail) should I use?"+ }+ return "What detail should I use?"+ }+private static func conversationResponse(for resolution: LocalAppTaskCatalogResolution) -> String {if let assistantResponse = resolution.metadata["assistantResponse"],!assistantResponse.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {@@ -1199,22 +1156,6 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)}- private static func contextPacketMetadata(- _ packet: AppHarnessContextPacket,- outcome: AppHarnessRoutingOutcome- ) -> [String: String] {- [- "appHarness.decision": outcome.decision.kind.rawValue,- "appHarness.decision.traceID": outcome.decision.traceID,- "appHarness.missingDetail": outcome.missingDetail ?? "",- "appHarness.context.traceID": packet.traceID,- "appHarness.context.eventCount": String(packet.recentEvents.count),- "appHarness.context.assetCount": String(packet.assets.count),- "appHarness.context.promptCharacters": String(packet.promptText.count),- "appHarness.context.redactionCount": String(packet.redactionCount)- ]- }-private static func genericHarnessMetadata(preparedTurn: AppHarnessGenericLifecyclePreparedTurn,runStep: HarnessStepExecutionResult? = nil,diff --git a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swiftindex ed374bf7..4c74acd4 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift@@ -191,6 +191,8 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {"Command: \(request.command)","Relevant local cache:",request.contextSnippets.joined(separator: "\n"),+ "Available harness tools:",+ request.availableToolNames.joined(separator: "\n"),"App skill guidance:",skillGuidance,"App finder catalog JSON:",@@ -201,13 +203,16 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {}private static let instructions = [- "Decide whether the user is asking Donkey to run one of the provided local app task definitions.",+ "You are the first model boundary for Donkey's generic agent harness. Decide how the harness should handle the user turn before any tool-specific executor is selected.","Return strict JSON only using the generic harness planning schema.",- "First decide whether Command is an executable local-app task or a conversation turn.",- "Executable local-app task means all three are clear: action, destination or target app/item, and enough payload to execute safely.",+ "First decide whether Command should be answered conversationally, should ask a clarification, or should use a supported tool path.",+ "Choose conversation for greetings, questions, brainstorming, explanations, status requests, malformed requests, or any turn that does not require external action.",+ "Choose clarification when the user wants action but a specific required detail is missing or the action is dangerously ambiguous.",+ "Choose localAppTask only when the user is asking Donkey to operate a supported local app or local item and all three are clear: action, destination or target app/item, and enough payload to execute safely.","Always fill structuredIntent, ambiguityRisk, contextNeeds, planSteps, verificationCriteria, fallbacks, clarificationPolicy, and metadata.",- "If Command is a greeting, conversation, question, malformed request, or lacks a real executable payload, set structuredIntent.route conversation, taskType \"none\", targetAppName \"none\", empty entities and normalizedEntities, confidence 0, needsConfirmation false, no planSteps with toolName values, and metadata.responseMode \"conversation\" with metadata.assistantResponse containing a brief natural-language reply.",- "For supported actions, set structuredIntent.route localAppTask, choose only a provided taskType and target app, and fill entities and normalizedEntities with the concrete values needed by required entity rules.",+ "If Command is conversation, set structuredIntent.route conversation, taskType \"none\", targetAppName \"none\", empty entities and normalizedEntities, confidence 0, needsConfirmation false, no planSteps with toolName values, and metadata.responseMode \"conversation\" with metadata.assistantResponse containing a brief natural-language reply.",+ "If Command needs clarification before tool use, set structuredIntent.route clarification, taskType \"none\", targetAppName \"none\" unless a target is already known, needsConfirmation true, ambiguityRisk.shouldAskBeforeActing true, clarificationPolicy.shouldAsk true, and include one specific question.",+ "For supported local app actions, set structuredIntent.route localAppTask, choose only a provided taskType and target app, and fill entities and normalizedEntities with the concrete values needed by required entity rules.","Use the generic local_app_interaction task type for executable local app requests that need a model-planned app workflow and do not have a more specific provided task type.","Use ambiguityRisk for safe, recoverable, or dangerous ambiguity. Dangerous ambiguity and missing required details must set structuredIntent.needsConfirmation true, ambiguityRisk.shouldAskBeforeActing true, and clarificationPolicy.shouldAsk true with a specific question.","Use contextNeeds for app lookup, memory lookup, screen observation, element discovery, or skill lookup needed before or during execution.",diff --git a/apps/Donkey/Sources/DonkeyAI/LocalModelTaskIntentResolver.swift b/apps/Donkey/Sources/DonkeyAI/LocalModelTaskIntentResolver.swiftindex 64f31548..8a9a93e5 100644--- a/apps/Donkey/Sources/DonkeyAI/LocalModelTaskIntentResolver.swift+++ b/apps/Donkey/Sources/DonkeyAI/LocalModelTaskIntentResolver.swift@@ -17,6 +17,7 @@ public struct LocalModelTaskIntentResolver: Sendable {public func resolve(command: String,contextSnippets: [String] = [],+ availableToolNames: [String] = [],sourceTraceID: String) async -> (resolution: LocalAppTaskCatalogResolution, trace: AIModelCallTrace) {let request = TaskIntentAdapterRequest(@@ -24,6 +25,7 @@ public struct LocalModelTaskIntentResolver: Sendable {taskDefinitions: catalog.taskDefinitions,contextSnippets: contextSnippets,appFinderCatalog: catalog.appFinderCatalogEntries(),+ availableToolNames: availableToolNames,sourceTraceID: sourceTraceID)let result = await adapter.parseTaskIntent(request)diff --git a/apps/Donkey/Sources/DonkeyAI/TaskIntentParsingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/TaskIntentParsingAdapter.swiftindex e3a13c9c..3dc676d6 100644--- a/apps/Donkey/Sources/DonkeyAI/TaskIntentParsingAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/TaskIntentParsingAdapter.swift@@ -8,6 +8,7 @@ public struct TaskIntentAdapterRequest: Equatable, Sendable {public var contextSnippets: [String]public var skillSnippets: [String]public var appFinderCatalog: [LocalAppFinderCatalogEntry]+ public var availableToolNames: [String]public var sourceTraceID: Stringpublic var routeRequest: AIModelRouteRequest@@ -17,6 +18,7 @@ public struct TaskIntentAdapterRequest: Equatable, Sendable {contextSnippets: [String] = [],skillSnippets: [String]? = nil,appFinderCatalog: [LocalAppFinderCatalogEntry] = [],+ availableToolNames: [String] = [],sourceTraceID: String,routeRequest: AIModelRouteRequest = AIModelRouteRequest(jobType: .taskIntent,@@ -28,6 +30,7 @@ public struct TaskIntentAdapterRequest: Equatable, Sendable {self.taskDefinitions = taskDefinitionsself.contextSnippets = TaskIntentModelContextCompactor.compact(contextSnippets)self.appFinderCatalog = appFinderCatalog+ self.availableToolNames = availableToolNamesself.skillSnippets = TaskIntentModelContextCompactor(maxSnippets: 8,maxSnippetCharacters: 1_200,diff --git a/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift b/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swiftindex 5338526e..bb37035d 100644--- a/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift+++ b/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift@@ -391,9 +391,9 @@ enum TaskIntentWireCodec {metadata["missingEntity"] = missingRequiredEntity.name}- var confidence = wire.confidence- var needsConfirmation = wire.needsConfirmation || missingRequiredEntity != nil- var actionPlan = wire.actionPlan.tools.isEmpty ? nil : wire.actionPlan+ let confidence = wire.confidence+ let needsConfirmation = wire.needsConfirmation || missingRequiredEntity != nil+ let actionPlan = wire.actionPlan.tools.isEmpty ? nil : wire.actionPlanlet primaryEntity = definition.verificationEntityName.flatMap { normalizedEntities[$0] }?? normalizedEntities.values.sorted().first@@ -429,10 +429,19 @@ enum TaskIntentWireCodec {var metadata = hostedPlanningMetadata(from: wire)metadata["parser"] = parserName- metadata["reason"] = nonEmpty(metadata["reason"]) ?? "noSupportedTaskIntent"- metadata["responseMode"] = "conversation"- metadata["assistantResponse"] = nonEmpty(metadata["assistantResponse"])- ?? defaultConversationAssistantResponse+ let route = wire.structuredIntent.route+ if route == "clarification" || wire.clarificationPolicy.shouldAsk {+ metadata["reason"] = nonEmpty(metadata["reason"]) ?? "clarificationRequired"+ metadata["responseMode"] = "clarification"+ metadata["assistantResponse"] = nonEmpty(metadata["assistantResponse"])+ ?? wire.clarificationPolicy.questions.first(where: { nonEmpty($0) != nil })+ ?? defaultConversationAssistantResponse+ } else {+ metadata["reason"] = nonEmpty(metadata["reason"]) ?? "noSupportedTaskIntent"+ metadata["responseMode"] = "conversation"+ metadata["assistantResponse"] = nonEmpty(metadata["assistantResponse"])+ ?? defaultConversationAssistantResponse+ }metadata["taskType"] = "none"metadata["targetApp"] = wire.structuredIntent.targetAppNamereturn metadatadiff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swiftindex 4e1f2043..ee986054 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift@@ -195,7 +195,7 @@ public struct AppHarnessGenericLifecycle: Sendable {clarificationPolicy: Self.clarificationPolicy(from: plannedStepMetadata),confidence: intent.confidence,metadata: [- "planner": "genericHarnessPointerPromptBridge",+ "planner": "genericHarnessLocalAppPlan","traceID": traceID,"resolution.status": resolution.status.rawValue,"modelPlan.stepCount": String(modelPlanSteps.count),@@ -285,8 +285,8 @@ public struct AppHarnessGenericLifecycle: Sendable {public static func localTaskRunDescriptor() -> HarnessToolDescriptor {HarnessToolDescriptor(name: AppHarnessGenericLifecycleToolNames.localAppRun,- pluginID: "pointer-prompt.migration",- summary: "Execute a resolved pointer-prompt local app task as one generic harness step.",+ pluginID: "pointer-prompt.local-app",+ summary: "Execute a resolved pointer-prompt local app task through the Mac local-app executor.",inputSchema: ["resolutionStatus": "Resolved, waiting, unsupported, or unavailable local app task status.","taskType": "Resolved local app task type.",@@ -298,8 +298,7 @@ public struct AppHarnessGenericLifecycle: Sendable {requiredContext: ["structured intent", "local app task resolution", "generic harness task"],verificationHints: ["Run state.verify after this step records its terminal evidence."],metadata: [- "migrationBridge": "true",- "legacyBackend": "LocalAppTaskLiveRunner"+ "executor": "LocalAppTaskLiveRunner"])}diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex e28d6a20..78f12d62 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -9,9 +9,9 @@ recovery, permission gates, clarification, pause/resume, interruption, andmulti-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.+Agent capabilities plug into that module through tools, skills, scripts,+plugins, catalogs, or memory. Core harness code does not contain app-specific+branches, phrase lists, or one-off workflow conditionals.Bundled and learned local-app skills carry app-specific planning guidance.Task-intent model calls receive relevant skills as bounded context alongside@@ -19,18 +19,19 @@ the generic task definitions, generated or user-reviewed app catalog data, andmemory. The core runtime does not ship app-specific Weather, Music, Notes, orNumbers task branches.-The existing pointer-prompt and local-app runner code still bridges concrete-desktop workflows while the product migrates onto the generic harness. New work-should build toward the generic registry and avoid app-specific runtime paths.+Pointer prompt uses the generic harness as the entrypoint for conversation,+clarification, planning, and tool selection. Local desktop actions are+registered harness tools rather than a separate default path.-Pointer-prompt local-app execution now enters the generic lifecycle before it-uses 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 clarification-policy. The bridge stores that packet in generic task intent/plan state, then-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.+Pointer-prompt turns enter the generic lifecycle before any local-app executor+is selected. The hosted planning boundary emits the+`generic_harness_planning` packet: structured intent, ambiguity/risk, context+needs, plan steps, verification criteria, fallbacks, and clarification policy.+Conversation and clarification routes stop in the harness. A structured+local-app route registers the Mac local-app execution tool, and the harness+stores the model packet in generic task intent/plan state before using+registry-backed executors for validation, state updates, gates, and lifecycle+behavior.## Core Model@@ -70,8 +71,8 @@ Threads are the durable conversation record. The generic harness defines athread-store boundary for threads, events, assets, task snapshots, task events,and compaction snapshots. In tests this can be backed by an in-memory store; inthe app the default generic lifecycle uses a file-backed local store under the-user's Application Support directory. Harness code should depend on this-generic store contract rather than reaching into UI-specific persistence.+user's Application Support directory. Harness code depends on this generic+store contract rather than reaching into UI-specific persistence.A thread record stores the user-visible conversation and the active task ids.Task state stores execution details such as world model, plan, permissions,@@ -92,14 +93,14 @@ the most recent useful events, recent tool summaries, memory summaries, and abounded 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+script source, and long tool outputs are saved as artifacts or structuredrecords and summarized into the prompt. Compaction metadata records what wasincluded, dropped, or truncated so the decision remains inspectable.-Pointer-prompt hosted intent calls consume the generic compacted thread context-rather than ad hoc thread snippets. Slow planner calls consume a compacted run-context, including bounded world-state, failure, hint, memory, and semantic-memory summaries.+Hosted planning calls consume the generic compacted thread context rather than+ad hoc thread snippets. Slow planner calls consume a compacted run context,+including bounded world-state, failure, hint, memory, and semantic memory+summaries.The pointer-prompt notch mirrors generic task stop states. Permission gatesshow the pending tool and missing permissions, and the approval control grants@@ -109,7 +110,7 @@ attention text.## Turn Flow-The desired loop is:+The loop is:```textintake@@ -122,8 +123,8 @@ intake-> recover, continue, clarify, or complete```-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+The harness does not treat desktop work as a single model completion. It+observes, acts, verifies, and replans. The planner may propose the next toolstep, but deterministic Swift owns task state, tool validation, permissions,focus checks, execution, and result recording.@@ -146,8 +147,8 @@ the pending continuation, asks a specific question, and resumes only after theanswer 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+Recoverable ambiguity uses available tools first, such as memory, app search,+screen observation, or skill lookup, and asks only if uncertainty remainsmaterial.## Tools And Plugins@@ -177,9 +178,8 @@ screen observation, UI element discovery and action, text and keyboard input,AppleScript generation/execution, state verification, and task lifecyclecontrol.-Additional plugins should register tools through the same interface. App-knowledge belongs in plugins, skills, catalogs, or memory, not in core harness-conditionals.+Plugins register tools through the same interface. App knowledge belongs in+plugins, skills, catalogs, or memory, not in core harness conditionals.## Computer Use@@ -199,9 +199,9 @@ Element actions execute only after the harness validates:- 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.+Models choose semantic targets and tool calls. They do not micromanage pixels.+Coordinate input is fallback evidence only and must pass the same guarded+execution checks as other input.## AppleScript And Scripts@@ -218,7 +218,7 @@ action metadata, and verification evidence attached.App-specific AppleScript belongs in skill-local scripts or generated artifacts.The guarded backend renders explicit `appleScript.source` or-`appleScript.template` metadata; it should not grow app-named script helpers.+`appleScript.template` metadata; it does not contain app-named script helpers.Do not add app-named Swift helpers such as `musicPlaybackScript` or`openFooScript`. If an app needs automation knowledge, put it in a skill,@@ -244,8 +244,8 @@ registry indexes:Skill lookup lets the planner find relevant instructions by structured taskneed. 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.+Skills are shared infrastructure. They are reusable by any agent or task, not+private scratch memory for one run.Built-in app skills live as resource skill packs under`apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/`. They are loaded@@ -256,7 +256,7 @@ before being sent to model boundaries.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.+Python, JavaScript, Swift, and additional language types.Each script descriptor records:@@ -290,7 +290,7 @@ draft, record bounded screenshot and Accessibility evidence, propose reversibleexploration candidates from technical Accessibility roles/actions, distill anapp profile and workflow recipes, and save a reusable skill pack.-For each meaningful state, the learner should gather:+For each meaningful state, the learner gathers:- screenshot evidence- Accessibility tree@@ -301,11 +301,11 @@ For each meaningful state, the learner should gather:- 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+The learner defaults to safe exploration: open menus, inspect tabs, focus+fields, navigate panels, and avoid destructive/send/purchase/save-overwriteactions unless the user explicitly approves.-The reusable output should be distilled, not just raw captures:+The reusable output is distilled, not just raw captures:- `SKILL.md` for human/model instructions- structured app profile JSON@@ -316,8 +316,8 @@ The reusable output should be distilled, not just raw captures:- optional redacted evidence artifactsValidated generated scripts owned by the learned skill are copied into the-skill-local `scripts/` directory when the pack is saved. Future agents use the-learned app skill by searching for the relevant skill, loading its bounded+skill-local `scripts/` directory when the pack is saved. Agents use the learned+app skill by searching for the relevant skill, loading its boundedinstructions, and then using any validated scripts or workflow tools exposed bythat skill.@@ -337,7 +337,7 @@ Accessibility constants, and other non-semantic technical data.Use `swift test` from `apps/Donkey/`.-Generic harness tests should cover:+Generic harness tests cover:- tool registration and unknown-tool rejection- permission stop/resume@@ -348,9 +348,9 @@ Generic harness tests should cover:- skill registration, search, loading, and filesystem discovery- script discovery, generation metadata, validation gates, and execution gates-Computer-use tests should cover app search, element retrieval, guarded element-actions, screenshot/Accessibility evidence boundaries, and verification failure-recovery.+Computer-use tests cover app search, element retrieval, guarded element+actions, screenshot/Accessibility evidence boundaries, and verification+failure recovery.## Source Entry Points