Open source CapCut alternative.
TypeScript
feat(app): replace music_play with discoverable app_skill and skill_run
David Le374ce42f5e24
diff --git a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swiftindex c7453bab..2f2dd4ae 100644--- a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift+++ b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift@@ -18,7 +18,8 @@ public enum DonkeyCommandLayer {public enum Command: String, CaseIterable, Sendable {case shellExec = "shell_exec"case appsList = "apps_list"- case musicPlay = "music_play"+ case appSkill = "app_skill"+ case skillRun = "skill_run"}public static var descriptors: [HarnessToolDescriptor] {@@ -28,8 +29,8 @@ public enum DonkeyCommandLayer {HarnessToolDescriptor(name: Command.shellExec.rawValue,pluginID: pluginID,- summary: "Run a single-line shell command on the user's Mac and return its output. This is your primary, expert tool: prefer it for finding files (`mdfind`, `ls -t`, `find`), launching or quitting apps (`open -a Spotify`, `osascript -e 'quit app …'`), reading state (`date`, `pmset -g batt`, `system_profiler`), and changing settings (`defaults write`, `networksetup -set…`). Read-only commands run immediately; anything that changes state asks the user for one-time or always-allow consent first, so you may freely propose it. Destructive or privileged commands (`sudo`, `rm`, `dd`, piping into a shell) ask every time.",- inputSchema: ["command": "A safe, single-line shell command, e.g. `open -a Notes`, `osascript -e 'tell application \"Spotify\" to play'`, or `date`."],+ summary: "Run a single-line shell command on the user's Mac and return its output. This is your primary, expert tool: prefer it for finding files (`mdfind`, `ls -t`, `find`), launching or quitting apps (`open -a \"App Name\"`, `osascript -e 'quit app \"App Name\"'`), reading state (`date`, `pmset -g batt`, `system_profiler`), and changing settings (`defaults write`, `networksetup -set…`). Read-only commands run immediately; anything that changes state asks the user for one-time or always-allow consent first, so you may freely propose it. Destructive or privileged commands (`sudo`, `rm`, `dd`, piping into a shell) ask every time.",+ inputSchema: ["command": "A safe, single-line shell command, e.g. `open -a \"App Name\"`, `osascript -e '…'`, or `date`."],outputSchema: ["stdout": "Captured standard output (trimmed).","exitCode": "Process exit code."@@ -62,18 +63,31 @@ public enum DonkeyCommandLayer {safetyClass: .readOnly),HarnessToolDescriptor(- name: Command.musicPlay.rawValue,+ name: Command.appSkill.rawValue,pluginID: pluginID,- summary: "Search for and play media in a music app (Spotify or Apple Music) without screenshots.",+ summary: "Look up the installed operating playbook (skill) for a specific app before driving it. The playbook says how that app is operated — whether it is scriptable, must be driven by vision, and its known workflows and pitfalls. Call this whenever a task targets a specific app you have no loaded guidance for; if no skill is installed the result says so and you fall back to your general tools.",+ inputSchema: ["app": "The app's display name or bundle identifier."],+ outputSchema: [+ "found": "\"true\" when an operating playbook is installed for the app.",+ "guidance": "The app's operating playbook, when found."+ ],+ requiredPermissions: [.skillLookup],+ safetyClass: .readOnly+ ),+ HarnessToolDescriptor(+ name: Command.skillRun.rawValue,+ pluginID: pluginID,+ summary: "Execute a validated script that an installed skill ships, without screenshots. Skills advertise their scripts through app_skill (skill id + script ids); running one performs that skill's bounded multi-step workflow natively in well under a second. Use it whenever a looked-up skill offers a script that covers the task, instead of reinventing the steps yourself.",inputSchema: [- "query": "Track, artist, album, or playlist to search and play.",- "app": "Music app: Spotify or Music. Defaults to the user's available music app."+ "skillID": "The skill that ships the script, as advertised by app_skill.",+ "scriptID": "The validated script to execute, as advertised by app_skill.",+ "input": "The script's input value (e.g. a search query), when it takes one."],- optionalInputKeys: ["app"],- outputSchema: ["status": "Playback status reported by the music app."],+ optionalInputKeys: ["input"],+ outputSchema: ["status": "Structured status the script reports."],requiredPermissions: [.appControl, .input],safetyClass: .guardedInput,- verificationHints: ["the music app reports that playback started"]+ verificationHints: ["the script reports a successful structured status"])]}diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swiftindex c33aa284..1889648a 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift@@ -27,11 +27,55 @@ public enum DonkeyCommandBackends {return await shellExec(context)case .appsList:return listApps(context)- case .musicPlay:- return await playMusic(context)+ case .appSkill:+ return appSkill(context)+ case .skillRun:+ return await runSkillScript(context)}}+ // MARK: - app_skill++ /// Surface the installed operating playbook for an app, discovered from the+ /// skill packs by display name or bundle id — never from a hardcoded app+ /// list. Apps without a skill report that plainly so the model falls back to+ /// its general tools.+ private static func appSkill(_ context: HarnessToolExecutionContext) -> HarnessToolResult {+ guard let app = trimmed(context.call.input["app"]) else {+ return invalidInput(context, "app_skill requires an `app` display name or bundle identifier.")+ }+ guard let descriptor = BuiltInLocalAppSkillPacks.appSkillDescriptor(forApp: app, bundleIdentifier: app),+ let guidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(forApp: app, bundleIdentifier: app)+ else {+ return success(+ context,+ summary: "No operating skill is installed for \(app).",+ facts: ["appSkill.\(app)": "notFound"],+ metadata: ["found": "false", "app": app]+ )+ }+ // Advertise the skill's validated scripts so the model can execute a+ // covered workflow directly with skill_run instead of reinventing it.+ let scriptLines = descriptor.scripts.map { script in+ "- skillID=\(descriptor.id) scriptID=\(script.id)\(script.purpose.isEmpty ? "" : " — \(script.purpose)")"+ }+ let scriptsBlock = scriptLines.isEmpty+ ? ""+ : "\n\nValidated scripts (execute with skill_run):\n" + scriptLines.joined(separator: "\n")+ return success(+ context,+ summary: guidance + scriptsBlock,+ facts: ["appSkill.\(app)": "loaded"],+ metadata: [+ "found": "true",+ "app": app,+ "skillID": descriptor.id,+ "scriptIDs": descriptor.scripts.map(\.id).joined(separator: ","),+ "guidance": guidance+ ]+ )+ }+// MARK: - apps_list/// Default and ceiling for the installed-list page size. The installed@@ -186,16 +230,26 @@ public enum DonkeyCommandBackends {return result}- // MARK: - music_play+ // MARK: - skill_run- private static func playMusic(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {- guard trimmed(context.call.input["query"]) != nil else {- return invalidInput(context, "music_play requires a `query`.")+ /// Execute a validated script an installed skill ships, looked up by the+ /// skill/script ids the model got from `app_skill` — the generic native+ /// fast path for any skill-covered workflow, with nothing domain-specific.+ private static func runSkillScript(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard let skillID = trimmed(context.call.input["skillID"]) else {+ return invalidInput(context, "skill_run requires the `skillID` advertised by app_skill.")+ }+ guard let scriptID = trimmed(context.call.input["scriptID"]) else {+ return invalidInput(context, "skill_run requires the `scriptID` advertised by app_skill.")}guard let artifact = LocalAppUserQueryHarnessServices.builtInValidatedScriptArtifacts()- .first(where: { $0.id == "scripts-play-media-by-search" }) else {- return failed(context, "The bundled music playback skill is unavailable.", reason: "musicSkillUnavailable")+ .first(where: { $0.id == scriptID && $0.ownerSkillID == skillID }) else {+ return failed(+ context,+ "No validated script \(scriptID) is installed for skill \(skillID). Look the app's skill up with app_skill for the available scripts.",+ reason: "skillScriptUnavailable"+ )}let outcome = await LocalAppUserQueryHarnessServices.executeSkillScript(artifact: artifact, context: context)if outcome.metadata["clarification.required"] == "true" {@@ -203,18 +257,18 @@ public enum DonkeyCommandBackends {callID: context.call.id,toolName: context.call.name,status: .waitingForUser,- summary: "The music app needs clarification before playing.",- question: outcome.metadata["clarification.question"] ?? "What would you like me to play?",+ summary: "The script needs clarification before it can proceed.",+ question: outcome.metadata["clarification.question"] ?? "What exactly should I use?",metadata: outcome.metadata.merging(["gate": "clarification"]) { current, _ in current })}guard outcome.succeeded else {- return failed(context, outcome.summary, reason: outcome.metadata["failureReason"] ?? "musicPlayFailed")+ return failed(context, outcome.summary, reason: outcome.metadata["failureReason"] ?? "skillScriptFailed")}return success(context,summary: outcome.summary,- facts: ["musicStatus": outcome.metadata["status"] ?? "played"],+ facts: ["skillRun.\(scriptID)": outcome.metadata["status"] ?? "succeeded"],metadata: outcome.metadata)}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swiftindex 60d22d97..67ec98e2 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift@@ -57,6 +57,21 @@ public enum BuiltInLocalAppSkillPacks {bundleIdentifier: String? = nil,maxCharacters: Int = 4_000) -> String? {+ guard let match = appSkillDescriptor(forApp: appName, bundleIdentifier: bundleIdentifier) else {+ return nil+ }+ let body = bounded(strippedSkillMetadata(from: match.description), maxCharacters: maxCharacters)+ return body.isEmpty ? nil : body+ }++ /// The app-specific skill descriptor (one whose `apps:` frontmatter names this app by display+ /// name or bundle identifier), or nil when no app-specific skill is installed. Exposes the+ /// skill's id and validated scripts so callers can advertise runnable workflows alongside the+ /// operating playbook.+ public static func appSkillDescriptor(+ forApp appName: String,+ bundleIdentifier: String? = nil+ ) -> HarnessSkillDescriptor? {let wanted = Set(([appName, bundleIdentifier].compactMap { $0 }).map { $0.lowercased().trimmingCharacters(in: .whitespacesAndNewlines) }@@ -64,16 +79,13 @@ public enum BuiltInLocalAppSkillPacks {)guard !wanted.isEmpty else { return nil }- let match = descriptors().first { descriptor in+ return descriptors().first { descriptor inlet apps = (descriptor.metadata["apps"] ?? "").split(separator: ",").map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }return apps.contains { app in wanted.contains { AppNameMatching.matches($0, app) } }}- guard let match else { return nil }- let body = bounded(strippedSkillMetadata(from: match.description), maxCharacters: maxCharacters)- return body.isEmpty ? nil : body}public static func scriptSource(diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/SKILL.mdindex e6ef02fb..57adb106 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-mediadescription: Plan low-risk media playback in Apple Music or another supported media app.tags: media, music, playback, local-appkeywords: play, listen, music, song, track, tune, album, playlist, artist, band, audio, podcast, radio, pause, resume, volume+apps: Music, Apple Music, com.apple.Musictools: app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyVisibleTextscripts: scripts-play-media-by-search@@ -20,9 +21,9 @@ Set `metadata.mediaSelection.kind` to `explicit_song`, `explicit_album`, `explicPrefer the validated skill script path when the selected catalog entry supports it:-- 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.+- This skill ships a validated script — `skillID=music-media`, `scriptID=scripts-play-media-by-search` — that searches Apple Music for the query and starts playback as one bounded step.+- Execute it with your skill-script execution tool (`skill.script.execute`, or `skill_run` in the fast command layer), passing the structured `query` as the script input.+- Verify the structured script evidence (`state.verify`, or the script's returned status fields); 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`.diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppSkillCommandTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppSkillCommandTests.swiftnew file mode 100644index 00000000..6de90204--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AppSkillCommandTests.swift@@ -0,0 +1,86 @@+import DonkeyContracts+import DonkeyHarness+import DonkeyRuntime+import Foundation+import Testing++@Suite+struct AppSkillCommandTests {+ @MainActor+ private func lookup(_ app: String) async -> HarnessToolResult? {+ let descriptor = DonkeyCommandLayer.descriptors.first { $0.name == "app_skill" }!+ let context = HarnessToolExecutionContext(+ taskID: "test",+ call: HarnessToolCall(name: "app_skill", input: ["app": app]),+ descriptor: descriptor,+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.skillLookup]+ )+ return await DonkeyCommandBackends.makeExecutor()(context)+ }++ @Test+ @MainActor+ func discoversAppOperatingPlaybooksFromSkillPacks() async {+ // App knowledge comes from the discoverable skill packs, never a+ // hardcoded list: the bundled Spotify pack matches by display name and+ // by bundle id, and its playbook says the app is driven by vision.+ for key in ["Spotify", "com.spotify.client"] {+ let result = await lookup(key)+ #expect(result?.status == .succeeded)+ #expect(result?.metadata["found"] == "true")+ #expect(result?.summary.lowercased().contains("vision") == true)+ }+ }++ @Test+ @MainActor+ func reportsMissingSkillsPlainly() async {+ let result = await lookup("Some App Without A Skill")+ #expect(result?.status == .succeeded)+ #expect(result?.metadata["found"] == "false")+ }++ @Test+ @MainActor+ func advertisesValidatedScriptsForScriptBackedSkills() async {+ // The music skill is discovered like any other app skill (its `apps:`+ // frontmatter, no hardcoded list) and advertises its validated script+ // so the model can execute the workflow with skill_run.+ for key in ["Music", "Apple Music", "com.apple.Music"] {+ let result = await lookup(key)+ #expect(result?.metadata["found"] == "true")+ #expect(result?.metadata["skillID"] == "music-media")+ #expect(result?.metadata["scriptIDs"]?.contains("scripts-play-media-by-search") == true)+ #expect(result?.summary.contains("skill_run") == true)+ }+ }++ @Test+ @MainActor+ func skillRunRejectsUnknownScriptsWithoutSideEffects() async {+ let descriptor = DonkeyCommandLayer.descriptors.first { $0.name == "skill_run" }!+ func run(_ input: [String: String]) async -> HarnessToolResult? {+ await DonkeyCommandBackends.makeExecutor()(HarnessToolExecutionContext(+ taskID: "test",+ call: HarnessToolCall(name: "skill_run", input: input),+ descriptor: descriptor,+ worldModel: HarnessWorldModel(),+ grantedPermissions: [.appControl, .input]+ ))+ }++ let missing = await run(["scriptID": "scripts-play-media-by-search"])+ #expect(missing?.status == .invalidInput)++ // A script id must belong to the named skill — ids from one skill can't+ // execute under another.+ let mismatched = await run(["skillID": "spotify-operate", "scriptID": "scripts-play-media-by-search"])+ #expect(mismatched?.status == .failed)+ #expect(mismatched?.metadata["reason"] == "skillScriptUnavailable")++ let unknown = await run(["skillID": "music-media", "scriptID": "no-such-script"])+ #expect(unknown?.status == .failed)+ #expect(unknown?.metadata["reason"] == "skillScriptUnavailable")+ }+}diff --git a/apps/Donkey/docs/fast-command-layer-and-gemini-live.md b/apps/Donkey/docs/fast-command-layer-and-gemini-live.mdindex b40d6005..e0e408cc 100644--- a/apps/Donkey/docs/fast-command-layer-and-gemini-live.md+++ b/apps/Donkey/docs/fast-command-layer-and-gemini-live.md@@ -37,15 +37,18 @@ A deliberately small set:|---|---|| `shell_exec` | runs a safe, single-line shell command via `/bin/zsh -c` and returns its output — the primary, general-purpose tool || `apps_list` | reuses `MacLocalAppAvailabilityProvider.installedApplications()` (Spotlight-backed, names + bundle ids, includes Apple native apps) + running apps so the model targets exact names instead of guessing; the installed list is paginated (`filter`/`offset`/`limit`, with `hasMore`/`nextOffset` in the result) so the full catalog survives the response cap |-| `music_play` | reuses the bundled, pre-validated `music-media` `play-media-by-search.applescript` (a multi-step search→play workflow a one-liner can't reproduce) |+| `app_skill` | looks up the installed operating playbook (skill pack) for a specific app — discovered by the skill's `apps:` frontmatter, never a hardcoded list — and advertises the skill's validated scripts |+| `skill_run` | executes a validated script an installed skill ships (by the `skillID`/`scriptID` that `app_skill` advertised) — the generic native fast path for any skill-covered multi-step workflow a one-liner can't reproduce (e.g. the `music-media` search→play script) |`shell_exec` is the **primary, general-purpose tool** (the same capability the competitor'sRealtime setup exposes) — listed first and prioritized in the system instruction. It handles mostrequests directly: opening/quitting/controlling apps (`open -a Spotify`, `osascript -e '…'`),changing settings, opening URLs (`open https://…`), and reading system state. Earlier dedicatedtools (`app.open`, `app.quit`, `browser.open_url`, `system.set_volume`) were **removed** as-redundant once `shell_exec` could do them reliably; only the two that earn their keep remain —-`apps_list` (discovery is awkward via raw shell) and `music_play` (encapsulated workflow). The+redundant once `shell_exec` could do them reliably; what remains is generic — `apps_list`+(discovery is awkward via raw shell) and the `app_skill`/`skill_run` pair (skill discovery and+validated-script execution; the earlier hardcoded `music_play` tool became the `music-media`+skill's script, reachable through them). Themodel is told to send only safe single-line commands; a backstop guardrail in`DonkeyCommandBackends` enforces single-line input, a length cap, and a hard ~12s timeout(SIGTERM→SIGKILL). Unsafe commands are caught by a **command-word** check on each pipeline/segment