Skip to content

Open source CapCut alternative.

TypeScript

Support skill-backed local app actions

David Le65b9a39c18a9
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index da3a70be..8becb6ed 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -341,9 +341,12 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
taskID: taskID,
resolution: resolution,
fallbackGoal: commandRedaction.redactedText,
- traceID: traceID
+ traceID: traceID,
+ availableToolNames: Self.genericHarnessToolNames()
+ )
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: LocalAppUserQueryHarnessServices.builtInSkillBackedServices()
)
- let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()
let localStepExecutor = LocalAppHarnessStepExecutor(
command: commandRedaction.redactedText,
traceID: traceID,
@@ -371,7 +374,10 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
step.toolResult?.toolName == LocalAppActionPlanTool.verifyCommand.rawValue
|| step.toolResult?.toolName == LocalAppActionPlanTool.verifyVisibleText.rawValue
}
- let result = await localStepExecutor.currentResult()
+ let result = Self.integratingGenericToolOutcome(
+ into: await localStepExecutor.currentResult(),
+ runSteps: runSteps
+ )
let finalized = await finalizeGenericHarnessTask(
taskID: taskID,
result: result,
@@ -544,6 +550,51 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
}
}
+ private static func integratingGenericToolOutcome(
+ into result: LocalAppTaskLiveRunResult,
+ runSteps: [HarnessStepExecutionResult]
+ ) -> LocalAppTaskLiveRunResult {
+ guard result.actionTraces.isEmpty,
+ result.status == .failedSafe
+ else {
+ return result
+ }
+
+ let toolResults = runSteps.compactMap(\.toolResult)
+ guard let toolResult = toolResults.last else {
+ return result
+ }
+ let completedGenericAction = toolResults.last { result in
+ result.status == .succeeded
+ && (
+ result.toolName == "skill.script.execute"
+ || result.toolName == "automation.applescript.execute"
+ )
+ }
+
+ switch toolResult.status {
+ case .succeeded where completedGenericAction != nil:
+ var completed = result
+ let actionResult = completedGenericAction ?? toolResult
+ completed.status = .completed
+ completed.metadata = result.metadata
+ .merging(actionResult.metadata) { current, _ in current }
+ .merging(toolResult.metadata) { current, _ in current }
+ completed.metadata["reason"] = "genericToolCompleted"
+ completed.metadata["genericTool.completed"] = actionResult.toolName
+ return completed
+ case .waitingForUser:
+ var waiting = result
+ waiting.status = .needsConfirmation
+ waiting.metadata = result.metadata.merging(toolResult.metadata) { current, _ in current }
+ waiting.metadata["reason"] = "genericToolNeedsUser"
+ waiting.metadata["genericTool.waiting"] = toolResult.toolName
+ return waiting
+ default:
+ return result
+ }
+ }
+
private func groundAgentVisualizationPlan(_ plan: AgentVisualizationPlan) -> AgentVisualizationPlan {
let candidates = MacWindowResolver().enumerateCandidates()
guard !candidates.isEmpty else { return plan }
@@ -1104,6 +1155,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
.lifecycle,
.appLookup,
.appControl,
+ .skillLookup,
.screenCapture,
.accessibility,
.input
@@ -1112,7 +1164,12 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
private static func genericHarnessToolNames() -> [String] {
Array(Set(
- BuiltInHarnessToolCatalog.descriptors.map(\.name)
+ BuiltInHarnessToolCatalog.descriptors
+ .filter { descriptor in
+ descriptor.safetyClass != .destructive
+ && descriptor.safetyClass != .sensitive
+ }
+ .map(\.name)
+ LocalAppHarnessStepExecutor.descriptors.map(\.name)
)).sorted()
}
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift
index 7b396e5f..4e04efee 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift
@@ -181,7 +181,10 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
"type": .string("json_schema"),
"name": .string(Self.schemaID),
"strict": .bool(true),
- "schema": Self.jsonValue(TaskIntentWireCodec.genericHarnessPlanningJsonSchema(taskDefinitions: adapterRequest.taskDefinitions))
+ "schema": Self.jsonValue(TaskIntentWireCodec.genericHarnessPlanningJsonSchema(
+ taskDefinitions: adapterRequest.taskDefinitions,
+ availableToolNames: adapterRequest.availableToolNames
+ ))
])
],
metadata: [
@@ -352,12 +355,12 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
"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.",
- "Use planSteps for the generic harness plan. Each executable step must name one allowed toolName, with inputEntity/controlID/focusKey filled when that tool needs them. Non-executable reasoning steps should use an empty toolName.",
+ "Use planSteps for the generic harness plan. Each executable step must name one available toolName, with toolInputs filled from structured entities and tool schemas. Keep inputEntity/controlID/focusKey for local UI compatibility when those tools need them. Non-executable reasoning steps should use an empty toolName.",
"Use verificationCriteria for what proves success, fallbacks for safe recovery choices, and clarificationPolicy for when Donkey should stop and ask.",
"Apply App skill guidance for app-specific workflows, control strategies, required metadata, and output shapes. Do not invent app-specific behavior that is absent from task definitions, catalog data, memory, or loaded skill guidance.",
"When App finder catalog JSON is non-empty and you use local_app_interaction, choose the target app only from a catalog entry with supportStatus supported and a matching capability. Set metadata.appFinder.selectedAppID to the exact appID, metadata.appFinder.selectedCapabilityID to the capability id, and metadata.appFinder.controlProfile to one declared control profile. Never select candidate, unsupported, or denied entries for execution.",
"For local_app_interaction, select the most likely local app, set targetAppName and entities.appName to the human app name, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.",
- "For local_app_interaction, fill planSteps with allowed toolName values only: app.openOrFocus, app.observe, ui.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.clickTarget, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",
+ "For local_app_interaction, use available local UI tools for UI workflows and available skill tools for skill-backed workflows. When a loaded app skill provides a validated script for the selected capability, prefer skill.load then skill.script.execute with structured toolInputs over repeated screenshot-driven keyboard fallback.",
"Use ui.clickTarget when the intended action is to click or submit a visible control by Accessibility or AI visual evidence instead of pressing Return. Put the semantic or observed visual target id in controlID.",
"Verification may be a set of verifier steps. Use app.verifyCommand for guarded command evidence, app.verifyVisibleText for observed result text, and include both when both kinds of evidence are needed.",
"When ui.setText is present, entities.query and normalizedEntities.query must be non-empty, the step inputEntity should usually be query, and controlID/focusKey should describe the guarded UI strategy.",
diff --git a/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift b/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift
index 3e42d74a..0528429f 100644
--- a/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift
+++ b/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift
@@ -118,7 +118,10 @@ enum TaskIntentWireCodec {
]
}
- static func genericHarnessPlanningJsonSchema(taskDefinitions: [LocalAppTaskDefinition]) -> [String: Any] {
+ static func genericHarnessPlanningJsonSchema(
+ taskDefinitions: [LocalAppTaskDefinition],
+ availableToolNames: [String] = []
+ ) -> [String: Any] {
let allowsDynamicTargets = taskDefinitions.contains { definition in
definition.metadata["dynamicTarget"] == "true"
}
@@ -127,7 +130,16 @@ enum TaskIntentWireCodec {
let targetAppNameSchema: [String: Any] = allowsDynamicTargets
? ["type": "string"]
: ["type": "string", "enum": appNames]
- let toolNames = [""] + LocalAppActionPlanTool.allCases.map(\.rawValue)
+ let availableToolNameSet = Set(
+ availableToolNames
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ )
+ let toolNames = [""] + Array(
+ availableToolNameSet.isEmpty
+ ? Set(LocalAppActionPlanTool.allCases.map(\.rawValue))
+ : availableToolNameSet
+ ).sorted()
let planStepSchema: [String: Any] = [
"type": "object",
"additionalProperties": false,
@@ -138,6 +150,7 @@ enum TaskIntentWireCodec {
"inputEntity",
"controlID",
"focusKey",
+ "toolInputs",
"expectedObservation"
],
"properties": [
@@ -147,6 +160,10 @@ enum TaskIntentWireCodec {
"inputEntity": ["type": "string"],
"controlID": ["type": "string"],
"focusKey": ["type": "string"],
+ "toolInputs": [
+ "type": "object",
+ "additionalProperties": ["type": "string"]
+ ],
"expectedObservation": ["type": "string"]
]
]
@@ -400,7 +417,11 @@ enum TaskIntentWireCodec {
let confidence = wire.confidence
let needsConfirmation = wire.needsConfirmation || missingRequiredEntity != nil
- let actionPlan = wire.actionPlan.tools.isEmpty ? nil : wire.actionPlan
+ let hasGenericExecutablePlan = metadata["genericHarness.planStepsJSON"]
+ .map(Self.hasGenericExecutableTool) ?? false
+ let actionPlan = wire.actionPlan.tools.isEmpty && !hasGenericExecutablePlan
+ ? nil
+ : wire.actionPlan
let primaryEntity = definition.verificationEntityName
.flatMap { normalizedEntities[$0] }
?? normalizedEntities.values.sorted().first
@@ -622,6 +643,7 @@ enum TaskIntentWireCodec {
"inputEntity": step.inputEntity,
"controlID": step.controlID,
"focusKey": step.focusKey,
+ "toolInputs": step.toolInputs,
"expectedObservation": step.expectedObservation
]
}
@@ -647,6 +669,19 @@ enum TaskIntentWireCodec {
return text
}
+ private static func hasGenericExecutableTool(_ planStepsJSON: String) -> Bool {
+ guard let data = planStepsJSON.data(using: .utf8),
+ let steps = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]]
+ else {
+ return false
+ }
+ return steps.contains { step in
+ guard let toolName = step["toolName"] as? String else { return false }
+ return toolName == "skill.script.execute"
+ || toolName == "automation.applescript.execute"
+ }
+ }
+
private static func firstNonEmpty(_ values: [String]) -> String? {
values.first { value in
!value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
@@ -854,7 +889,31 @@ private struct GenericHarnessPlanStepWire: Decodable {
var inputEntity: String
var controlID: String
var focusKey: String
+ var toolInputs: [String: String]
var expectedObservation: String
+
+ private enum CodingKeys: String, CodingKey {
+ case id
+ case summary
+ case toolName
+ case inputEntity
+ case controlID
+ case focusKey
+ case toolInputs
+ case expectedObservation
+ }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ self.id = try container.decode(String.self, forKey: .id)
+ self.summary = try container.decode(String.self, forKey: .summary)
+ self.toolName = try container.decode(String.self, forKey: .toolName)
+ self.inputEntity = try container.decode(String.self, forKey: .inputEntity)
+ self.controlID = try container.decode(String.self, forKey: .controlID)
+ self.focusKey = try container.decode(String.self, forKey: .focusKey)
+ self.toolInputs = try container.decodeIfPresent([String: String].self, forKey: .toolInputs) ?? [:]
+ self.expectedObservation = try container.decode(String.self, forKey: .expectedObservation)
+ }
}
private struct GenericHarnessClarificationPolicyWire: Decodable {
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
index 33d0a0de..81f7cc8f 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
@@ -495,6 +495,29 @@ public enum BuiltInHarnessToolExecutors {
}
let outcome = await executor(artifact, context)
+ if outcome.metadata["clarification.required"] == "true" {
+ let question = trimmed(outcome.metadata["clarification.question"])
+ ?? "What should I try next?"
+ return HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .waitingForUser,
+ 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
+ ]
+ ),
+ question: question,
+ metadata: outcome.metadata.merging([
+ "scriptArtifactID": scriptID,
+ "executor": "guardedScriptBackend"
+ ]) { current, _ in current }
+ )
+ }
let status: HarnessToolResultStatus = outcome.succeeded ? .succeeded : .failed
return HarnessToolResult(
callID: context.call.id,
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift
index 9421eefc..e74bba89 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift
@@ -405,12 +405,13 @@ public struct HarnessSkillFileSystemSource: Sendable {
language: language,
purpose: titleCased(basename),
relativePath: relativePath,
- validationStatus: .pendingValidation,
+ validationStatus: sourceKind == .builtIn ? .validated : .pendingValidation,
requiredPermissions: requiredPermissions(for: language),
safetyClass: language == .appleScript ? .guardedInput : .sensitive,
metadata: [
"source": "filesystem",
- "scriptDirectory": scriptsDirectory.path
+ "scriptDirectory": scriptsDirectory.path,
+ "validation.provenance": sourceKind == .builtIn ? "bundleResource" : ""
]
)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift
index 4b825842..e69770c8 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift
@@ -136,7 +136,8 @@ public struct AppHarnessGenericLifecycle: Sendable {
taskID: String,
resolution: LocalAppTaskCatalogResolution,
fallbackGoal: String,
- traceID: String
+ traceID: String,
+ availableToolNames: [String] = AppHarnessGenericLifecycleToolNames.localAppTools
) async -> HarnessTaskState? {
let intent = Self.intentAnalysis(
for: resolution,
@@ -146,7 +147,10 @@ public struct AppHarnessGenericLifecycle: Sendable {
let plannedStepMetadata = resolution.intent?.metadata ?? [:]
let modelPlanSteps = Self.modelPlanningSteps(
from: plannedStepMetadata,
- traceID: traceID
+ traceID: traceID,
+ availableToolNames: availableToolNames,
+ normalizedEntities: resolution.intent?.normalizedEntities ?? [:],
+ entities: resolution.intent?.entities ?? [:]
)
let plan = HarnessPlan(
goal: intent.goal,
@@ -427,31 +431,40 @@ public struct AppHarnessGenericLifecycle: Sendable {
private static func modelPlanningSteps(
from metadata: [String: String],
- traceID: String
+ traceID: String,
+ availableToolNames: [String],
+ normalizedEntities: [String: String],
+ entities: [String: String]
) -> [HarnessPlanStep] {
guard let text = metadata["genericHarness.planStepsJSON"],
let data = text.data(using: .utf8),
- let values = try? JSONSerialization.jsonObject(with: data) as? [[String: String]]
+ let values = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]]
else {
return []
}
+ let allowedToolNames = Set(availableToolNames)
return values.enumerated().map { index, value in
- let id = nonEmpty(value["id"]) ?? "model-plan-step-\(index + 1)"
- let toolName = nonEmpty(value["toolName"])
+ let id = nonEmpty(stringValue(value["id"])) ?? "model-plan-step-\(index + 1)"
+ let toolName = nonEmpty(stringValue(value["toolName"]))
let toolCall = toolName.flatMap { toolName -> HarnessToolCall? in
- guard LocalAppActionPlanTool(rawValue: toolName) != nil else { return nil }
+ guard allowedToolNames.contains(toolName) else { return nil }
+ let input = toolInput(
+ from: value,
+ normalizedEntities: normalizedEntities,
+ entities: entities
+ )
return HarnessToolCall(
id: "local-app-step-\(traceID)-\(index + 1)",
name: toolName,
- input: [
- "inputEntity": value["inputEntity"] ?? "",
- "controlID": value["controlID"] ?? "",
- "focusKey": value["focusKey"] ?? "",
- "expectedObservation": value["expectedObservation"] ?? "",
+ input: input.merging([
+ "inputEntity": stringValue(value["inputEntity"]) ?? "",
+ "controlID": stringValue(value["controlID"]) ?? "",
+ "focusKey": stringValue(value["focusKey"]) ?? "",
+ "expectedObservation": stringValue(value["expectedObservation"]) ?? "",
"modelStepID": id,
"modelStepIndex": String(index)
- ],
+ ]) { current, _ in current },
metadata: [
"adapter": "userQuery",
"traceID": traceID,
@@ -461,20 +474,38 @@ public struct AppHarnessGenericLifecycle: Sendable {
}
return HarnessPlanStep(
id: "model-\(id)",
- summary: nonEmpty(value["summary"]) ?? "Model-planned harness step",
+ summary: nonEmpty(stringValue(value["summary"])) ?? "Model-planned harness step",
toolCall: toolCall,
- expectedObservation: nonEmpty(value["expectedObservation"]),
+ expectedObservation: nonEmpty(stringValue(value["expectedObservation"])),
metadata: [
"source": "hostedGenericHarnessPlanning",
"toolName": toolName ?? "",
- "inputEntity": value["inputEntity"] ?? "",
- "controlID": value["controlID"] ?? "",
- "focusKey": value["focusKey"] ?? ""
+ "inputEntity": stringValue(value["inputEntity"]) ?? "",
+ "controlID": stringValue(value["controlID"]) ?? "",
+ "focusKey": stringValue(value["focusKey"]) ?? ""
]
)
}
}
+ private static func toolInput(
+ from value: [String: Any],
+ normalizedEntities: [String: String],
+ entities: [String: String]
+ ) -> [String: String] {
+ var input = value["toolInputs"] as? [String: String] ?? [:]
+ let inputEntity = nonEmpty(input["inputEntity"] ?? stringValue(value["inputEntity"]))
+ if let inputEntity {
+ input["inputEntity"] = inputEntity
+ }
+ if input["input"]?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty != false,
+ let inputEntity,
+ let entityValue = normalizedEntities[inputEntity] ?? entities[inputEntity] {
+ input["input"] = entityValue
+ }
+ return input
+ }
+
private static func clarificationPolicy(from metadata: [String: String]) -> [String] {
var policy = stringArrayMetadata(
metadata["genericHarness.clarification.questionsJSON"],
@@ -506,6 +537,10 @@ public struct AppHarnessGenericLifecycle: Sendable {
let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return trimmed.isEmpty ? nil : trimmed
}
+
+ private static func stringValue(_ value: Any?) -> String? {
+ value as? String
+ }
}
private extension HarnessThreadEventRole {
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
index 2a71c31b..17ac6464 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
@@ -977,11 +977,22 @@ public struct LocalAppTaskCatalog: Sendable {
)
}
+ let hasGenericExecutablePlan = Self.hasGenericExecutablePlan(intent.metadata)
+ let availability = availabilityProvider.availability(namedApp: cleanedRequestedAppName)
guard let plan = intent.actionPlan else {
+ let definition = hasGenericExecutablePlan
+ ? Self.genericLocalAppInteractionDefinition(
+ target: availability.target,
+ plan: LocalAppActionPlan(tools: [], inputEntity: "query", focusKey: "")
+ )
+ : Self.genericLocalAppInteractionDefinition
return LocalAppTaskCatalogResolution(
- status: .needsConfirmation,
+ status: hasGenericExecutablePlan && availability.isInstalled
+ ? .resolved
+ : (hasGenericExecutablePlan ? .appUnavailable : .needsConfirmation),
intent: intent,
- definition: Self.genericLocalAppInteractionDefinition,
+ definition: definition,
+ availability: hasGenericExecutablePlan ? availability : nil,
metadata: [
"reason": "missingActionPlan",
"taskType": Self.genericLocalAppInteractionTaskType,
@@ -989,7 +1000,7 @@ public struct LocalAppTaskCatalog: Sendable {
]
)
}
- guard plan.isExecutable else {
+ guard plan.isExecutable || hasGenericExecutablePlan else {
return LocalAppTaskCatalogResolution(
status: .needsConfirmation,
intent: intent,
@@ -1018,7 +1029,6 @@ public struct LocalAppTaskCatalog: Sendable {
)
}
- let availability = availabilityProvider.availability(namedApp: cleanedRequestedAppName)
let target = availability.target
let definition = Self.genericLocalAppInteractionDefinition(
target: target,
@@ -1064,6 +1074,20 @@ public struct LocalAppTaskCatalog: Sendable {
)
}
+ private static func hasGenericExecutablePlan(_ metadata: [String: String]) -> Bool {
+ guard let text = metadata["genericHarness.planStepsJSON"],
+ let data = text.data(using: .utf8),
+ let steps = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]]
+ else {
+ return false
+ }
+ return steps.contains { step in
+ guard let toolName = step["toolName"] as? String else { return false }
+ return toolName == "skill.script.execute"
+ || toolName == "automation.applescript.execute"
+ }
+ }
+
public static var genericLocalItemOpenDefinition: LocalAppTaskDefinition {
genericAppOpenDefinition(target: genericLocalItemTarget)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift
new file mode 100644
index 00000000..7f5887e1
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift
@@ -0,0 +1,151 @@
+import DonkeyContracts
+import DonkeyHarness
+import Foundation
+
+public enum LocalAppUserQueryHarnessServices {
+ public static func builtInSkillBackedServices() -> HarnessBuiltInToolServices {
+ HarnessBuiltInToolServices(
+ skillRegistry: HarnessSkillRegistry(skills: BuiltInLocalAppSkillPacks.descriptors()),
+ generatedScripts: HarnessGeneratedScriptStore(artifacts: builtInValidatedScriptArtifacts()),
+ appleScriptExecutor: { artifact, context in
+ await executeSkillScript(artifact: artifact, context: context)
+ },
+ skillScriptExecutor: { artifact, context in
+ await executeSkillScript(artifact: artifact, context: context)
+ }
+ )
+ }
+
+ public static func builtInValidatedScriptArtifacts() -> [HarnessGeneratedScriptArtifact] {
+ BuiltInLocalAppSkillPacks.descriptors().flatMap { skill in
+ skill.scripts.compactMap { script -> HarnessGeneratedScriptArtifact? in
+ guard let source = BuiltInLocalAppSkillPacks.scriptSource(
+ skillID: skill.id,
+ relativePath: script.relativePath
+ ) else {
+ return nil
+ }
+ return HarnessGeneratedScriptArtifact(
+ id: script.id,
+ language: generatedLanguage(for: script.language),
+ source: source,
+ validationStatus: .validated,
+ createdByToolName: "built-in-skill-pack",
+ ownerSkillID: skill.id,
+ metadata: script.metadata.merging([
+ "skillID": skill.id,
+ "relativePath": script.relativePath,
+ "validation.policy": "builtInSkillScript",
+ "validation.provenance": "bundleResource"
+ ]) { current, _ in current }
+ )
+ }
+ }
+ }
+
+ public static func executeSkillScript(
+ artifact: HarnessGeneratedScriptArtifact,
+ context: HarnessToolExecutionContext
+ ) async -> HarnessScriptExecutionOutcome {
+ switch artifact.language {
+ case .appleScript:
+ return await executeAppleScriptSkill(artifact: artifact, context: context)
+ case .shell, .javaScript, .python, .swift, .unknown:
+ return HarnessScriptExecutionOutcome(
+ succeeded: false,
+ summary: "Skill script language is not supported by the guarded local-app backend.",
+ metadata: [
+ "reason": "unsupportedSkillScriptLanguage",
+ "language": artifact.language.rawValue
+ ]
+ )
+ }
+ }
+
+ private static func executeAppleScriptSkill(
+ artifact: HarnessGeneratedScriptArtifact,
+ context: HarnessToolExecutionContext
+ ) async -> HarnessScriptExecutionOutcome {
+ let input = context.call.input["input"]
+ ?? context.call.input["query"]
+ ?? context.call.input["entityValue"]
+ ?? ""
+ let command = ActionEngineCommand(
+ id: "\(context.taskID)-\(artifact.id)",
+ traceID: context.call.metadata["traceID"] ?? context.taskID,
+ targetID: context.call.input["targetID"] ?? artifact.ownerSkillID ?? artifact.id,
+ kind: .controller,
+ issuedAt: now(),
+ key: input,
+ metadata: [
+ "automationBackend": "appleScript",
+ "appleScript.action": artifact.metadata["action"] ?? artifact.id,
+ "appleScript.template": artifact.source,
+ "appleScript.query": input,
+ "appleScript.entityValue": input,
+ "targetApp": context.call.input["targetApp"] ?? "",
+ "bundleIdentifier": context.call.input["bundleIdentifier"] ?? ""
+ ]
+ )
+ let result = await MacAppleScriptActionEngineInputBackend().execute(command)
+ let output = result.metadata["appleScript.output"] ?? ""
+ let outputMetadata = structuredOutputMetadata(output)
+ let clarificationRequired = outputMetadata["clarification.required"] == "true"
+ let succeeded = result.executed && !clarificationRequired
+ return HarnessScriptExecutionOutcome(
+ succeeded: succeeded,
+ summary: succeeded
+ ? "Skill script executed successfully."
+ : "Skill script did not complete successfully.",
+ output: output,
+ metadata: result.metadata.merging(outputMetadata) { current, _ in current }.merging([
+ "skillID": artifact.ownerSkillID ?? "",
+ "scriptID": artifact.id,
+ "script.relativePath": artifact.metadata["relativePath"] ?? ""
+ ]) { current, _ in current }
+ )
+ }
+
+ private static func structuredOutputMetadata(_ output: String) -> [String: String] {
+ var metadata: [String: String] = [:]
+ let fields = output
+ .split { character in
+ character == "\n" || character == "\r" || character == ";"
+ }
+ for field in fields {
+ let parts = field.split(separator: "=", maxSplits: 1).map(String.init)
+ guard parts.count == 2 else { continue }
+ let key = parts[0].trimmingCharacters(in: .whitespacesAndNewlines)
+ let value = parts[1].trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !key.isEmpty else { continue }
+ metadata[key] = value
+ }
+ return metadata
+ }
+
+ private static func generatedLanguage(
+ for language: HarnessSkillScriptLanguage
+ ) -> HarnessGeneratedScriptLanguage {
+ switch language {
+ case .appleScript:
+ return .appleScript
+ case .shell:
+ return .shell
+ case .javaScript:
+ return .javaScript
+ case .python:
+ return .python
+ case .swift:
+ return .swift
+ case .unknown:
+ return .unknown
+ }
+ }
+
+ private static func now() -> RunTraceTimestamp {
+ RunTraceTimestamp(
+ wallClock: Date(),
+ monotonicUptimeNanoseconds: UInt64(ProcessInfo.processInfo.systemUptime * 1_000_000_000)
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/SKILL.md
index 3122dea5..b83e091e 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/SKILL.md
+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/SKILL.md
@@ -3,6 +3,7 @@ id: music-media
description: Plan low-risk media playback in Apple Music or another supported media app.
tags: media, music, playback, local-app
tools: app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyVisibleText
+scripts: scripts-play-media-by-search
Use this skill for play or listen requests when a supported media app or a `play_media` catalog capability is available.
@@ -14,14 +15,14 @@ For vague artist, mood, or genre playback requests, choose one concrete represen
Set `metadata.mediaSelection.kind` to `explicit_song`, `explicit_album`, `explicit_playlist`, or `representative_song`, and always set `metadata.mediaSelection.source` to `streaming` or `local_library`. For representative choices, also set `metadata.mediaSelection.seed`, `metadata.mediaSelection.selectedTitle`, and a short `metadata.mediaSelection.reason`. The `query` must include the selected song title and artist, not only the artist, album, genre, or mood seed.
-Also return a bounded AppleScript artifact for Apple Music playback when the selected catalog entry has bundle identifier `com.apple.Music`. Put it in metadata, not in free text:
+Prefer the validated skill script path when the selected catalog entry supports it:
-- `metadata.automationBackend=appleScript`
-- `metadata.appleScript.action=music.playMediaBySearch`
-- `metadata.appleScript.entityName=query`
-- `metadata.appleScript.query` equal to the same structured `query`
-- `metadata.appleScript.source` containing AppleScript that uses only the structured `query`, targets `application id "com.apple.Music"`, opens/focuses Music, searches for the query, activates a playable result, and returns compact status text
+- Load this skill with `skill.load` using `toolInputs.skillID=music-media`.
+- Execute `skill.script.execute` with `toolInputs.skillID=music-media`, `toolInputs.scriptID=scripts-play-media-by-search`, and `inputEntity=query`.
+- Verify the structured script evidence with `state.verify`; do not use screenshot verification unless the script cannot provide evidence.
+- The script input must be the same structured `query`; never pass raw user text separately.
+- Treat script output as structured evidence. `status=played` means the script submitted playback. `clarification.required=true` means stop and ask the included `clarification.question`.
-The AppleScript must be bounded and deterministic. It must not use raw user text, shell commands, files, deletion, quitting apps, network commands, or unrelated applications. Keep the UI plan below as the fallback path even when AppleScript metadata is present.
+The AppleScript script is bounded and deterministic. It must not use raw user text, shell commands, files, deletion, quitting apps, network commands, or unrelated applications. Keep the UI plan below as the fallback path when the skill script cannot execute or does not produce enough evidence.
-When planning generic `local_app_interaction`, use `targetAppName` and `entities.appName` from the supported catalog entry. Use `goal=play media`, `inputEntity=query`, `controlID=search`, `focusKey=Command+F`, and tools `app.openOrFocus`, `app.observe`, `ui.focusSearch`, `ui.setText`, `ui.pressReturn`, a second `ui.pressReturn`, and `app.verifyVisibleText`. The first Return submits the search; the second Return activates the top playable result. If visible results are present, prefer a playable song row matching the requested seed over artist, playlist, category, or unrelated rows.
+When planning generic `local_app_interaction`, use `targetAppName` and `entities.appName` from the supported catalog entry. For the preferred script flow, use `skill.load`, `skill.script.execute`, and `state.verify`. For UI fallback, use `goal=play media`, `inputEntity=query`, `controlID=search`, `focusKey=Command+F`, and tools `app.openOrFocus`, `app.observe`, `ui.focusSearch`, `ui.setText`, `ui.pressReturn`, a second `ui.pressReturn`, and `app.verifyVisibleText`. The first Return submits the search; the second Return activates the top playable result. If visible results are present, prefer a playable song row matching the requested seed over artist, playlist, category, or unrelated rows.
diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/scripts/play-media-by-search.applescript b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/scripts/play-media-by-search.applescript
new file mode 100644
index 00000000..73a66fd8
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/scripts/play-media-by-search.applescript
@@ -0,0 +1,32 @@
+set mediaQuery to {query}
+set trimmedQuery to mediaQuery as text
+
+if trimmedQuery is "" then
+ return "status=not_found" & linefeed & "clarification.required=true" & linefeed & "clarification.question=What would you like me to play?"
+end if
+
+tell application id "com.apple.Music"
+ activate
+end tell
+
+delay 0.4
+
+tell application "System Events"
+ if not (exists process "Music") then
+ return "status=failed" & linefeed & "failureReason=music_process_unavailable"
+ end if
+
+ tell process "Music"
+ set frontmost to true
+ end tell
+
+ keystroke "f" using command down
+ delay 0.2
+ keystroke trimmedQuery
+ delay 0.2
+ key code 36
+ delay 1.0
+ key code 36
+end tell
+
+return "status=played" & linefeed & "query=" & trimmedQuery & linefeed & "playedTitle=" & trimmedQuery
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index 6a123a9c..9008e5f1 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -405,6 +405,66 @@ struct AIHarnessAdapterTests {
#expect(prompt.contains("Skill ID: browser-navigation"))
}
+ @Test
+ func hostedTaskIntentAdapterPreservesSkillToolPlanInputs() async throws {
+ let httpClient = FakeAIHTTPClient(
+ data: responseData(
+ outputText: hostedPlanningOutput(
+ goal: "play a selected song in Music",
+ taskType: "local_app_interaction",
+ targetAppName: "Music",
+ entitiesJSON: #"{"appName":"Music","goal":"play media","query":"Yellow Coldplay"}"#,
+ normalizedEntitiesJSON: #"{"appName":"Music","goal":"play media","query":"Yellow Coldplay"}"#,
+ confidence: 0.91,
+ planStepsJSON: #"[{"id":"load-music-skill","summary":"Load the media skill.","toolName":"skill.load","inputEntity":"","controlID":"","focusKey":"","toolInputs":{"skillID":"music-media"},"expectedObservation":"Music skill is loaded."},{"id":"play-media","summary":"Run the validated media script.","toolName":"skill.script.execute","inputEntity":"query","controlID":"","focusKey":"","toolInputs":{"skillID":"music-media","scriptID":"scripts-play-media-by-search"},"expectedObservation":"status=played"},{"id":"verify-played","summary":"Verify script evidence.","toolName":"state.verify","inputEntity":"","controlID":"","focusKey":"","toolInputs":{"criteria":"status=played"},"expectedObservation":"Script reported playback."}]"#,
+ verificationCriteriaJSON: #"["status=played"]"#,
+ fallbacksJSON: #"["Ask if the script reports clarification.required=true."]"#,
+ metadataJSON: #"{"appFinder.selectedAppID":"com.apple.Music","appFinder.selectedCapabilityID":"play_media","appFinder.controlProfile":"search_then_enter"}"#
+ )
+ ),
+ statusCode: 200
+ )
+ let adapter = HostedTaskIntentParsingAdapter(
+ configuration: DonkeyBackendInferenceConfiguration(
+ baseURL: URL(string: "https://donkey.example")!,
+ clientID: "client-1"
+ ),
+ httpClient: httpClient
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "play some coldplay",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ availableToolNames: [
+ "skill.load",
+ "skill.script.execute",
+ "state.verify"
+ ],
+ sourceTraceID: "trace-skill-intent"
+ )
+ )
+
+ #expect(result.intent?.taskType == "local_app_interaction")
+ #expect(result.intent?.actionPlan != nil)
+ #expect(result.intent?.metadata["genericHarness.planStepsJSON"]?.contains("\"toolName\":\"skill.script.execute\"") == true)
+ #expect(result.intent?.metadata["genericHarness.planStepsJSON"]?.contains("\"scriptID\":\"scripts-play-media-by-search\"") == true)
+
+ let request = try #require(httpClient.requests.first)
+ let body = try #require(request.httpBodyJSONObject)
+ let text = try #require(body["text"] as? [String: Any])
+ let format = try #require(text["format"] as? [String: Any])
+ let schema = try #require(format["schema"] as? [String: Any])
+ let properties = try #require(schema["properties"] as? [String: Any])
+ let planSteps = try #require(properties["planSteps"] as? [String: Any])
+ let items = try #require(planSteps["items"] as? [String: Any])
+ let stepProperties = try #require(items["properties"] as? [String: Any])
+ #expect(stepProperties["toolInputs"] != nil)
+ let toolName = try #require(stepProperties["toolName"] as? [String: Any])
+ let toolEnums = try #require(toolName["enum"] as? [String])
+ #expect(toolEnums.contains("skill.script.execute"))
+ }
+
@Test
func hostedTaskIntentAdapterPreservesNoTaskConversationResponse() async throws {
let httpClient = FakeAIHTTPClient(
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
index 4ebffefe..cb4bc294 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
@@ -180,6 +180,100 @@ struct GenericHarnessTests {
#expect(context.snippets.joined(separator: "\n").contains("metadata.mediaSelection.kind"))
}
+ @Test
+ func userQueryHarnessServicesExposeBuiltInMusicSkillScript() async throws {
+ let services = LocalAppUserQueryHarnessServices.builtInSkillBackedServices()
+ let musicSkill = await services.skillRegistry?.descriptor(id: "music-media")
+ let script = await services.generatedScripts.artifact(id: "scripts-play-media-by-search")
+
+ #expect(musicSkill?.scripts.contains { $0.id == "scripts-play-media-by-search" } == true)
+ #expect(script?.ownerSkillID == "music-media")
+ #expect(script?.validationStatus == .validated)
+ #expect(script?.language == .appleScript)
+ }
+
+ @Test
+ func skillScriptExecuteUsesStructuredOutcomeForSuccessAndClarification() async throws {
+ let generatedScripts = HarnessGeneratedScriptStore(artifacts: [
+ HarnessGeneratedScriptArtifact(
+ id: "scripts-play-media-by-search",
+ language: .appleScript,
+ source: "return \"status=played\"",
+ validationStatus: .validated,
+ createdByToolName: "test",
+ ownerSkillID: "music-media"
+ )
+ ])
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(
+ generatedScripts: generatedScripts,
+ skillScriptExecutor: { _, _ in
+ HarnessScriptExecutionOutcome(
+ succeeded: true,
+ summary: "played",
+ output: "status=played",
+ metadata: ["status": "played"]
+ )
+ }
+ )
+ )
+
+ let result = await registry.execute(
+ HarnessToolCall(
+ id: "execute-script",
+ name: "skill.script.execute",
+ input: [
+ "skillID": "music-media",
+ "scriptID": "scripts-play-media-by-search",
+ "input": "Yellow Coldplay"
+ ]
+ ),
+ taskID: "task-script-success",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: [.appControl, .input]
+ )
+
+ #expect(result.status == .succeeded)
+ #expect(result.metadata["status"] == "played")
+
+ let clarificationRegistry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(
+ generatedScripts: generatedScripts,
+ skillScriptExecutor: { _, _ in
+ HarnessScriptExecutionOutcome(
+ succeeded: false,
+ summary: "not found",
+ output: "status=not_found",
+ metadata: [
+ "status": "not_found",
+ "clarification.required": "true",
+ "clarification.question": "What should I try instead?"
+ ]
+ )
+ }
+ )
+ )
+
+ let clarification = await clarificationRegistry.execute(
+ HarnessToolCall(
+ id: "execute-script-not-found",
+ name: "skill.script.execute",
+ input: [
+ "skillID": "music-media",
+ "scriptID": "scripts-play-media-by-search",
+ "input": "Unknown song"
+ ]
+ ),
+ taskID: "task-script-clarification",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: [.appControl, .input]
+ )
+
+ #expect(clarification.status == .waitingForUser)
+ #expect(clarification.question == "What should I try instead?")
+ #expect(clarification.metadata["status"] == "not_found")
+ }
+
@Test
func unknownToolIsRejectedByRegistry() async {
let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()
@@ -984,6 +1078,67 @@ struct GenericHarnessTests {
#expect(result?.toolResult?.status == .waitingForUser)
}
+ @Test
+ func userQueryLifecyclePlansGenericSkillToolSteps() async throws {
+ let store = InMemoryHarnessThreadStore()
+ let coordinator = HarnessTaskCoordinator()
+ let lifecycle = AppHarnessGenericLifecycle(threadStore: store, coordinator: coordinator)
+ let task = await coordinator.createTask(
+ id: "skill-task",
+ threadID: "skill-thread",
+ goal: "play media"
+ )
+ let intent = TaskIntent(
+ intentID: "intent-skill-music",
+ taskType: "local_app_interaction",
+ targetApp: LocalAppTarget(appName: "Music"),
+ entities: [
+ "appName": "Music",
+ "goal": "play media",
+ "query": "Yellow Coldplay"
+ ],
+ normalizedEntities: [
+ "appName": "Music",
+ "goal": "play media",
+ "query": "Yellow Coldplay"
+ ],
+ confidence: 0.9,
+ parserSource: .onlineModel,
+ actionPlan: LocalAppActionPlan(tools: [], inputEntity: "query", focusKey: ""),
+ metadata: [
+ "genericHarness.schemaVersion": "generic_harness_planning",
+ "genericHarness.planStepsJSON": """
+ [{"id":"load-music-skill","summary":"Load the media skill.","toolName":"skill.load","inputEntity":"","controlID":"","focusKey":"","toolInputs":{"skillID":"music-media"},"expectedObservation":"Skill loaded."},{"id":"play-media","summary":"Run the validated script.","toolName":"skill.script.execute","inputEntity":"query","controlID":"","focusKey":"","toolInputs":{"skillID":"music-media","scriptID":"scripts-play-media-by-search"},"expectedObservation":"status=played"}]
+ """,
+ "genericHarness.verificationCriteriaJSON": #"["status=played"]"#,
+ "genericHarness.fallbacksJSON": #"["Ask for a different query."]"#
+ ]
+ )
+ let resolution = LocalAppTaskCatalogResolution(
+ status: .resolved,
+ intent: intent,
+ definition: LocalAppTaskCatalog.genericLocalAppInteractionDefinition(
+ target: LocalAppTarget(appName: "Music", bundleIdentifier: "com.apple.Music"),
+ plan: LocalAppActionPlan(tools: [], inputEntity: "query", focusKey: "")
+ )
+ )
+
+ let planned = await lifecycle.planLocalTaskRun(
+ taskID: task.id,
+ resolution: resolution,
+ fallbackGoal: "play music",
+ traceID: "trace-skill-plan",
+ availableToolNames: ["skill.load", "skill.script.execute"]
+ )
+
+ let steps = try #require(planned?.plan?.steps)
+ let calls = steps.compactMap(\.toolCall)
+ #expect(calls.map(\.name) == ["skill.load", "skill.script.execute"])
+ #expect(calls[0].input["skillID"] == "music-media")
+ #expect(calls[1].input["scriptID"] == "scripts-play-media-by-search")
+ #expect(calls[1].input["input"] == "Yellow Coldplay")
+ }
+
@Test
func userQueryLifecycleUsesHostedGenericPlanningMetadata() async {
let store = InMemoryHarnessThreadStore()
diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.md
index d749caf9..da716051 100644
--- a/docs/guides/agent-harness.md
+++ b/docs/guides/agent-harness.md
@@ -241,6 +241,13 @@ control.
Plugins register tools through the same interface. App knowledge belongs in
plugins, skills, catalogs, or memory, not in core harness conditionals.
+Skill-backed local-app actions are first-class generic plan steps. A model plan
+may load a relevant skill, execute a validated skill script with structured
+entity input, and verify the script's structured evidence before falling back to
+Accessibility or screenshot-driven UI actions. Built-in and learned scripts must
+be registered as validated artifacts with provenance before execution; raw user
+text is not passed as script source or used to select app-specific behavior.
+
## Computer Use
Computer use is one tool family inside the harness.