Skip to content

Open source CapCut alternative.

TypeScript

Add dynamic AppleScript generation harness

David Leff9c1e430e6b
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 742b3981..a5aad971 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -386,8 +386,13 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
traceID: traceID,
availableToolNames: Self.genericHarnessToolNames()
)
+ var harnessServices = LocalAppUserQueryHarnessServices.builtInSkillBackedServices()
+ let appleScriptGenerationAdapter = HostedAppleScriptGenerationAdapter()
+ harnessServices.appleScriptGenerator = { request in
+ await appleScriptGenerationAdapter.generateAppleScript(request)
+ }
let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
- services: LocalAppUserQueryHarnessServices.builtInSkillBackedServices()
+ services: harnessServices
)
let localStepExecutor = LocalAppHarnessStepExecutor(
command: commandRedaction.redactedText,
@@ -1222,11 +1227,17 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
}
private static func genericHarnessToolNames() -> [String] {
- Array(Set(
+ let allowedSensitiveTools: Set<String> = [
+ "automation.applescript.generate"
+ ]
+ return Array(Set(
BuiltInHarnessToolCatalog.descriptors
.filter { descriptor in
- descriptor.safetyClass != .destructive
- && descriptor.safetyClass != .sensitive
+ (
+ descriptor.safetyClass != .destructive
+ && descriptor.safetyClass != .sensitive
+ )
+ || allowedSensitiveTools.contains(descriptor.name)
}
.map(\.name)
+ LocalAppHarnessStepExecutor.descriptors.map(\.name)
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedAppleScriptGenerationAdapter.swift b/apps/Donkey/Sources/DonkeyAI/HostedAppleScriptGenerationAdapter.swift
new file mode 100644
index 00000000..1cd033a4
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/HostedAppleScriptGenerationAdapter.swift
@@ -0,0 +1,289 @@
+import DonkeyContracts
+import DonkeyHarness
+import Foundation
+
+public struct HostedAppleScriptGenerationAdapter: Sendable {
+ public static let schemaID = "dynamic_applescript_generation_v1"
+
+ public var router: AIModelRouter
+ public var configuration: DonkeyBackendInferenceConfiguration?
+ public var httpClient: any AIHTTPClient
+ public var environment: [String: String]
+
+ public init(
+ router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),
+ configuration: DonkeyBackendInferenceConfiguration? = nil,
+ httpClient: any AIHTTPClient = URLSessionAIHTTPClient(),
+ environment: [String: String] = ProcessInfo.processInfo.environment
+ ) {
+ self.router = router
+ self.configuration = configuration
+ self.httpClient = httpClient
+ self.environment = environment
+ }
+
+ public func generateAppleScript(
+ _ request: HarnessScriptGenerationRequest
+ ) async -> HarnessScriptGenerationOutcome {
+ guard request.language == .appleScript else {
+ return HarnessScriptGenerationOutcome(
+ succeeded: false,
+ summary: "Only AppleScript generation is supported by this adapter.",
+ metadata: ["reason": "unsupportedLanguage"]
+ )
+ }
+
+ let entry: AIModelRegistryEntry
+ do {
+ entry = try router.route(
+ AIModelRouteRequest(
+ jobType: .taskIntent,
+ risk: .medium,
+ privacyMode: .privacySensitive,
+ latencyTolerance: .interactive
+ )
+ .limitingProviders([.donkeyBackend])
+ )
+ } catch {
+ return HarnessScriptGenerationOutcome(
+ succeeded: false,
+ summary: "Dynamic AppleScript generation could not route a model.",
+ metadata: ["reason": "routingFailed", "error": String(describing: error)]
+ )
+ }
+
+ let backend: DonkeyBackendInferenceClient
+ do {
+ backend = DonkeyBackendInferenceClient(
+ configuration: try configuration ?? DonkeyBackendInferenceConfiguration.fromEnvironment(environment),
+ httpClient: httpClient
+ )
+ } catch {
+ return HarnessScriptGenerationOutcome(
+ succeeded: false,
+ summary: "Dynamic AppleScript generation is missing backend configuration.",
+ metadata: [
+ "reason": "missingCredentials",
+ "credential": DonkeyBackendInferenceConfiguration.baseURLConfigurationDescription,
+ "error": String(describing: error)
+ ]
+ )
+ }
+
+ do {
+ let response = try await backend.createResponse(
+ responseRequest(entry: entry, request: request)
+ )
+ guard let outputText = Self.outputText(from: response),
+ let data = outputText.data(using: .utf8)
+ else {
+ return HarnessScriptGenerationOutcome(
+ succeeded: false,
+ summary: "Dynamic AppleScript generation returned empty output.",
+ metadata: ["reason": "emptyModelOutput"]
+ )
+ }
+
+ let wire = try JSONDecoder().decode(AppleScriptGenerationWire.self, from: data)
+ guard wire.canGenerate else {
+ return HarnessScriptGenerationOutcome(
+ succeeded: false,
+ summary: wire.blockedReason.isEmpty
+ ? "Dynamic AppleScript generation decided the task is not doable as a small script."
+ : wire.blockedReason,
+ metadata: [
+ "reason": "appleScriptTaskNotDoable",
+ "blockedReason": wire.blockedReason
+ ]
+ )
+ }
+ let source = wire.scriptSource.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !source.isEmpty else {
+ return HarnessScriptGenerationOutcome(
+ succeeded: false,
+ summary: "Dynamic AppleScript generation returned an empty script.",
+ metadata: ["reason": "emptyScriptSource"]
+ )
+ }
+
+ return HarnessScriptGenerationOutcome(
+ succeeded: true,
+ source: source,
+ summary: wire.summary,
+ metadata: [
+ "generator": "hostedDynamicAppleScript",
+ "schemaID": Self.schemaID,
+ "provider": entry.provider.rawValue,
+ "modelEntryID": entry.id,
+ "safetyNotes": wire.safetyNotes.joined(separator: "\n"),
+ "expectedOutput": wire.expectedOutput
+ ]
+ )
+ } catch is CancellationError {
+ return HarnessScriptGenerationOutcome(
+ succeeded: false,
+ summary: "Dynamic AppleScript generation was cancelled.",
+ metadata: ["reason": "cancelled"]
+ )
+ } catch {
+ return HarnessScriptGenerationOutcome(
+ succeeded: false,
+ summary: "Dynamic AppleScript generation failed.",
+ metadata: ["reason": "requestFailed", "error": String(describing: error)]
+ )
+ }
+ }
+
+ private func responseRequest(
+ entry: AIModelRegistryEntry,
+ request: HarnessScriptGenerationRequest
+ ) -> RemoteInferenceResponseCreateRequest {
+ RemoteInferenceResponseCreateRequest(
+ input: .array([
+ .object([
+ "role": .string("user"),
+ "content": .array([
+ .object([
+ "type": .string("input_text"),
+ "text": .string(promptText(for: request))
+ ])
+ ])
+ ])
+ ]),
+ store: false,
+ text: [
+ "format": .object([
+ "type": .string("json_schema"),
+ "name": .string(Self.schemaID),
+ "strict": .bool(true),
+ "schema": Self.jsonValue(Self.schema())
+ ])
+ ],
+ metadata: [
+ "source_trace_id": request.sourceTraceID ?? "",
+ "prompt_version": "dynamic-applescript-generation-v1",
+ "privacy.store": "false",
+ "model_entry_id": entry.id
+ ],
+ parameters: [
+ "instructions": .string(Self.instructions),
+ "temperature": .number(0)
+ ]
+ )
+ }
+
+ private func promptText(for request: HarnessScriptGenerationRequest) -> String {
+ let payload: [String: Any] = [
+ "targetApp": request.targetApp,
+ "bundleIdentifier": request.bundleIdentifier ?? "",
+ "goal": request.goal,
+ "entities": request.entities,
+ "allowedActions": request.allowedActions,
+ "verification": request.verification,
+ "worldFacts": request.worldFacts,
+ "metadata": request.metadata
+ ]
+ let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys])
+ let json = data.flatMap { String(data: $0, encoding: .utf8) } ?? "{}"
+ return "Generate one bounded AppleScript for this structured local-app task JSON:\n\(json)"
+ }
+
+ private static let instructions = [
+ "You generate AppleScript for Donkey's guarded local-app harness.",
+ "Return strict JSON only.",
+ "Generate only a small AppleScript for one bounded operation or a very small sequence inside the requested target app.",
+ "Do not build a full automation pipeline; Donkey handles observation, clicking, recovery, and verification as separate harness steps.",
+ "Set canGenerate false when the task is not doable with a small target-app AppleScript using the provided entities and allowed actions.",
+ "Use only the provided entities and allowed actions.",
+ "Do not use shell commands, System Events, keystrokes, key codes, file deletion, quitting apps, network calls, credential access, or unrelated applications.",
+ "Prefer app dictionary commands and return a concise structured text result with key=value fields when possible.",
+ "Do not execute anything. The harness will validate, permission-gate, execute, observe, and verify separately."
+ ].joined(separator: " ")
+
+ private static func schema() -> [String: Any] {
+ [
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["canGenerate", "blockedReason", "scriptSource", "summary", "safetyNotes", "expectedOutput"],
+ "properties": [
+ "canGenerate": [
+ "type": "boolean",
+ "description": "False when the request is not doable as a small scoped AppleScript."
+ ],
+ "blockedReason": [
+ "type": "string",
+ "description": "Why generation is not possible, or empty when canGenerate is true."
+ ],
+ "scriptSource": [
+ "type": "string",
+ "description": "Small AppleScript source for one bounded target-app operation, or empty when canGenerate is false."
+ ],
+ "summary": [
+ "type": "string",
+ "description": "Short description of what the script does."
+ ],
+ "safetyNotes": [
+ "type": "array",
+ "items": ["type": "string"],
+ "description": "Brief notes about the safety boundaries followed."
+ ],
+ "expectedOutput": [
+ "type": "string",
+ "description": "Expected key=value style output or observation that should verify success."
+ ]
+ ]
+ ]
+ }
+
+ private static func jsonValue(_ value: Any) -> RemoteInferenceJSONValue {
+ switch value {
+ case let value as String:
+ return .string(value)
+ case let value as Bool:
+ return .bool(value)
+ case let value as Int:
+ return .number(Double(value))
+ case let value as Double:
+ return .number(value)
+ case let value as [String: Any]:
+ return .object(value.mapValues(jsonValue))
+ case let value as [Any]:
+ return .array(value.map(jsonValue))
+ default:
+ return .null
+ }
+ }
+
+ private static func outputText(from value: RemoteInferenceJSONValue) -> String? {
+ if let outputText = value.objectValue?["output_text"]?.stringValue,
+ !outputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ return outputText
+ }
+
+ guard let output = value.objectValue?["output"]?.arrayValue else {
+ return nil
+ }
+ for item in output {
+ guard let content = item.objectValue?["content"]?.arrayValue else { continue }
+ for contentItem in content {
+ guard contentItem.objectValue?["type"]?.stringValue == "output_text",
+ let text = contentItem.objectValue?["text"]?.stringValue,
+ !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ else {
+ continue
+ }
+ return text
+ }
+ }
+ return nil
+ }
+}
+
+private struct AppleScriptGenerationWire: Decodable {
+ var canGenerate: Bool
+ var blockedReason: String
+ var scriptSource: String
+ var summary: String
+ var safetyNotes: [String]
+ var expectedOutput: String
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift
index 84112957..2f88e4ca 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift
@@ -400,6 +400,7 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
"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, 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.",
+ "When automation.applescript.generate is available and a supported app action is better handled through AppleScript than UI input, use it only for a small doable target-app operation, not a full automation pipeline. Plan dynamic AppleScript as separate steps: automation.applescript.generate, automation.applescript.validate, automation.applescript.execute, then app.observe and an app.verifyCommand or app.verifyVisibleText step. Use the same stable toolInputs.scriptArtifactID on generate, validate, and execute. The generate step should include targetApp, bundleIdentifier when known, goal, entities as JSON text, allowedActions, and verification. Never put script source in planner output; the child generation tool creates the source artifact. If AppleScript is not clearly doable for that small operation, use observation, Accessibility, screenshot, or UI tools instead.",
"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/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
index 81f7cc8f..a075db8f 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
@@ -100,6 +100,62 @@ public struct HarnessScriptExecutionOutcome: Equatable, Sendable {
}
}
+public struct HarnessScriptGenerationRequest: Equatable, Sendable {
+ public var language: HarnessGeneratedScriptLanguage
+ public var targetApp: String
+ public var bundleIdentifier: String?
+ public var goal: String
+ public var entities: [String: String]
+ public var allowedActions: String
+ public var verification: String
+ public var worldFacts: [String: String]
+ public var sourceTraceID: String?
+ public var metadata: [String: String]
+
+ public init(
+ language: HarnessGeneratedScriptLanguage,
+ targetApp: String,
+ bundleIdentifier: String? = nil,
+ goal: String,
+ entities: [String: String] = [:],
+ allowedActions: String = "",
+ verification: String = "",
+ worldFacts: [String: String] = [:],
+ sourceTraceID: String? = nil,
+ metadata: [String: String] = [:]
+ ) {
+ self.language = language
+ self.targetApp = targetApp
+ self.bundleIdentifier = bundleIdentifier
+ self.goal = goal
+ self.entities = entities
+ self.allowedActions = allowedActions
+ self.verification = verification
+ self.worldFacts = worldFacts
+ self.sourceTraceID = sourceTraceID
+ self.metadata = metadata
+ }
+}
+
+public struct HarnessScriptGenerationOutcome: Equatable, Sendable {
+ public var succeeded: Bool
+ public var source: String
+ public var summary: String
+ public var metadata: [String: String]
+
+ public init(
+ succeeded: Bool,
+ source: String = "",
+ summary: String,
+ metadata: [String: String] = [:]
+ ) {
+ self.succeeded = succeeded
+ self.source = source
+ self.summary = summary
+ self.metadata = metadata
+ }
+}
+
public actor HarnessGeneratedScriptStore {
private var artifactsByID: [String: HarnessGeneratedScriptArtifact]
@@ -154,6 +210,7 @@ public struct HarnessBuiltInToolServices: Sendable {
public var generatedScripts: HarnessGeneratedScriptStore
public var applicationLearningStore: HarnessApplicationLearningStore
public var applicationSkillPackWriter: HarnessApplicationSkillPackWriter?
+ public var appleScriptGenerator: (@Sendable (HarnessScriptGenerationRequest) async -> HarnessScriptGenerationOutcome)?
public var appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?
public var skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?
@@ -164,6 +221,7 @@ public struct HarnessBuiltInToolServices: Sendable {
generatedScripts: HarnessGeneratedScriptStore = HarnessGeneratedScriptStore(),
applicationLearningStore: HarnessApplicationLearningStore = HarnessApplicationLearningStore(),
applicationSkillPackWriter: HarnessApplicationSkillPackWriter? = nil,
+ appleScriptGenerator: (@Sendable (HarnessScriptGenerationRequest) async -> HarnessScriptGenerationOutcome)? = nil,
appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,
skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil
) {
@@ -173,6 +231,7 @@ public struct HarnessBuiltInToolServices: Sendable {
self.generatedScripts = generatedScripts
self.applicationLearningStore = applicationLearningStore
self.applicationSkillPackWriter = applicationSkillPackWriter
+ self.appleScriptGenerator = appleScriptGenerator
self.appleScriptExecutor = appleScriptExecutor
self.skillScriptExecutor = skillScriptExecutor
}
@@ -229,6 +288,8 @@ public enum BuiltInHarnessToolExecutors {
return keyboardPress(context)
case "automation.applescript.generate":
return await appleScriptGenerate(context, services: services)
+ case "automation.applescript.validate":
+ return await scriptValidate(context, services: services)
case "automation.applescript.execute":
return await scriptExecute(context, services: services, executor: services.appleScriptExecutor)
case "application.learning.start":
@@ -452,6 +513,11 @@ public enum BuiltInHarnessToolExecutors {
_ = await services.generatedScripts.reject(id: scriptID, reason: "emptyScriptSource")
return failed(context, "Script artifact has no source to validate.", reason: "emptyScriptSource")
}
+ if artifact.language == .appleScript,
+ let rejectionReason = appleScriptValidationRejectionReason(artifact: artifact, context: context) {
+ _ = await services.generatedScripts.reject(id: scriptID, reason: rejectionReason)
+ return failed(context, "AppleScript artifact failed validation.", reason: rejectionReason)
+ }
let validated = await services.generatedScripts.validate(
id: scriptID,
@@ -748,15 +814,51 @@ public enum BuiltInHarnessToolExecutors {
_ context: HarnessToolExecutionContext,
services: HarnessBuiltInToolServices
) async -> HarnessToolResult {
- guard trimmed(context.call.input["targetApp"]) != nil else {
+ guard let targetApp = trimmed(context.call.input["targetApp"]) else {
return invalidInput(context, "automation.applescript.generate requires a targetApp.")
}
- guard trimmed(context.call.input["goal"]) != nil else {
+ guard let goal = trimmed(context.call.input["goal"]) 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"]
+ input["purpose"] = goal
+ if trimmed(input["scriptSource"] ?? input["source"]) == nil {
+ guard let generator = services.appleScriptGenerator else {
+ return failed(context, "No dynamic AppleScript generation backend is configured.", reason: "missingAppleScriptGenerationBackend")
+ }
+ let outcome = await generator(
+ HarnessScriptGenerationRequest(
+ language: .appleScript,
+ targetApp: targetApp,
+ bundleIdentifier: trimmed(context.call.input["bundleIdentifier"]),
+ goal: goal,
+ entities: scriptGenerationEntities(from: context),
+ allowedActions: context.call.input["allowedActions"] ?? "",
+ verification: context.call.input["verification"] ?? "",
+ worldFacts: context.worldModel.facts,
+ sourceTraceID: context.call.metadata["traceID"],
+ metadata: context.call.input
+ )
+ )
+ guard outcome.succeeded,
+ let generatedSource = trimmed(outcome.source)
+ else {
+ return failed(
+ context,
+ outcome.summary.isEmpty ? "Dynamic AppleScript generation failed." : outcome.summary,
+ reason: outcome.metadata["reason"] ?? "appleScriptGenerationFailed"
+ )
+ }
+ input["scriptSource"] = generatedSource
+ input.merge(
+ Dictionary(uniqueKeysWithValues: outcome.metadata.map { key, value in
+ ("generation.\(key)", value)
+ })
+ ) { current, _ in current }
+ input["generation.summary"] = outcome.summary
+ input["generation.backend"] = outcome.metadata["generator"] ?? "dynamicAppleScriptGenerator"
+ }
let generatedContext = HarnessToolExecutionContext(
taskID: context.taskID,
call: HarnessToolCall(
@@ -772,6 +874,78 @@ public enum BuiltInHarnessToolExecutors {
return await scriptGenerate(generatedContext, services: services, ownerSkillID: nil)
}
+ private static func appleScriptValidationRejectionReason(
+ artifact: HarnessGeneratedScriptArtifact,
+ context: HarnessToolExecutionContext
+ ) -> String? {
+ let source = artifact.source.trimmingCharacters(in: .whitespacesAndNewlines)
+ let lowercased = source.lowercased()
+ guard source.count <= 6_000 else {
+ return "appleScriptTooLarge"
+ }
+ guard lowercased.contains("tell application")
+ || lowercased.contains("using terms from application")
+ else {
+ return "missingAppleScriptApplicationScope"
+ }
+ let deniedFragments = [
+ "do shell script",
+ "system events",
+ "keystroke",
+ "key code",
+ "delete ",
+ "erase ",
+ "empty trash",
+ "shutdown",
+ "restart",
+ "quit "
+ ]
+ if let denied = deniedFragments.first(where: lowercased.contains) {
+ return "disallowedAppleScriptFragment:\(denied)"
+ }
+ if let targetApp = trimmed(
+ context.call.input["targetApp"]
+ ?? artifact.metadata["targetApp"]
+ ) {
+ let normalizedSource = normalized(source)
+ let normalizedTarget = normalized(targetApp)
+ let bundleIdentifier = trimmed(
+ context.call.input["bundleIdentifier"]
+ ?? artifact.metadata["bundleIdentifier"]
+ ).map(normalized)
+ guard normalizedSource.contains(normalizedTarget)
+ || bundleIdentifier.map({ normalizedSource.contains($0) }) == true
+ else {
+ return "targetAppNotReferenced"
+ }
+ }
+ return nil
+ }
+
+ private static func scriptGenerationEntities(
+ from context: HarnessToolExecutionContext
+ ) -> [String: String] {
+ var entities = context.worldModel.visibleText
+ for (key, value) in context.call.input {
+ if key.hasPrefix("entity.") {
+ entities[String(key.dropFirst("entity.".count))] = value
+ }
+ }
+ if let input = trimmed(context.call.input["input"]) {
+ entities["input"] = input
+ }
+ if let inputEntity = trimmed(context.call.input["inputEntity"]),
+ let value = trimmed(context.call.input[inputEntity] ?? context.call.input["input"]) {
+ entities[inputEntity] = value
+ }
+ if let rawEntities = context.call.input["entities"],
+ let data = rawEntities.data(using: .utf8),
+ let decoded = try? JSONSerialization.jsonObject(with: data) as? [String: String] {
+ entities.merge(decoded) { _, new in new }
+ }
+ return entities
+ }
+
private static func applicationLearningStart(
_ context: HarnessToolExecutionContext,
services: HarnessBuiltInToolServices
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
index 08054be2..f0a7befe 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
@@ -325,8 +325,9 @@ public enum BuiltInHarnessToolCatalog {
descriptor(
"automation.applescript.generate",
pluginID: "core.automation",
- summary: "Ask a model boundary to generate a bounded AppleScript artifact for a resolved app task.",
+ summary: "Ask a child model boundary to generate a small, bounded AppleScript artifact for a doable resolved app task.",
input: [
+ "scriptArtifactID": "Stable artifact identifier reused by validate and execute steps.",
"targetApp": "Resolved app name and bundle identifier.",
"goal": "Structured task goal.",
"entities": "Resolved task entities.",
@@ -346,6 +347,21 @@ public enum BuiltInHarnessToolCatalog {
"directExecution": "false"
]
),
+ descriptor(
+ "automation.applescript.validate",
+ pluginID: "core.automation",
+ summary: "Validate a generated AppleScript artifact before execution.",
+ input: [
+ "scriptArtifactID": "Generated AppleScript artifact identifier.",
+ "targetApp": "Resolved app name and bundle identifier.",
+ "validationPolicy": "Static checks, allowed APIs, target app, permissions, and review state."
+ ],
+ output: ["validationStatus": "validated or rejected with reason."],
+ permissions: [.appLookup],
+ safety: .readOnly,
+ requiredContext: ["generated AppleScript artifact", "validation policy"],
+ verification: ["validated artifacts record provenance and policy metadata"]
+ ),
descriptor(
"automation.applescript.execute",
pluginID: "core.automation",
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
index cb4bc294..816eb075 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
@@ -20,6 +20,7 @@ struct GenericHarnessTests {
#expect(names.contains("skill.script.validate"))
#expect(names.contains("skill.script.execute"))
#expect(names.contains("automation.applescript.generate"))
+ #expect(names.contains("automation.applescript.validate"))
#expect(names.contains("automation.applescript.execute"))
#expect(names.contains("application.learning.start"))
#expect(names.contains("application.learning.captureState"))
@@ -36,6 +37,10 @@ struct GenericHarnessTests {
#expect(execute?.metadata["requiresGeneratedArtifact"] == "true")
#expect(execute?.requiredPermissions == [.appControl, .input])
+ let validate = descriptors.first { $0.name == "automation.applescript.validate" }
+ #expect(validate?.requiredPermissions == [.appLookup])
+ #expect(validate?.safetyClass == .readOnly)
+
let skillSearch = descriptors.first { $0.name == "skill.search" }
#expect(skillSearch?.requiredPermissions == [.skillLookup])
#expect(skillSearch?.pluginID == "core.skills")
@@ -445,12 +450,12 @@ struct GenericHarnessTests {
let validatedAppleScript = await registry.execute(
HarnessToolCall(
id: "as-validate",
- name: "skill.script.validate",
+ name: "automation.applescript.validate",
input: ["scriptArtifactID": "script-open-notes", "validationPolicy": "static safe subset"]
),
taskID: "task-scripts",
worldModel: HarnessWorldModel(),
- grantedPermissions: [.skillLookup]
+ grantedPermissions: [.appLookup]
)
let executedAppleScript = await registry.execute(
HarnessToolCall(
@@ -508,6 +513,91 @@ struct GenericHarnessTests {
#expect(executedSkillScript.observations.facts["script.executed.output"] == "prepared")
}
+ @Test
+ func appleScriptGenerateUsesConfiguredChildGeneratorWhenSourceIsAbsent() async {
+ let scriptStore = HarnessGeneratedScriptStore()
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(
+ generatedScripts: scriptStore,
+ appleScriptGenerator: { request in
+ #expect(request.targetApp == "Music")
+ #expect(request.goal == "play requested media")
+ #expect(request.entities["query"] == "Yellow Coldplay")
+ return HarnessScriptGenerationOutcome(
+ succeeded: true,
+ source: #"tell application "Music" to play"#,
+ summary: "Generated Music playback script.",
+ metadata: ["generator": "test-child-llm"]
+ )
+ }
+ )
+ )
+
+ let generated = await registry.execute(
+ HarnessToolCall(
+ id: "dynamic-as-generate",
+ name: "automation.applescript.generate",
+ input: [
+ "scriptArtifactID": "dynamic-music-play",
+ "targetApp": "Music",
+ "goal": "play requested media",
+ "entities": #"{"query":"Yellow Coldplay"}"#,
+ "allowedActions": "play media in Music",
+ "verification": "playbackState=playing"
+ ],
+ metadata: ["traceID": "trace-dynamic-as"]
+ ),
+ taskID: "task-dynamic-as",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: [.appLookup]
+ )
+ let artifact = await scriptStore.artifact(id: "dynamic-music-play")
+
+ #expect(generated.status == .succeeded)
+ #expect(generated.metadata["scriptArtifactID"] == "dynamic-music-play")
+ #expect(generated.metadata["validationStatus"] == HarnessSkillScriptValidationStatus.pendingValidation.rawValue)
+ #expect(artifact?.source == #"tell application "Music" to play"#)
+ #expect(artifact?.metadata["generation.generator"] == "test-child-llm")
+ }
+
+ @Test
+ func appleScriptValidationRejectsOversizedGeneratedScripts() async {
+ let scriptStore = HarnessGeneratedScriptStore()
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(generatedScripts: scriptStore)
+ )
+ let oversizedSource = #"tell application "Notes" to activate"# + String(repeating: "\n-- filler", count: 800)
+
+ _ = await registry.execute(
+ HarnessToolCall(
+ id: "oversized-as-generate",
+ name: "automation.applescript.generate",
+ input: [
+ "scriptArtifactID": "oversized-notes-script",
+ "targetApp": "Notes",
+ "goal": "Activate Notes",
+ "scriptSource": oversizedSource
+ ]
+ ),
+ taskID: "task-oversized-as",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: [.appLookup]
+ )
+ let validated = await registry.execute(
+ HarnessToolCall(
+ id: "oversized-as-validate",
+ name: "automation.applescript.validate",
+ input: ["scriptArtifactID": "oversized-notes-script", "targetApp": "Notes"]
+ ),
+ taskID: "task-oversized-as",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: [.appLookup]
+ )
+
+ #expect(validated.status == .failed)
+ #expect(validated.metadata["reason"] == "appleScriptTooLarge")
+ }
+
@Test
func applicationLearningFlowSavesSearchableSkillPackWithValidatedScripts() async throws {
let root = FileManager.default.temporaryDirectory
diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.md
index da716051..1cd49c5d 100644
--- a/docs/guides/agent-harness.md
+++ b/docs/guides/agent-harness.md
@@ -1,165 +1,37 @@
# Agent Harness
```text
-+-----------+ +----------------+ +---------------------------+
-| User turn | ----> | User query | ----> | Generic harness lifecycle |
-+-----------+ +----------------+ +-------------+-------------+
- |
- v
- +----------------------------------+----------------------------------+
- | |
- v v
- +----------------+----------------+ +----------------------+----------------------+
- | Thread/task storage | | Compacted model context |
- | - conversation events | | - active/waiting tasks |
- | - task snapshots | | - summaries, memory, recent tool evidence |
- | - compaction metadata | | - bounded assets and world state |
- +----------------+----------------+ +----------------------+----------------------+
- ^ |
- | v
- | +--------------------+--------------------+
- | | Hosted model/runtime boundary |
- | | - structured intent |
- | | - ambiguity and risk |
- | | - plan, next step, verification criteria |
- | +--------------------+--------------------+
- | |
- | v
- | +--------------------+--------------------+
- | | Tool registry |
- | | - permissions and schemas |
- | | - skills, plugins, catalogs, memory |
- | | - app discovery, observation, actions |
- | +--------------------+--------------------+
- | |
- | v
- | +--------------------+--------------------+
- | | Guarded executors |
- | | - validate focus, safety, permissions |
- | | - execute one tool step |
- | | - return structured observations |
- | +--------------------+--------------------+
- | |
- +---------------------------------------------------------------------+
- verify, recover, clarify,
- pause, resume, or complete
+User turn
+ |
+ v
+Model boundary -> structured intent, risk, plan, verification
+ |
+ v
+Generic harness task state
+ |
+ v
+Tool registry -> guarded executor -> structured observation
+ | |
+ +----------- verify / recover / gate --+
```
-## What It Is
-
The agent harness is Donkey's app-agnostic runtime boundary for turning a user
-turn into durable task progress. It owns the lifecycle around intent,
-context-gathering, world modeling, planning, tool execution, verification,
-recovery, permission gates, clarification, pause/resume, interruption, and
-multi-task coordination.
-
-The generic harness contracts live in `apps/Donkey/Sources/DonkeyHarness/`.
-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
-the generic task definitions, generated or user-reviewed app catalog data, and
-memory. The core runtime does not ship app-specific Weather, Music, Notes, or
-Numbers task branches.
-
-The app catalog is part of the model boundary, not a hidden executor shortcut.
-User-query turns send the current supported app catalog to planning. If the
-catalog is still refreshing or does not contain a supported entry, the harness
-must surface conversation, clarification, waiting, or failed-safe state instead
-of silently dropping the request or executing an unsupported candidate.
-
-User query 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.
-
-User-query 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
-
-Every task has its own durable state:
-
-- task id and thread id
-- current goal
-- structured intent analysis
-- gathered context
-- world model
-- plan
-- granted permissions
-- tool history
-- pending continuation
-- lifecycle status
-
-Supported task statuses are:
-
-- `running`
-- `paused`
-- `waitingForUser`
-- `waitingForPermission`
-- `interrupted`
-- `resuming`
-- `completed`
-- `failedSafe`
-- `cancelled`
-
-Multiple tasks may be active at once. Mutable execution state must stay
-task-local unless it is stored in an explicit task-safe service. A pause,
-clarification gate, permission gate, or cancellation affects only the selected
-task; it must not block unrelated active tasks.
-
-## Thread Storage
-
-Threads are the durable conversation record. The generic harness defines a
-thread-store boundary for threads, events, assets, task snapshots, task events,
-and compaction snapshots. In tests this can be backed by an in-memory store; in
-the app the default generic lifecycle uses a file-backed local store under the
-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,
-tool history, and pending continuations. Summaries are stored as thread events
-with the `summary` role. Compaction snapshots store the selected event, asset,
-and task ids plus truncation/drop metadata so model context remains
-inspectable. Keeping thread records, task snapshots, and compaction metadata
-separate lets one thread coordinate multiple active tasks without mixing their
-execution state.
-
-## Smart Compaction
-
-The harness never sends raw unbounded history to a model. Before model-backed
-intent routing, generic planning, or slow-planner hint generation, compaction
-builds a bounded context packet. It keeps the current turn, active and waiting
-task state, pending questions or permissions, pinned events, durable summaries,
-the most recent useful events, recent tool summaries, memory summaries, and a
-bounded asset list.
-
-Large event bodies are truncated. Raw screenshots, full Accessibility trees,
-script source, and long tool outputs are saved as artifacts or structured
-records and summarized into the prompt. Compaction metadata records what was
-included, dropped, or truncated so the decision remains inspectable.
-
-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 user-query notch mirrors generic task stop states. Permission gates
-show the pending tool and missing permissions, and the approval control grants
-those exact permissions through the generic lifecycle. Follow-up course changes
-surface as typed interrupted/changed-course task state instead of generic
-attention text.
-
-## Turn Flow
+turn into durable task progress. It owns intent routing, bounded context,
+planning, guarded tool execution, verification, recovery, permission gates,
+clarification, pause/resume, interruption, and multi-task state.
+
+Keep the harness generic. App-specific behavior belongs in task definitions,
+catalog data, skills, generated artifacts, plugins, or memory. Core harness
+code must not add phrase lists, app-name branches, or one-off natural-language
+conditionals.
+
+## Runtime Shape
+
+A user-query turn enters the generic lifecycle before any local-app executor is
+selected. The model boundary returns structured intent, risk/ambiguity, context
+needs, plan steps, verification criteria, fallback policy, and clarification
+policy. Deterministic Swift then validates the structured plan against the tool
+registry, permissions, supported app catalog, and task state.
The loop is:
@@ -169,282 +41,137 @@ intake
-> context gathering
-> world model update
-> planning
--> execute one validated tool step
+-> execute one guarded tool step
-> verify
--> recover, continue, clarify, or complete
+-> recover, continue, clarify, ask permission, or complete
```
-The harness does not treat desktop work as a single model completion. It
-observes, acts, verifies, and replans. The planner may propose the next tool
-step, but deterministic Swift owns task state, tool validation, permissions,
-focus checks, execution, and result recording.
-
-Pointer-prompt local-app work is executed through the same tool loop. Planning
-receives compacted context, tool descriptors, relevant skills, and the current
-supported app catalog, then returns a structured route and plan. A local-app
-route must validate against the catalog before it becomes executable tool
-state. The runtime executes one guarded step, records the resulting
-Accessibility or screenshot-backed observation, and continues only while the
-next planned step remains valid. It stops on verification failure, missing
-evidence, permission gates, clarification gates, or exhausted plan steps.
-
-If the user interrupts a task, the harness classifies whether the turn starts a
-new task, modifies the current task, cancels, pauses, resumes, answers a
-clarification, grants permission, or is conversation. A course change updates
-the existing task goal/world model/plan and resumes from the checkpoint instead
-of blindly restarting.
-
-## Stop Points
-
-Waiting states are hard stop points.
-
-If a tool lacks permission, the task moves to `waitingForPermission`, stores a
-pending continuation, asks for the specific permission, and does not execute
-more tools until approval is recorded.
-
-If required information is missing, the task moves to `waitingForUser`, stores
-the pending continuation, asks a specific question, and resumes only after the
-answer is attached.
-
-Dangerous ambiguity must ask before acting. Safe ambiguity may be inferred.
-Recoverable ambiguity uses available tools first, such as memory, app search,
-screen observation, or skill lookup, and asks only if uncertainty remains
-material.
-
-## Tools And Plugins
-
-Tools are registered through the generic tool registry. A tool descriptor
-declares:
-
-- name
-- plugin id
-- summary
-- input/output schema
-- required permissions
-- safety class
-- required context
-- verification hints
-- metadata
-
-The planner sees tool descriptors and schemas, not Swift implementation
-details. 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, permission
-requests, memory lookup, skill lookup, skill-script lifecycle, app discovery,
-screen observation, UI element discovery and action, text and keyboard input,
-AppleScript generation/execution, state verification, and task lifecycle
-control.
-
-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.
+Desktop work is not a single model completion. The harness observes, acts,
+records evidence, verifies, and may replan. Models choose structured tool calls;
+Swift owns task state, tool validation, focus checks, permission gates,
+execution, and result recording.
+
+## Task State
+
+Each task has its own durable state: goal, structured intent, context, world
+model, plan, granted permissions, tool history, pending continuation, and
+lifecycle status.
+
+Active/waiting tasks stay task-local. A pause, clarification, permission gate,
+interruption, cancellation, or failed-safe state must affect only the selected
+task.
+
+Threads store conversation events and active task ids. Task snapshots store
+execution state. Compaction snapshots record what bounded context was sent to a
+model so decisions remain inspectable.
+
+## Context And Intent
+
+The harness never sends raw unbounded history to a model. Compaction keeps the
+current turn, relevant active/waiting task state, recent useful evidence,
+summaries, memory snippets, pending questions/permissions, and bounded assets.
+
+Never infer semantic intent by matching raw user text. Pass the turn through an
+LLM or another typed model/runtime boundary first. After that, deterministic
+code may match typed fields such as tool names, app ids, schema values,
+permissions, filesystem paths, and Accessibility roles/actions.
+
+The app catalog is part of the model boundary. If a requested app or capability
+is not supported or is still refreshing, surface conversation, clarification,
+waiting, or failed-safe state rather than silently executing an unsupported
+candidate.
+
+## Tools
+
+Tools are registered through the generic registry. A descriptor declares the
+tool name, plugin id, schemas, required permissions, safety class, required
+context, verification hints, and metadata. The planner sees descriptors and
+schemas, not Swift implementation details.
+
+Tool results return structured observations that update the task world model.
+Waiting states are hard stops:
+
+- missing permission moves the task to `waitingForPermission`
+- missing required user detail moves the task to `waitingForUser`
+- dangerous ambiguity asks before acting
+- verification failure chooses recovery, review, or failed-safe state
+
+Core tool families cover conversation, clarification, permission requests,
+memory, skills, app lookup, observation, UI element actions, text/keyboard
+input, AppleScript/script generation and execution, verification, learning, and
+lifecycle control.
## Computer Use
-Computer use is one tool family inside the harness.
-
-Accessibility is the primary source for actionable UI elements. Screenshots,
-vision, OCR, and hover evidence enrich the world model, labels, and layout. When
-Accessibility cannot resolve the target, scoped AI screenshot boxes may become a
-secondary actionable target for a guarded coordinate click.
-
-Screenshot understanding is a structured evidence source, not an overlay-only
-feature. Hosted screenshot parsers may stream partial UI-understanding results
-while a final parse is still running. The local-app controller forwards those
-partial controls, labels, boxes, confidence values, and provenance metadata into
-the same observation path used for actions, then replaces or augments them with
-the final parse result when it arrives.
-
-Element actions execute only after the harness validates:
-
-- target focus
-- permission policy
-- element eligibility
-- allowed action type
-- rate limits
-- safety class
-- verification criteria
-
-Models choose semantic targets and tool calls. They may choose an observed AI
-visual target when no Accessibility target is available. Coordinate input is a
-fallback execution path and must pass the same guarded execution checks as other
-input.
-
-Verification must be backed by task evidence. A local-app command attempt is not
-verified merely because the target app is focused or running after execution;
-the harness needs post-action evidence, such as guarded command traces, visible
-text, selected element state, app-reported results, or screenshot-backed
-observations, before the task can complete or choose a recovery path.
+Computer use is a tool family inside the harness. Accessibility is the primary
+source for actionable elements. Screenshots, vision, OCR, and hover evidence
+enrich the world model and can provide fallback targets when Accessibility is
+insufficient.
+
+Input must be guarded by target focus, permission policy, element eligibility,
+allowed action type, safety class, and verification criteria. Coordinate input
+is a fallback path, not a shortcut around those checks.
+
+Verification must be evidence-backed. A command is not complete merely because
+the target app is focused. The harness needs post-action evidence such as a
+guarded command trace, visible text, selected state, app-reported result, or
+screenshot-backed observation.
## AppleScript And Scripts
-AppleScript is a tool path, not a hardcoded helper path.
-
-AppleScript generation gathers the resolved app, goal, entities, allowed
-actions, and verification criteria, then passes that bounded request through a
-model/script-generation boundary. It returns a script artifact for validation or
-review. It does not execute the script.
-
-AppleScript execution may run only a validated, generated, or user-reviewed
-artifact through the guarded automation backend, with target app, permissions,
-action metadata, and verification evidence attached.
-
-App-specific AppleScript belongs in skill-local scripts or generated artifacts.
-The guarded backend renders explicit `appleScript.source` or
-`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,
-plugin, catalog entry, generated artifact, or user-reviewed definition.
-
-## Skills
-
-Skills are reusable harness extensions. A skill can be registered directly or
-discovered from configured roots by finding `SKILL.md` files. The skill
-registry indexes:
-
-- id
-- name
-- summary and description
-- source kind
-- instruction path
-- tags
-- provided tools
-- scripts
-- required permissions
-- metadata
-
-Skill lookup lets the planner find relevant instructions by structured task
-need. Loading a skill adds selected instructions to bounded planning context.
-
-Skills are shared infrastructure. They 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
-through the same skill descriptor shape as user/plugin skills and compacted
-before being sent to model boundaries.
-
-## Skill Scripts
-
-Skill packs may include generated scripts under a skill-local `scripts/`
-directory. Supported script descriptors include AppleScript, shell/Bash,
-Python, JavaScript, Swift, and additional language types.
-
-Each script descriptor records:
-
-- id
-- language
-- purpose
-- skill-relative path
-- generator provenance
-- validation status
-- required permissions
-- safety class
-- metadata
-
-Script generation, validation, and execution are separate steps. Generation
-creates a reusable artifact through a model boundary and stores it as pending
-validation. Validation records whether the script is allowed. Execution may run
-only validated scripts through the appropriate guarded backend with normal
-permission and verification gates.
-
-A learned application skill can therefore carry instructions, app maps,
-workflow recipes, evidence notes, and generated scripts together.
-
-## Learning Applications
-
-"Learn an application" is supported as a skill-producing harness task. The
-generic built-in tools `application.learning.start`,
-`application.learning.captureState`,
-`application.learning.proposeExploration`, `application.learning.distill`, and
-`application.learning.saveSkillPack` coordinate the flow: start a safe learning
-draft, record bounded screenshot and Accessibility evidence, propose reversible
-exploration candidates from technical Accessibility roles/actions, distill an
-app profile and workflow recipes, and save a reusable skill pack.
-
-For each meaningful state, the learner gathers:
-
-- screenshot evidence
-- Accessibility tree
-- focused app/window metadata
-- visible text
-- actionable elements
-- menus, buttons, fields, panels, and tabs
-- navigation path
-- what changed from the previous state
-
-The learner defaults to safe exploration: open menus, inspect tabs, focus
-fields, navigate panels, and avoid destructive/send/purchase/save-overwrite
-actions unless the user explicitly approves.
-
-The reusable output is distilled, not just raw captures:
-
-- `SKILL.md` for human/model instructions
-- structured app profile JSON
-- workflow recipes
-- generated scripts in `scripts/`
-- verification rules
-- safety notes
-- optional redacted evidence artifacts
-
-Validated generated scripts owned by the learned skill are copied into the
-skill-local `scripts/` directory when the pack is saved. Agents use the learned
-app skill by searching for the relevant skill, loading its bounded
-instructions, and then using any validated scripts or workflow tools exposed by
-that skill.
-
-## Intent Rules
-
-Never infer semantic user intent by string matching raw user input. Do not add
-phrase lists, prefixes, suffixes, regexes, app-name checks, greeting/help
-classifiers, or natural-language command-text matching to decide what the user
-wants.
-
-Pass the turn through an LLM or another typed model/runtime boundary first. Once
-structured output exists, deterministic code may validate typed fields, schema
-values, tool names, permissions, app identifiers, filesystem paths,
-Accessibility constants, and other non-semantic technical data.
-
-## Verification
-
-Use `swift test` from `apps/Donkey/`.
-
-Generic harness tests cover:
-
-- tool registration and unknown-tool rejection
-- permission stop/resume
-- clarification stop/resume
-- pause, resume, interrupt, cancel, complete, and fail-safe states
-- multiple active tasks with isolated state
-- one-tool-at-a-time execution loops
-- skill registration, search, loading, and filesystem discovery
-- script discovery, generation metadata, validation gates, and execution gates
-
-Computer-use tests cover app search, element retrieval, guarded element
-actions, screenshot/Accessibility evidence boundaries, and verification
-failure recovery.
-
-## Source Entry Points
-
-Start in:
-
-- `apps/Donkey/Sources/DonkeyHarness/` for generic harness lifecycle, tool
- registry, skill discovery, and script descriptors.
-- `apps/Donkey/Sources/DonkeyContracts/` for shared contracts that cross module
- boundaries.
-- `apps/Donkey/Sources/DonkeyRuntime/` for guarded runtime execution,
- Accessibility, app/window observation, and input backends.
+AppleScript is a tool path, not a hardcoded helper path. Generation creates a
+script artifact; it does not execute the script. Execution may run only a
+validated, generated, or user-reviewed artifact through the guarded backend,
+with target app, permissions, action metadata, and verification evidence.
+
+Dynamic AppleScript follows the same artifact boundary and should stay small:
+
+```text
+automation.applescript.generate
+-> automation.applescript.validate
+-> automation.applescript.execute
+-> observe
+-> verify
+```
+
+The generation step receives structured target-app, goal, entity,
+allowed-action, and verification inputs for one bounded target-app operation or
+a very small sequence. It must not try to build a full automation pipeline;
+observation, clicking, recovery, and verification stay as separate harness
+steps. If the requested operation is not doable as a small scoped AppleScript,
+generation should fail cleanly and the plan should use observation,
+Accessibility, screenshot, or UI tools instead.
+
+Planner output must not contain raw script source for dynamic AppleScript. A
+child generation boundary creates the artifact source, and the plan reuses the
+same `scriptArtifactID` across generation, validation, and execution.
+
+App-specific AppleScript belongs in skill-local scripts, generated artifacts,
+plugins, catalog entries, or user-reviewed definitions. Do not add app-named
+Swift helpers such as `musicPlaybackScript`.
+
+## Skills And Learning
+
+Skills are reusable harness extensions. Skill lookup gives the planner bounded
+instructions, descriptors, and validated scripts without putting app-specific
+branches into core runtime code.
+
+Learning an application is a skill-producing harness task. It gathers bounded
+screenshot and Accessibility evidence, explores only safe/reversible states
+unless the user approves more, distills an app profile and workflow recipes,
+and saves a reusable skill pack with any validated scripts.
+
+## Source Map
+
+Start here:
+
+- `apps/Donkey/Sources/DonkeyHarness/` for task state, registry, tools, skills,
+ thread storage, and generic runtime execution.
+- `apps/Donkey/Sources/DonkeyContracts/` for shared contracts across modules.
+- `apps/Donkey/Sources/DonkeyRuntime/` for guarded local-app execution,
+ Accessibility, screenshots, app/window observation, and input backends.
- `apps/Donkey/Sources/DonkeyAI/` for hosted model routing and adapters.
- `apps/Donkey/Sources/Donkey/` for user-query integration.
-Tests live in `apps/Donkey/Tests/DonkeyRuntimeTests/`.
+Tests live in `apps/Donkey/Tests/DonkeyRuntimeTests/`. Use focused `swift test`
+runs from `apps/Donkey/` when changing harness behavior.