Open source CapCut alternative.
TypeScript
feat(app): native MusicKit music playback
David Lee86237b1a071
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swiftindex 2b6a3609..5fcdde4a 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift@@ -408,8 +408,8 @@ public struct HarnessSkillFileSystemSource: Sendable {let relativePath = relativePath(of: url, from: skillDirectory)let basename = url.deletingPathExtension().lastPathComponent// Derive the script ID from the path WITHOUT the file extension so it matches the- // `scripts:` IDs declared in SKILL.md (e.g. `scripts-play-media-by-search`, not- // `scripts-play-media-by-search-applescript`).+ // `scripts:` IDs declared in SKILL.md (e.g. `scripts-save-note`, not+ // `scripts-save-note-applescript`).let relativePathWithoutExtension = (relativePath as NSString).deletingPathExtensionreturn HarnessSkillScriptDescriptor(id: slug(relativePathWithoutExtension),diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swiftindex 8e667605..f33795c0 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift@@ -7,6 +7,13 @@ public struct HarnessToolDescriptor: Codable, Equatable, Sendable {/// need a later read-only observation before `run.complete` is accepted.public static let resultIsEvidenceMetadataKey = "resultIsEvidence"+ /// Descriptor metadata key for a multi-action tool (one whose `action` input selects the+ /// operation) naming, comma-separated, the `action` values that are pure reads. The runtime's+ /// duplicate-action guard exempts those calls: re-listing or re-reading is legitimate+ /// verification even when the tool's overall safety class is state-changing, and the guard+ /// must never block the re-read its own rejection message asks for.+ public static let readOnlyActionsMetadataKey = "readOnlyActions"+public var name: Stringpublic var pluginID: Stringpublic var summary: Stringdiff --git a/apps/Donkey/Sources/DonkeyRuntime/MusicPlaybackService.swift b/apps/Donkey/Sources/DonkeyRuntime/MusicPlaybackService.swiftnew file mode 100644index 00000000..00bb92ad--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/MusicPlaybackService.swift@@ -0,0 +1,781 @@+import Foundation+import MusicKit++/// One catalog search result the planner can play: a typed kind plus the catalog id, so later calls+/// match on structured fields, never on free text.+public struct MusicSearchHit: Equatable, Sendable {+ public enum Kind: String, Sendable, CaseIterable {+ case song, album, playlist, station+ }++ public var kind: Kind+ public var id: String+ public var title: String+ /// Artist for songs/albums, curator for playlists; empty when the kind has none (stations).+ public var artist: String+ /// The song's album title; empty for other kinds.+ public var album: String++ public init(kind: Kind, id: String, title: String, artist: String = "", album: String = "") {+ self.kind = kind+ self.id = id+ self.title = title+ self.artist = artist+ self.album = album+ }+}++/// One playlist in the user's music library, by typed id — what playlist tools list, create, and+/// add to.+public struct MusicPlaylistSummary: Equatable, Sendable {+ public var id: String+ public var name: String++ public init(id: String, name: String) {+ self.id = id+ self.name = name+ }+}++/// One entry inside a library playlist, for reporting and verification after edits.+public struct MusicPlaylistEntry: Equatable, Sendable {+ public var title: String+ public var artist: String++ public init(title: String, artist: String = "") {+ self.title = title+ self.artist = artist+ }+}++/// Queue repeat setting, by the names the planner uses.+public enum MusicRepeatSetting: String, Sendable {+ case off, one, all+}++/// A point-in-time read of the playback engine, with optional advancement evidence: when+/// `positionAdvancing` is non-nil the position was sampled twice, and `true` means audio is really+/// progressing — the only trustworthy "it is playing" signal (a status string alone can lie).+/// Shuffle/repeat are nil when the player has not reported them (nothing queued yet).+public struct MusicPlaybackSnapshot: Equatable, Sendable {+ public enum Status: String, Sendable {+ case playing, paused, stopped, interrupted, seeking, unknown+ }++ public var status: Status+ public var title: String?+ public var artist: String?+ public var positionSeconds: Double+ public var positionAdvancing: Bool?+ public var shuffleOn: Bool?+ public var repeatSetting: MusicRepeatSetting?++ public init(+ status: Status,+ title: String? = nil,+ artist: String? = nil,+ positionSeconds: Double = 0,+ positionAdvancing: Bool? = nil,+ shuffleOn: Bool? = nil,+ repeatSetting: MusicRepeatSetting? = nil+ ) {+ self.status = status+ self.title = title+ self.artist = artist+ self.positionSeconds = positionSeconds+ self.positionAdvancing = positionAdvancing+ self.shuffleOn = shuffleOn+ self.repeatSetting = repeatSetting+ }+}++/// Why a music operation failed, with the exact actionable cause in the message — these strings go+/// straight to the thread and the user-facing summary, so they must name what to fix, not just that+/// something failed.+public enum MusicPlaybackError: Error, Equatable, CustomStringConvertible {+ /// Media & Apple Music permission missing/denied for this app.+ case notAuthorized(String)+ /// No active Apple Music subscription / not signed in for catalog playback.+ case subscriptionRequired(String)+ /// MusicKit could not get its developer token — a signing/provisioning problem, not a user one.+ case developerTokenUnavailable(String)+ /// The query or id matched nothing playable.+ case notFound(String)+ /// Playback was issued but position never advanced.+ case playbackDidNotStart(String)+ /// Any other request failure, with the underlying error text.+ case requestFailed(String)++ public var description: String {+ switch self {+ case let .notAuthorized(detail): return detail+ case let .subscriptionRequired(detail): return detail+ case let .developerTokenUnavailable(detail): return detail+ case let .notFound(detail): return detail+ case let .playbackDidNotStart(detail): return detail+ case let .requestFailed(detail): return detail+ }+ }+}++/// The native music boundary: catalog search, playback, transport, and state — everything the music+/// skill needs, with no Music-app GUI or AppleScript involved. The app-facing tools talk to this+/// protocol; `MusicKitPlaybackService` is the real implementation and tests substitute a fake.+@MainActor+public protocol MusicPlaybackServicing {+ func search(query: String, limit: Int) async throws -> [MusicSearchHit]+ /// Plays one specific catalog item and returns a snapshot with advancement evidence.+ func play(kind: MusicSearchHit.Kind, id: String) async throws -> MusicPlaybackSnapshot+ /// One-shot search + play: ranks hits (preferred kind first when given, else song → album →+ /// playlist → station, each in catalog relevance order) and plays the top match.+ func playTopMatch(query: String, preferredKind: MusicSearchHit.Kind?) async throws+ -> (hit: MusicSearchHit, snapshot: MusicPlaybackSnapshot)+ /// Inserts a catalog item into the play queue without interrupting what's playing. Stations+ /// cannot be queued (they replace the queue) — the tool layer rejects them before this call.+ func enqueue(kind: MusicSearchHit.Kind, id: String, next: Bool) async throws -> MusicPlaybackSnapshot+ func pause() async throws -> MusicPlaybackSnapshot+ func resume() async throws -> MusicPlaybackSnapshot+ func stop() async throws -> MusicPlaybackSnapshot+ func skipToNext() async throws -> MusicPlaybackSnapshot+ func skipToPrevious() async throws -> MusicPlaybackSnapshot+ /// Jumps the play position to an absolute second offset in the current entry (clamped at 0).+ func seek(toSeconds: Double) async throws -> MusicPlaybackSnapshot+ /// Moves the play position relatively — positive fast-forwards, negative rewinds (clamped at 0).+ func seek(bySeconds: Double) async throws -> MusicPlaybackSnapshot+ func setShuffle(_ enabled: Bool) async throws -> MusicPlaybackSnapshot+ func setRepeat(_ setting: MusicRepeatSetting) async throws -> MusicPlaybackSnapshot+ /// Samples the position over ~1s so the snapshot carries advancement evidence.+ func status() async -> MusicPlaybackSnapshot+ /// The user's library playlists, newest context first as the platform returns them.+ func libraryPlaylists(limit: Int) async throws -> [MusicPlaylistSummary]+ func createPlaylist(name: String, description: String?) async throws -> MusicPlaylistSummary+ /// Adds catalog songs (ids from `search`) to a library playlist.+ func addToPlaylist(playlistID: String, songIDs: [String]) async throws+ func playlistEntries(playlistID: String, limit: Int) async throws -> [MusicPlaylistEntry]+}++/// MusicKit-backed implementation. Plays through `ApplicationMusicPlayer` in this process — the+/// Music app is never launched, focused, scripted, or clicked.+///+/// Requirements this surface makes explicit when missing (instead of failing generically):+/// - Media & Apple Music consent (`MusicAuthorization`, needs `NSAppleMusicUsageDescription`).+/// - A MusicKit developer token: the app must be signed with a real development identity and its+/// bundle id enabled for MusicKit — an ad-hoc-signed build cannot get a token.+/// - An active Apple Music subscription on this Mac's Apple ID for catalog playback.+@MainActor+public final class MusicKitPlaybackService: MusicPlaybackServicing {+ private var player: ApplicationMusicPlayer { .shared }++ public init() {}++ public func search(query: String, limit: Int) async throws -> [MusicSearchHit] {+ try await ensureAuthorized()+ var request = MusicCatalogSearchRequest(+ term: query,+ types: [Song.self, Album.self, Playlist.self, Station.self]+ )+ request.limit = max(1, min(limit, 25))+ let response: MusicCatalogSearchResponse+ do {+ response = try await request.response()+ } catch {+ throw Self.mapped(error)+ }+ var hits: [MusicSearchHit] = []+ hits += response.songs.map {+ MusicSearchHit(kind: .song, id: $0.id.rawValue, title: $0.title, artist: $0.artistName, album: $0.albumTitle ?? "")+ }+ hits += response.albums.map {+ MusicSearchHit(kind: .album, id: $0.id.rawValue, title: $0.title, artist: $0.artistName)+ }+ hits += response.playlists.map {+ MusicSearchHit(kind: .playlist, id: $0.id.rawValue, title: $0.name, artist: $0.curatorName ?? "")+ }+ hits += response.stations.map {+ MusicSearchHit(kind: .station, id: $0.id.rawValue, title: $0.name)+ }+ return hits+ }++ public func play(kind: MusicSearchHit.Kind, id: String) async throws -> MusicPlaybackSnapshot {+ try await ensureAuthorized()+ do {+ switch kind {+ case .song:+ try await ensureSubscribed()+ let song = try await firstCatalogItem(+ MusicCatalogResourceRequest<Song>(matching: \.id, equalTo: MusicItemID(id)), id: id+ )+ player.queue = ApplicationMusicPlayer.Queue(for: [song])+ case .album:+ try await ensureSubscribed()+ let album = try await firstCatalogItem(+ MusicCatalogResourceRequest<Album>(matching: \.id, equalTo: MusicItemID(id)), id: id+ )+ player.queue = ApplicationMusicPlayer.Queue(for: [album])+ case .playlist:+ // Library first: "play my X playlist" ids come from libraryPlaylists, play without+ // a catalog subscription, and don't exist in the catalog. A miss falls through to+ // the catalog lookup, which does require a subscription.+ if let library = try await Self.fetchLibraryPlaylist(id: id) {+ player.queue = ApplicationMusicPlayer.Queue(for: [library])+ } else {+ try await ensureSubscribed()+ let playlist = try await firstCatalogItem(+ MusicCatalogResourceRequest<Playlist>(matching: \.id, equalTo: MusicItemID(id)), id: id+ )+ player.queue = ApplicationMusicPlayer.Queue(for: [playlist])+ }+ case .station:+ try await ensureSubscribed()+ let station = try await firstCatalogItem(+ MusicCatalogResourceRequest<Station>(matching: \.id, equalTo: MusicItemID(id)), id: id+ )+ player.queue = ApplicationMusicPlayer.Queue(for: [station])+ }+ } catch let error as MusicPlaybackError {+ throw error+ } catch {+ throw Self.mapped(error)+ }+ return try await startAndVerify(describedAs: "\(kind.rawValue) \(id)")+ }++ public func playTopMatch(query: String, preferredKind: MusicSearchHit.Kind?) async throws+ -> (hit: MusicSearchHit, snapshot: MusicPlaybackSnapshot) {+ try await ensureAuthorized()+ // Library first: owned/downloaded content plays without a catalog subscription and is+ // instant, so a broad term (an artist, an album, a saved playlist) plays whatever the user+ // already owns before reaching for the catalog. A library miss or search error falls+ // through to the catalog path.+ if let owned = try? await Self.queueFirstLibraryMatch(query: query, preferredKind: preferredKind) {+ return (owned, try await startAndVerify(describedAs: "\(owned.kind.rawValue) \"\(owned.title)\""))+ }+ let hits = try await search(query: query, limit: 10)+ guard let hit = Self.topMatch(in: hits, preferredKind: preferredKind) else {+ throw MusicPlaybackError.notFound(+ "Apple Music catalog search found nothing playable for \"\(query)\"."+ )+ }+ return (hit, try await play(kind: hit.kind, id: hit.id))+ }++ /// Starts playback for the already-loaded queue and samples the position until it advances —+ /// the only trustworthy "it really played" signal. Throws a typed `playbackDidNotStart` (not a+ /// generic failure) naming what to check when the position never moves.+ private func startAndVerify(describedAs description: String) async throws -> MusicPlaybackSnapshot {+ do {+ try await Self.startPlayback()+ } catch {+ throw Self.mapped(error)+ }+ let snapshot = await snapshotWithAdvancementEvidence(maxTicks: 5)+ guard snapshot.positionAdvancing == true else {+ throw MusicPlaybackError.playbackDidNotStart(+ "Playback was issued for \(description) but the position never advanced "+ + "(status=\(snapshot.status.rawValue), position=\(String(format: "%.1f", snapshot.positionSeconds))s). "+ + "The item may be unavailable in this storefront, or Apple Music is not usable on this Mac."+ )+ }+ return snapshot+ }++ /// Searches the user's own library and loads the top match into the queue, returning a hit that+ /// describes it — or nil when the library has nothing matching. Owned/downloaded content plays+ /// without a catalog subscription, so this restores the local-first behavior the native path+ /// replaced. nonisolated so the non-Sendable request/player machinery stays in one region.+ private nonisolated static func queueFirstLibraryMatch(+ query: String,+ preferredKind: MusicSearchHit.Kind?+ ) async throws -> MusicSearchHit? {+ var request = MusicLibrarySearchRequest(term: query, types: [Song.self, Album.self, Playlist.self])+ request.limit = 10+ let response = try await request.response()+ let player = ApplicationMusicPlayer.shared+ // Prefer the requested kind, then song → album → playlist (the library has no stations).+ let order: [MusicSearchHit.Kind]+ if let preferredKind {+ order = [preferredKind] + MusicSearchHit.Kind.allCases.filter { $0 != preferredKind }+ } else {+ order = MusicSearchHit.Kind.allCases+ }+ for kind in order {+ switch kind {+ case .song:+ if let song = response.songs.first {+ player.queue = ApplicationMusicPlayer.Queue(for: [song])+ return MusicSearchHit(+ kind: .song, id: song.id.rawValue, title: song.title,+ artist: song.artistName, album: song.albumTitle ?? ""+ )+ }+ case .album:+ if let album = response.albums.first {+ player.queue = ApplicationMusicPlayer.Queue(for: [album])+ return MusicSearchHit(kind: .album, id: album.id.rawValue, title: album.title, artist: album.artistName)+ }+ case .playlist:+ if let playlist = response.playlists.first {+ player.queue = ApplicationMusicPlayer.Queue(for: [playlist])+ return MusicSearchHit(kind: .playlist, id: playlist.id.rawValue, title: playlist.name, artist: playlist.curatorName ?? "")+ }+ case .station:+ continue+ }+ }+ return nil+ }++ /// Preferred kind first when given; otherwise songs, then albums, playlists, stations — each in+ /// the catalog's own relevance order. Pure ranking on typed fields.+ static func topMatch(in hits: [MusicSearchHit], preferredKind: MusicSearchHit.Kind?) -> MusicSearchHit? {+ if let preferredKind, let preferred = hits.first(where: { $0.kind == preferredKind }) {+ return preferred+ }+ for kind in MusicSearchHit.Kind.allCases {+ if let hit = hits.first(where: { $0.kind == kind }) {+ return hit+ }+ }+ return nil+ }++ public func enqueue(kind: MusicSearchHit.Kind, id: String, next: Bool) async throws -> MusicPlaybackSnapshot {+ try await ensureAuthorized()+ do {+ switch kind {+ case .song:+ try await ensureSubscribed()+ let song = try await firstCatalogItem(+ MusicCatalogResourceRequest<Song>(matching: \.id, equalTo: MusicItemID(id)), id: id+ )+ try await Self.insertIntoQueue(song, next: next)+ case .album:+ try await ensureSubscribed()+ let album = try await firstCatalogItem(+ MusicCatalogResourceRequest<Album>(matching: \.id, equalTo: MusicItemID(id)), id: id+ )+ try await Self.insertIntoQueue(album, next: next)+ case .playlist:+ // Owned library playlists queue without a subscription; a miss needs the catalog.+ if let library = try await Self.fetchLibraryPlaylist(id: id) {+ try await Self.insertIntoQueue(library, next: next)+ } else {+ try await ensureSubscribed()+ let playlist = try await firstCatalogItem(+ MusicCatalogResourceRequest<Playlist>(matching: \.id, equalTo: MusicItemID(id)), id: id+ )+ try await Self.insertIntoQueue(playlist, next: next)+ }+ case .station:+ throw MusicPlaybackError.requestFailed(+ "Stations cannot be queued — a station replaces the queue. Play it with music.play instead."+ )+ }+ } catch let error as MusicPlaybackError {+ throw error+ } catch {+ throw Self.mapped(error)+ }+ return currentSnapshot()+ }++ public func pause() async throws -> MusicPlaybackSnapshot {+ player.pause()+ return currentSnapshot()+ }++ public func resume() async throws -> MusicPlaybackSnapshot {+ do {+ try await Self.startPlayback()+ } catch {+ throw Self.mapped(error)+ }+ return await snapshotWithAdvancementEvidence(maxTicks: 3)+ }++ public func stop() async throws -> MusicPlaybackSnapshot {+ player.stop()+ return currentSnapshot()+ }++ public func skipToNext() async throws -> MusicPlaybackSnapshot {+ do {+ try await Self.advanceQueue(forward: true)+ } catch {+ throw Self.mapped(error)+ }+ return await snapshotWithAdvancementEvidence(maxTicks: 3)+ }++ public func skipToPrevious() async throws -> MusicPlaybackSnapshot {+ do {+ try await Self.advanceQueue(forward: false)+ } catch {+ throw Self.mapped(error)+ }+ return await snapshotWithAdvancementEvidence(maxTicks: 3)+ }++ public func seek(toSeconds: Double) async throws -> MusicPlaybackSnapshot {+ player.playbackTime = max(0, toSeconds)+ return currentSnapshot()+ }++ public func seek(bySeconds: Double) async throws -> MusicPlaybackSnapshot {+ player.playbackTime = max(0, player.playbackTime + bySeconds)+ return currentSnapshot()+ }++ public func setShuffle(_ enabled: Bool) async throws -> MusicPlaybackSnapshot {+ player.state.shuffleMode = enabled ? .songs : .off+ return currentSnapshot()+ }++ public func setRepeat(_ setting: MusicRepeatSetting) async throws -> MusicPlaybackSnapshot {+ switch setting {+ case .off: player.state.repeatMode = MusicPlayer.RepeatMode.none+ case .one: player.state.repeatMode = .one+ case .all: player.state.repeatMode = .all+ }+ return currentSnapshot()+ }++ public func status() async -> MusicPlaybackSnapshot {+ await snapshotWithAdvancementEvidence(maxTicks: 2)+ }++ // MARK: - Playlists++ /// MusicKit's library WRITE surface (`MusicLibrary.createPlaylist`/`add`/`edit`) is+ /// `@available(macOS, unavailable)`, so on macOS reads go through `MusicLibraryRequest` and+ /// writes go through the Apple Music REST API via `MusicDataRequest` (which signs requests with+ /// the same developer/user tokens). Removing tracks and deleting playlists have no public API on+ /// any platform — callers get a typed unsupported error path via the tool layer, never a fake+ /// success.++ public func libraryPlaylists(limit: Int) async throws -> [MusicPlaylistSummary] {+ try await ensureAuthorized()+ do {+ return try await Self.fetchLibraryPlaylists(limit: max(1, min(limit, 100)))+ } catch {+ throw Self.mapped(error)+ }+ }++ public func createPlaylist(name: String, description: String?) async throws -> MusicPlaylistSummary {+ try await ensureAuthorized()+ var attributes: [String: Any] = ["name": name]+ if let description, !description.isEmpty {+ attributes["description"] = description+ }+ let body: [String: Any] = ["attributes": attributes]+ var urlRequest = URLRequest(url: Self.libraryPlaylistsURL)+ urlRequest.httpMethod = "POST"+ urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")+ urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: body)+ let response: (data: Data, httpStatus: Int)+ do {+ response = try await Self.musicAPIResponse(urlRequest)+ } catch {+ throw Self.mapped(error)+ }+ if let created = Self.parsePlaylistSummaries(from: response.data).first {+ return created+ }+ // The write reply was ambiguous (no playlist in the body). Confirm by reading the library:+ // a matching playlist means the create actually landed; its absence makes this a provably+ // failed create, reported with the exact cause instead of an empty mystery.+ if let confirmed = (try? await Self.fetchLibraryPlaylists(limit: 100))?.first(where: { $0.name == name }) {+ return confirmed+ }+ throw MusicPlaybackError.requestFailed(+ Self.playlistCreateFailureDetail(name: name, httpStatus: response.httpStatus, body: response.data)+ )+ }++ /// The failure detail when a playlist create returned no playlist: names the HTTP status, the+ /// response body (or its absence), and the verification-read result, plus a do-not-retry+ /// directive — a failure summary must state the exact cause, and this one must also stop the+ /// planner from re-issuing the same doomed call.+ static func playlistCreateFailureDetail(name: String, httpStatus: Int, body: Data) -> String {+ let bodyDetail = body.isEmpty+ ? "an empty body"+ : "body: \(String(decoding: body.prefix(300), as: UTF8.self))"+ return "Playlist create for \"\(name)\" failed: the Apple Music API returned HTTP \(httpStatus) "+ + "with \(bodyDetail), and a follow-up library read found no playlist named \"\(name)\". "+ + "Do not retry the same call — report this exact cause to the user."+ }++ public func addToPlaylist(playlistID: String, songIDs: [String]) async throws {+ try await ensureAuthorized()+ guard !songIDs.isEmpty else {+ throw MusicPlaybackError.requestFailed("No song ids given to add to playlist \(playlistID).")+ }+ let body: [String: Any] = ["data": songIDs.map { ["id": $0, "type": "songs"] }]+ var urlRequest = URLRequest(+ url: Self.libraryPlaylistsURL.appendingPathComponent(playlistID).appendingPathComponent("tracks")+ )+ urlRequest.httpMethod = "POST"+ urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")+ urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: body)+ do {+ _ = try await Self.musicAPIResponse(urlRequest)+ } catch {+ throw Self.mapped(error)+ }+ }++ public func playlistEntries(playlistID: String, limit: Int) async throws -> [MusicPlaylistEntry] {+ try await ensureAuthorized()+ var components = URLComponents(+ url: Self.libraryPlaylistsURL.appendingPathComponent(playlistID).appendingPathComponent("tracks"),+ resolvingAgainstBaseURL: false+ )+ components?.queryItems = [URLQueryItem(name: "limit", value: String(max(1, min(limit, 100))))]+ guard let url = components?.url else {+ throw MusicPlaybackError.requestFailed("Could not build the playlist tracks URL for \(playlistID).")+ }+ let data: Data+ do {+ data = try await Self.musicAPIResponse(URLRequest(url: url)).data+ } catch let error as MusicDataRequest.Error where error.status == 404 {+ // An empty library playlist 404s on /tracks rather than returning an empty list.+ return []+ } catch {+ throw Self.mapped(error)+ }+ return Self.parsePlaylistEntries(from: data)+ }++ private static let libraryPlaylistsURL = URL(string: "https://api.music.apple.com/v1/me/library/playlists")!++ /// Both wire parsers are lenient on extra fields and strict on the ones they report — they parse+ /// the Apple Music API's documented `data[].attributes` shape.+ static func parsePlaylistSummaries(from data: Data) -> [MusicPlaylistSummary] {+ struct Wire: Decodable {+ struct Item: Decodable {+ struct Attributes: Decodable { var name: String? }+ var id: String+ var attributes: Attributes?+ }+ var data: [Item]+ }+ let items = (try? JSONDecoder().decode(Wire.self, from: data))?.data ?? []+ return items.map { MusicPlaylistSummary(id: $0.id, name: $0.attributes?.name ?? $0.id) }+ }++ static func parsePlaylistEntries(from data: Data) -> [MusicPlaylistEntry] {+ struct Wire: Decodable {+ struct Item: Decodable {+ struct Attributes: Decodable {+ var name: String?+ var artistName: String?+ }+ var attributes: Attributes?+ }+ var data: [Item]+ }+ let items = (try? JSONDecoder().decode(Wire.self, from: data))?.data ?? []+ return items.compactMap { item in+ guard let name = item.attributes?.name else { return nil }+ return MusicPlaylistEntry(title: name, artist: item.attributes?.artistName ?? "")+ }+ }++ /// Runs an Apple Music API request signed by MusicKit (developer + user tokens), keeping the+ /// HTTP status so an ambiguous write can be reported with its exact cause. nonisolated so the+ /// non-Sendable request machinery stays within one region (same rule as the player helpers).+ private nonisolated static func musicAPIResponse(_ urlRequest: URLRequest) async throws -> (data: Data, httpStatus: Int) {+ let response = try await MusicDataRequest(urlRequest: urlRequest).response()+ return (response.data, response.urlResponse.statusCode)+ }++ private nonisolated static func fetchLibraryPlaylists(limit: Int) async throws -> [MusicPlaylistSummary] {+ var request = MusicLibraryRequest<Playlist>()+ request.limit = limit+ let response = try await request.response()+ return response.items.map { MusicPlaylistSummary(id: $0.id.rawValue, name: $0.name) }+ }++ private nonisolated static func fetchLibraryPlaylist(id: String) async throws -> Playlist? {+ var request = MusicLibraryRequest<Playlist>()+ request.filter(matching: \.id, equalTo: MusicItemID(id))+ return try await request.response().items.first+ }++ // MARK: - Internals++ /// The player's async methods are nonisolated on a non-Sendable class, so a main-actor caller+ /// cannot await them on a stored reference without "sending" the player across the boundary.+ /// These helpers resolve `.shared` inside the nonisolated region, keeping the instance local.+ private nonisolated static func startPlayback() async throws {+ try await ApplicationMusicPlayer.shared.play()+ }++ private nonisolated static func advanceQueue(forward: Bool) async throws {+ if forward {+ try await ApplicationMusicPlayer.shared.skipToNextEntry()+ } else {+ try await ApplicationMusicPlayer.shared.skipToPreviousEntry()+ }+ }++ private nonisolated static func insertIntoQueue(_ item: some PlayableMusicItem, next: Bool) async throws {+ try await ApplicationMusicPlayer.shared.queue.insert(item, position: next ? .afterCurrentEntry : .tail)+ }++ private func ensureAuthorized() async throws {+ switch MusicAuthorization.currentStatus {+ case .authorized:+ return+ case .notDetermined:+ let status = await MusicAuthorization.request()+ guard status == .authorized else {+ throw MusicPlaybackError.notAuthorized(+ "Media & Apple Music access was not granted (status: \(status))."+ )+ }+ case .denied:+ throw MusicPlaybackError.notAuthorized(+ "Media & Apple Music access is denied for this app. Enable it in "+ + "System Settings → Privacy & Security → Media & Apple Music."+ )+ case .restricted:+ throw MusicPlaybackError.notAuthorized(+ "Media & Apple Music access is restricted on this Mac (parental controls or a profile)."+ )+ @unknown default:+ throw MusicPlaybackError.notAuthorized(+ "Media & Apple Music access is unavailable (status: \(MusicAuthorization.currentStatus))."+ )+ }+ }++ private func ensureSubscribed() async throws {+ let subscription: MusicSubscription+ do {+ subscription = try await MusicSubscription.current+ } catch {+ throw Self.mapped(error)+ }+ guard subscription.canPlayCatalogContent else {+ throw MusicPlaybackError.subscriptionRequired(+ "This Mac's Apple ID cannot play Apple Music catalog content — no active subscription, "+ + "or Music is not signed in."+ )+ }+ }++ private func firstCatalogItem<Item: MusicItem & Decodable>(+ _ request: MusicCatalogResourceRequest<Item>,+ id: String+ ) async throws -> Item {+ let response: MusicCatalogResourceResponse<Item>+ do {+ response = try await request.response()+ } catch {+ throw Self.mapped(error)+ }+ guard let item = response.items.first else {+ throw MusicPlaybackError.notFound("No Apple Music catalog item with id \(id).")+ }+ return item+ }++ private func currentSnapshot(positionAdvancing: Bool? = nil) -> MusicPlaybackSnapshot {+ MusicPlaybackSnapshot(+ status: Self.status(from: player.state.playbackStatus),+ title: player.queue.currentEntry?.title,+ artist: player.queue.currentEntry?.subtitle,+ positionSeconds: player.playbackTime,+ positionAdvancing: positionAdvancing,+ shuffleOn: player.state.shuffleMode.map { $0 == .songs },+ repeatSetting: Self.repeatSetting(from: player.state.repeatMode)+ )+ }++ private static func repeatSetting(from mode: MusicPlayer.RepeatMode?) -> MusicRepeatSetting? {+ guard let mode else { return nil }+ switch mode {+ case .none: return .off+ case .one: return .one+ case .all: return .all+ @unknown default: return nil+ }+ }++ /// Samples the position every ~0.7s until it advances or the tick budget runs out. Playback that+ /// is buffering reports position 0 for the first second or two, so a single early sample would+ /// misread a fine start as a failure.+ private func snapshotWithAdvancementEvidence(maxTicks: Int) async -> MusicPlaybackSnapshot {+ let initialPosition = player.playbackTime+ var lastPosition = initialPosition+ for _ in 0..<maxTicks {+ try? await Task.sleep(nanoseconds: 700_000_000)+ lastPosition = player.playbackTime+ if lastPosition > initialPosition {+ return currentSnapshot(positionAdvancing: true)+ }+ }+ return currentSnapshot(positionAdvancing: lastPosition > initialPosition)+ }++ private static func status(from playbackStatus: MusicPlayer.PlaybackStatus) -> MusicPlaybackSnapshot.Status {+ switch playbackStatus {+ case .playing: return .playing+ case .paused: return .paused+ case .stopped: return .stopped+ case .interrupted: return .interrupted+ case .seekingForward, .seekingBackward: return .seeking+ @unknown default: return .unknown+ }+ }++ /// Maps a MusicKit failure to the exact actionable cause. Matching is on typed error values;+ /// the token-error fallback inspects the error's own text only to classify a framework error+ /// string, never user input.+ private static func mapped(_ error: Error) -> MusicPlaybackError {+ if let error = error as? MusicPlaybackError {+ return error+ }+ if let apiError = error as? MusicDataRequest.Error {+ let detail = apiError.detailText.isEmpty ? apiError.title : apiError.detailText+ switch apiError.status {+ case 401, 403:+ return .notAuthorized(+ "Apple Music API rejected the request (HTTP \(apiError.status): \(detail)) — "+ + "the user token or library permission is missing."+ )+ case 404:+ return .notFound("Apple Music API found nothing at that id (HTTP 404: \(detail)).")+ default:+ return .requestFailed("Apple Music API error (HTTP \(apiError.status): \(detail)).")+ }+ }+ if let tokenError = error as? MusicTokenRequestError {+ switch tokenError {+ case .developerTokenRequestFailed:+ return .developerTokenUnavailable(+ "MusicKit could not get a developer token. The app must be signed with a real "+ + "development identity (not ad-hoc) and its bundle id must have the MusicKit "+ + "app service enabled in the Apple Developer portal."+ )+ case .userNotSignedIn:+ return .subscriptionRequired("No Apple ID is signed in for Apple Music on this Mac.")+ case .privacyAcknowledgementRequired:+ return .subscriptionRequired(+ "Apple Music needs its privacy prompt acknowledged — open the Music app once and accept it."+ )+ case .permissionDenied:+ return .notAuthorized(+ "Media & Apple Music access is denied for this app. Enable it in "+ + "System Settings → Privacy & Security → Media & Apple Music."+ )+ default:+ return .requestFailed("Apple Music token request failed: \(tokenError).")+ }+ }+ return .requestFailed("Apple Music request failed: \(error.localizedDescription)")+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/MusicPlaybackTools.swift b/apps/Donkey/Sources/DonkeyRuntime/MusicPlaybackTools.swiftnew file mode 100644index 00000000..89dc8af2--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/MusicPlaybackTools.swift@@ -0,0 +1,639 @@+import DonkeyContracts+import DonkeyHarness+import Foundation++/// Native music tools registered into a `HarnessToolRegistry`: catalog search, playback, transport,+/// and playback state — all through the platform music framework, never by launching, focusing,+/// scripting, or clicking the Music app. Playback results carry their own verification (the play+/// position sampled until it advances), so a successful `music.play` is completion evidence by+/// itself and the planner can `run.complete` without a separate observation step.+@MainActor+public final class MusicPlaybackToolProvider {+ public enum ToolName {+ public static let search = "music.search"+ public static let play = "music.play"+ public static let transport = "music.transport"+ public static let status = "music.status"+ public static let playlist = "music.playlist"+ }++ /// The `music.playlist` operations, as one typed source of truth. The descriptor's action+ /// schema, the read-only exemption metadata the duplicate-action guard reads, and the dispatch+ /// switch all derive from these cases — so renaming or adding an action updates every site at+ /// once instead of silently drifting a hand-kept "list,entries" string out of sync.+ enum PlaylistAction: String, CaseIterable {+ case list, create, add, entries++ /// Pure reads (verification, not side effects) the duplicate-action guard must never block.+ var isReadOnly: Bool {+ switch self {+ case .list, .entries: return true+ case .create, .add: return false+ }+ }++ /// Human-facing `a | b | c` list for schemas and error messages.+ static var schemaList: String { allCases.map(\.rawValue).joined(separator: " | ") }++ /// Comma-separated read-only action values for `readOnlyActionsMetadataKey`.+ static var readOnlyMetadataValue: String {+ allCases.filter(\.isReadOnly).map(\.rawValue).joined(separator: ",")+ }+ }++ private let service: any MusicPlaybackServicing++ public init(service: any MusicPlaybackServicing) {+ self.service = service+ }++ public static var descriptors: [HarnessToolDescriptor] {+ [+ HarnessToolDescriptor(+ name: ToolName.search,+ pluginID: "media.music",+ summary: "Search the Apple Music catalog (songs, albums, playlists, stations) and return playable hits with typed ids. Use only when the right item is ambiguous — music.play with a query already plays the top match. For several lookups (filling a playlist), put ALL the queries in ONE call separated by \" | \" — they run concurrently; never search one song per step.",+ inputSchema: [+ "query": "Plain words naming the music — no command phrases like \"play\". Several queries separated by \" | \" run concurrently in one call.",+ "limit": "Max results per kind (default 5; defaults to 1 per query for multi-query calls)."+ ],+ optionalInputKeys: ["limit"],+ outputSchema: ["hits": "kind:id — title (artist), in catalog relevance order."],+ safetyClass: .readOnly+ ),+ HarnessToolDescriptor(+ name: ToolName.play,+ pluginID: "media.music",+ summary: "Play Apple Music natively — THE way to start any music playback; never script or click the Music app. Give a plain-words query (plays the top match) or a kind+id from music.search. Success means playback was verified (position advancing) — complete the run on it. With enqueue, queues the item instead of interrupting what's playing.",+ inputSchema: [+ "query": "Plain words naming the music, e.g. \"blackpink\" or \"my heart will go on celine dion\".",+ "kind": "song | album | playlist | station — with id, plays that exact item; with query, prefers that kind.",+ "id": "Catalog id from music.search (requires kind).",+ "enqueue": "next | last — queue it instead of playing now (current song keeps playing). Stations can't be queued."+ ],+ optionalInputKeys: ["query", "kind", "id", "enqueue"],+ safetyClass: .reversible,+ verificationHints: ["success already includes verified playback (position advanced)"],+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ ),+ HarnessToolDescriptor(+ name: ToolName.transport,+ pluginID: "media.music",+ summary: "Control native music playback: pause, resume, stop, next, previous, fast-forward/rewind, seek, shuffle, repeat.",+ inputSchema: [+ "action": "pause | resume | stop | next | previous | forward | rewind | seek | shuffle | repeat",+ "seconds": "forward/rewind amount (default 15), or the seek target measured from the start of the song.",+ "mode": "shuffle: on | off — repeat: off | one | all."+ ],+ optionalInputKeys: ["seconds", "mode"],+ safetyClass: .reversible,+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ ),+ HarnessToolDescriptor(+ name: ToolName.status,+ pluginID: "media.music",+ summary: "Read native playback state: what's playing, position, and whether the position is advancing.",+ outputSchema: ["state": "status, title, artist, position, advancing"],+ safetyClass: .readOnly+ ),+ HarnessToolDescriptor(+ name: ToolName.playlist,+ pluginID: "media.music",+ summary: "Manage Apple Music library playlists natively: list them, create one, add catalog songs (ids from music.search), or read a playlist's entries. Play one via music.play kind=playlist id=<id>. Removing tracks and deleting playlists are NOT possible (no Apple API) — tell the user instead of attempting it.",+ inputSchema: [+ "action": PlaylistAction.schemaList,+ "name": "Playlist name (create).",+ "description": "Playlist description (create, optional).",+ "playlistID": "Library playlist id from action=list or create (add, entries).",+ "songIDs": "Comma-separated catalog song ids from music.search (add).",+ "limit": "Max items returned (list/entries, default 25)."+ ],+ optionalInputKeys: ["name", "description", "playlistID", "songIDs", "limit"],+ safetyClass: .reversible,+ metadata: [+ HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true",+ HarnessToolDescriptor.readOnlyActionsMetadataKey: PlaylistAction.readOnlyMetadataValue+ ]+ )+ ]+ }++ public func makeTools() -> [HarnessTool] {+ Self.descriptors.map { descriptor in+ HarnessTool(descriptor: descriptor) { context in+ await self.execute(context)+ }+ }+ }++ private func execute(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ switch context.call.name {+ case ToolName.search: return await search(context)+ case ToolName.play: return await play(context)+ case ToolName.transport: return await transport(context)+ case ToolName.status: return await status(context)+ case ToolName.playlist: return await playlist(context)+ default:+ return result(context, status: .unknownTool, summary: "Unknown music tool.", reason: "unknownMusicTool")+ }+ }++ /// Most queries a batched search needs in one call — enough for any playlist-sized lookup+ /// while bounding the fan-out against the catalog API.+ private static let maxBatchQueries = 15++ private func search(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard let queryInput = trimmed(context.call.input["query"]) else {+ return result(context, status: .invalidInput, summary: "music.search requires a query.", reason: "missingQuery")+ }+ let queries = queryInput.split(separator: "|")+ .map { $0.trimmingCharacters(in: .whitespaces) }+ .filter { !$0.isEmpty }+ guard let firstQuery = queries.first else {+ return result(context, status: .invalidInput, summary: "music.search requires a query.", reason: "missingQuery")+ }+ guard queries.count <= Self.maxBatchQueries else {+ return result(+ context,+ status: .invalidInput,+ summary: "music.search accepts at most \(Self.maxBatchQueries) queries per call — split the rest into a second call.",+ reason: "tooManyQueries"+ )+ }+ // Batched lookups default to the top hit per query — the playlist-filling case wants one id+ // per song, not five candidates each.+ let limit = context.call.input["limit"].flatMap(Int.init) ?? (queries.count > 1 ? 1 : 5)+ if queries.count == 1 {+ do {+ let hits = try await service.search(query: firstQuery, limit: limit)+ guard !hits.isEmpty else {+ return result(+ context,+ status: .failed,+ summary: "Apple Music catalog search found nothing for \"\(firstQuery)\".",+ reason: "noResults"+ )+ }+ let lines = hits.map { Self.line(for: $0) }+ return result(+ context,+ status: .succeeded,+ summary: "Found \(hits.count) playable item(s) for \"\(firstQuery)\":\n" + lines.joined(separator: "\n"),+ reason: "searched",+ facts: ["music.search.query": firstQuery, "music.search.hitCount": String(hits.count)]+ )+ } catch {+ return failure(context, error: error)+ }+ }+ // Several queries in one call run concurrently — one planning step finds every song for a+ // playlist instead of burning a full inference per lookup. The actor only serializes the+ // cheap setup; the catalog requests themselves overlap on the network. A query that finds+ // nothing or fails is reported inline so partial results stay usable.+ let outcomes = await withTaskGroup(of: (Int, Result<[MusicSearchHit], any Error>).self) { group in+ for (index, query) in queries.enumerated() {+ group.addTask {+ await (index, self.searchOutcome(query: query, limit: limit))+ }+ }+ var collected: [(Int, Result<[MusicSearchHit], any Error>)] = []+ for await outcome in group {+ collected.append(outcome)+ }+ return collected.sorted { $0.0 < $1.0 }+ }+ var sections: [String] = []+ var totalHits = 0+ var missed = 0+ for (index, outcome) in outcomes {+ let query = queries[index]+ switch outcome {+ case let .success(hits) where !hits.isEmpty:+ totalHits += hits.count+ sections.append("For \"\(query)\":\n" + hits.map { Self.line(for: $0) }.joined(separator: "\n"))+ case .success:+ missed += 1+ sections.append("For \"\(query)\": nothing found.")+ case let .failure(error):+ missed += 1+ let detail = (error as? MusicPlaybackError)?.description ?? String(describing: error)+ sections.append("For \"\(query)\": search failed — \(detail)")+ }+ }+ guard totalHits > 0 else {+ return result(+ context,+ status: .failed,+ summary: "Apple Music catalog search found nothing for any of the \(queries.count) queries:\n"+ + sections.joined(separator: "\n"),+ reason: "noResults"+ )+ }+ let missedNote = missed > 0 ? ", \(missed) with no result" : ""+ return result(+ context,+ status: .succeeded,+ summary: "Searched \(queries.count) queries concurrently (\(totalHits) hit(s)\(missedNote)):\n"+ + sections.joined(separator: "\n"),+ reason: "searched",+ facts: ["music.search.queryCount": String(queries.count), "music.search.hitCount": String(totalHits)]+ )+ }++ private func searchOutcome(query: String, limit: Int) async -> Result<[MusicSearchHit], any Error> {+ do {+ return .success(try await service.search(query: query, limit: limit))+ } catch {+ return .failure(error)+ }+ }++ private func play(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ let query = trimmed(context.call.input["query"])+ let id = trimmed(context.call.input["id"])+ let kind = trimmed(context.call.input["kind"]).flatMap(MusicSearchHit.Kind.init(rawValue:))+ if let enqueue = trimmed(context.call.input["enqueue"]) {+ return await self.enqueue(context, position: enqueue, query: query, kind: kind, id: id)+ }+ do {+ let played: MusicSearchHit+ let snapshot: MusicPlaybackSnapshot+ if let id, let kind {+ snapshot = try await service.play(kind: kind, id: id)+ played = MusicSearchHit(+ kind: kind,+ id: id,+ title: snapshot.title ?? id,+ artist: snapshot.artist ?? ""+ )+ } else if let query {+ (played, snapshot) = try await service.playTopMatch(query: query, preferredKind: kind)+ } else {+ return result(+ context,+ status: .invalidInput,+ summary: "music.play needs a query (plays the top match) or kind+id from music.search.",+ reason: "missingQueryOrID"+ )+ }+ return result(+ context,+ status: .succeeded,+ summary: "Playing \(played.kind.rawValue) \"\(played.title)\""+ + (played.artist.isEmpty ? "" : " by \(played.artist)")+ + " — verified, position advancing (\(Self.position(snapshot))).",+ reason: "played",+ facts: [+ "music.playing.kind": played.kind.rawValue,+ "music.playing.id": played.id,+ "music.playing.title": played.title,+ "music.playing.artist": played.artist+ ]+ )+ } catch {+ return failure(context, error: error)+ }+ }++ /// Resolves the target (exact kind+id, or the top match for a query) and queues it without+ /// interrupting playback. Stations are rejected up front — queueing one replaces the queue.+ private func enqueue(+ _ context: HarnessToolExecutionContext,+ position: String,+ query: String?,+ kind: MusicSearchHit.Kind?,+ id: String?+ ) async -> HarnessToolResult {+ guard position == "next" || position == "last" else {+ return result(+ context,+ status: .invalidInput,+ summary: "music.play enqueue must be next or last, not \"\(position)\".",+ reason: "unknownEnqueuePosition"+ )+ }+ do {+ let target: MusicSearchHit+ if let id, let kind {+ target = MusicSearchHit(kind: kind, id: id, title: id)+ } else if let query {+ let hits = try await service.search(query: query, limit: 10)+ guard let hit = MusicKitPlaybackService.topMatch(in: hits, preferredKind: kind) else {+ throw MusicPlaybackError.notFound(+ "Apple Music catalog search found nothing queueable for \"\(query)\"."+ )+ }+ target = hit+ } else {+ return result(+ context,+ status: .invalidInput,+ summary: "music.play with enqueue needs a query or kind+id from music.search.",+ reason: "missingQueryOrID"+ )+ }+ guard target.kind != .station else {+ return result(+ context,+ status: .invalidInput,+ summary: "Stations cannot be queued — a station replaces the queue. Play it with music.play instead.",+ reason: "stationNotQueueable"+ )+ }+ let snapshot = try await service.enqueue(kind: target.kind, id: target.id, next: position == "next")+ return result(+ context,+ status: .succeeded,+ summary: "Queued \(target.kind.rawValue) \"\(target.title)\""+ + (target.artist.isEmpty ? "" : " by \(target.artist)")+ + " to play \(position) — confirmed; now \(Self.describe(snapshot)).",+ reason: "queued",+ facts: ["music.queued.kind": target.kind.rawValue, "music.queued.id": target.id]+ )+ } catch {+ return failure(context, error: error)+ }+ }++ private func transport(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ let actions = "pause | resume | stop | next | previous | forward | rewind | seek | shuffle | repeat"+ guard let action = trimmed(context.call.input["action"]) else {+ return result(+ context,+ status: .invalidInput,+ summary: "music.transport requires an action: \(actions).",+ reason: "missingAction"+ )+ }+ let seconds = trimmed(context.call.input["seconds"]).flatMap(Double.init)+ let mode = trimmed(context.call.input["mode"])+ do {+ let snapshot: MusicPlaybackSnapshot+ switch action {+ case "pause": snapshot = try await service.pause()+ case "resume": snapshot = try await service.resume()+ case "stop": snapshot = try await service.stop()+ case "next": snapshot = try await service.skipToNext()+ case "previous": snapshot = try await service.skipToPrevious()+ case "forward": snapshot = try await service.seek(bySeconds: seconds ?? 15)+ case "rewind": snapshot = try await service.seek(bySeconds: -(seconds ?? 15))+ case "seek":+ guard let seconds else {+ return result(+ context,+ status: .invalidInput,+ summary: "music.transport action=seek requires seconds — the target position from the start of the song.",+ reason: "missingSeconds"+ )+ }+ snapshot = try await service.seek(toSeconds: seconds)+ case "shuffle":+ guard mode == "on" || mode == "off" else {+ return result(+ context,+ status: .invalidInput,+ summary: "music.transport action=shuffle requires mode: on | off.",+ reason: "missingMode"+ )+ }+ snapshot = try await service.setShuffle(mode == "on")+ case "repeat":+ guard let setting = mode.flatMap(MusicRepeatSetting.init(rawValue:)) else {+ return result(+ context,+ status: .invalidInput,+ summary: "music.transport action=repeat requires mode: off | one | all.",+ reason: "missingMode"+ )+ }+ snapshot = try await service.setRepeat(setting)+ default:+ return result(+ context,+ status: .invalidInput,+ summary: "Unknown music.transport action \"\(action)\" — use \(actions).",+ reason: "unknownAction"+ )+ }+ return result(+ context,+ status: .succeeded,+ summary: "Transport \(action) done — \(Self.describe(snapshot)).",+ reason: action+ )+ } catch {+ return failure(context, error: error)+ }+ }++ private func status(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ let snapshot = await service.status()+ return result(+ context,+ status: .succeeded,+ summary: "Playback state: \(Self.describe(snapshot)).",+ reason: "status",+ facts: ["music.status": snapshot.status.rawValue]+ )+ }++ private func playlist(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard let rawAction = trimmed(context.call.input["action"]) else {+ return result(+ context,+ status: .invalidInput,+ summary: "music.playlist requires an action: \(PlaylistAction.schemaList).",+ reason: "missingAction"+ )+ }+ guard let action = PlaylistAction(rawValue: rawAction) else {+ // remove/delete are real Apple-platform gaps (no API); anything else is a typo.+ if rawAction == "remove" || rawAction == "delete" {+ return result(+ context,+ status: .failed,+ summary: "Removing tracks or deleting playlists is not possible — Apple provides no API for it. "+ + "Tell the user to do that in the Music app; do not retry.",+ reason: "unsupportedByPlatform"+ )+ }+ return result(+ context,+ status: .invalidInput,+ summary: "Unknown music.playlist action \"\(rawAction)\" — use \(PlaylistAction.schemaList).",+ reason: "unknownAction"+ )+ }+ let limit = context.call.input["limit"].flatMap(Int.init) ?? 25+ do {+ switch action {+ case .list:+ let playlists = try await service.libraryPlaylists(limit: limit)+ guard !playlists.isEmpty else {+ return result(context, status: .succeeded, summary: "The music library has no playlists yet.", reason: "listed")+ }+ let lines = playlists.map { "\($0.id) — \($0.name)" }+ return result(+ context,+ status: .succeeded,+ summary: "Library playlists (\(playlists.count)):\n" + lines.joined(separator: "\n"),+ reason: "listed",+ facts: ["music.playlist.count": String(playlists.count)]+ )+ case .create:+ guard let name = trimmed(context.call.input["name"]) else {+ return result(context, status: .invalidInput, summary: "music.playlist action=create requires a name.", reason: "missingName")+ }+ let created = try await service.createPlaylist(+ name: name,+ description: trimmed(context.call.input["description"])+ )+ return result(+ context,+ status: .succeeded,+ summary: "Created playlist \"\(created.name)\" (id \(created.id)) — confirmed by the Apple Music API.",+ reason: "created",+ facts: ["music.playlist.created.id": created.id, "music.playlist.created.name": created.name]+ )+ case .add:+ guard let playlistID = trimmed(context.call.input["playlistID"]) else {+ return result(context, status: .invalidInput, summary: "music.playlist action=add requires a playlistID.", reason: "missingPlaylistID")+ }+ let songIDs = (context.call.input["songIDs"] ?? "")+ .split(separator: ",")+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter { !$0.isEmpty }+ guard !songIDs.isEmpty else {+ return result(+ context,+ status: .invalidInput,+ summary: "music.playlist action=add requires songIDs — comma-separated catalog song ids from music.search.",+ reason: "missingSongIDs"+ )+ }+ try await service.addToPlaylist(playlistID: playlistID, songIDs: songIDs)+ return result(+ context,+ status: .succeeded,+ summary: "Added \(songIDs.count) song(s) to playlist \(playlistID) — confirmed by the Apple Music API.",+ reason: "added",+ facts: ["music.playlist.added.count": String(songIDs.count)]+ )+ case .entries:+ guard let playlistID = trimmed(context.call.input["playlistID"]) else {+ return result(context, status: .invalidInput, summary: "music.playlist action=entries requires a playlistID.", reason: "missingPlaylistID")+ }+ let entries = try await service.playlistEntries(playlistID: playlistID, limit: limit)+ guard !entries.isEmpty else {+ return result(context, status: .succeeded, summary: "Playlist \(playlistID) is empty.", reason: "entries")+ }+ let lines = entries.map { $0.artist.isEmpty ? $0.title : "\($0.title) — \($0.artist)" }+ return result(+ context,+ status: .succeeded,+ summary: "Playlist \(playlistID) entries (\(entries.count)):\n" + lines.joined(separator: "\n"),+ reason: "entries"+ )+ }+ } catch {+ return failure(context, error: error)+ }+ }++ // MARK: - Formatting++ private static func line(for hit: MusicSearchHit) -> String {+ var line = "\(hit.kind.rawValue):\(hit.id) — \(hit.title)"+ if !hit.artist.isEmpty { line += " (\(hit.artist))" }+ if !hit.album.isEmpty { line += " [album: \(hit.album)]" }+ return line+ }++ private static func describe(_ snapshot: MusicPlaybackSnapshot) -> String {+ var parts = [snapshot.status.rawValue]+ if let title = snapshot.title, !title.isEmpty {+ let artist = snapshot.artist.flatMap { $0.isEmpty ? nil : " by \($0)" } ?? ""+ parts.append("\"\(title)\"\(artist)")+ }+ parts.append("at \(position(snapshot))")+ if let advancing = snapshot.positionAdvancing {+ parts.append(advancing ? "position advancing" : "position NOT advancing")+ }+ if let shuffleOn = snapshot.shuffleOn {+ parts.append("shuffle \(shuffleOn ? "on" : "off")")+ }+ if let repeatSetting = snapshot.repeatSetting {+ parts.append("repeat \(repeatSetting.rawValue)")+ }+ return parts.joined(separator: ", ")+ }++ private static func position(_ snapshot: MusicPlaybackSnapshot) -> String {+ String(format: "%.1fs", snapshot.positionSeconds)+ }++ /// Failure summaries carry the service's exact actionable cause (`MusicPlaybackError`+ /// descriptions name the missing permission, subscription, or signing requirement). Setup-class+ /// causes additionally carry a hard stop directive: no other tool in the run can fix a signing,+ /// consent, or subscription problem, and without the directive the planner drifts into+ /// AppleScript/GUI fallbacks the music doctrine forbids (observed: minutes of osascript attempts+ /// after a developer-token failure).+ private func failure(_ context: HarnessToolExecutionContext, error: Error) -> HarnessToolResult {+ let reason: String+ var isSetupProblem = false+ switch error as? MusicPlaybackError {+ case .notAuthorized:+ reason = "notAuthorized"+ isSetupProblem = true+ case .subscriptionRequired:+ reason = "subscriptionRequired"+ isSetupProblem = true+ case .developerTokenUnavailable:+ reason = "developerTokenUnavailable"+ isSetupProblem = true+ case .notFound: reason = "notFound"+ case .playbackDidNotStart: reason = "playbackDidNotStart"+ case .requestFailed, nil: reason = "requestFailed"+ }+ var summary = String(describing: error as? MusicPlaybackError ?? .requestFailed(error.localizedDescription))+ if isSetupProblem {+ summary += " STOP: this is a machine/account setup problem no tool in this run can fix. "+ + "Do NOT retry, and do NOT fall back to AppleScript, the Music app GUI, or a web "+ + "player. Tell the user this exact reason with conversation.respond, then run.failSafe."+ }+ return result(+ context,+ status: .failed,+ summary: summary,+ reason: reason+ )+ }++ private func result(+ _ context: HarnessToolExecutionContext,+ status: HarnessToolResultStatus,+ summary: String,+ reason: String,+ facts: [String: String] = [:]+ ) -> HarnessToolResult {+ var allFacts = facts+ if status == .succeeded {+ allFacts["lastAcceptedTool"] = context.call.name+ }+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: status,+ summary: summary,+ observations: HarnessObservationDelta(facts: allFacts),+ metadata: ["reason": reason, "source": "musickit"]+ )+ }++ private func trimmed(_ value: String?) -> String? {+ guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {+ return nil+ }+ return value+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music/SKILL.mdindex 9afbbfe3..2192fe0f 100644--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music/SKILL.md+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music/SKILL.md@@ -1,74 +1,66 @@# Musicid: music-description: Play music locally in Apple Music — never a web player — using the validated playback script first, then UI fallback only when needed.+description: Play and control Apple Music natively with the music.* tools — never the Music app GUI, AppleScript, or a web player.tags: media, music, playback, local-app-keywords: play, listen, music, song, track, tune, album, playlist, artist, band, audio, radio, pause, resume, skip, volume+keywords: play, listen, music, song, track, tune, album, playlist, artist, band, audio, radio, pause, resume, skip, volume, shuffle, repeat, queue, seek, rewindapps: Music, Apple Music, com.apple.Music-tools: skill_run, shell_exec, vision.capture, vision.click, web.search+tools: music.play, music.search, music.transport, music.status, music.playlist, shell_exec, web.search-Use this for any music playback request: "play baby don't cry", "play top 80s hits", "play the latest album from Taylor Swift", "play something by Coldplay", "play the song from Titanic", "play relaxing piano music", "pause the music", "turn it up", "what's playing?".+Use this for any music request: "play baby don't cry", "play top 80s hits", "play the latest album from Taylor Swift", "play something by Coldplay", "pause the music", "skip this", "what's playing?", "make me a workout playlist", "add this song to my mix".-Playback is low-risk and reversible: act directly, don't ask for confirmation. Always play locally in the Music app; never open YouTube, Spotify web, Apple Music web, or any browser player. Convert the request into the best Apple Music search query, then play it. Prefer the most likely mainstream interpretation. Do not over-explain — the user wants the music to start.+Playback is low-risk and reversible: act directly, don't ask for confirmation. Everything goes through the native music tools — never launch, focus, script, or click the Music app, and never open YouTube, Spotify web, Apple Music web, or any browser player. Do not over-explain — the user wants the music to start.-## Step 1: Classify the playback intent+## Step 1: Pick the tool-1. play_track — a specific song or likely song.-2. play_album — an album.-3. play_artist — an artist, or "something by" an artist.-4. play_playlist_or_station — hits, genre, mood, era, playlist, radio, "music like X".-5. transport_control — pause, resume, skip, previous, stop.-6. volume_control — louder, quieter, set volume.-7. now_playing — what is currently playing.--For transport_control, volume_control, and now_playing use direct AppleScript (commands below) — never run a search for these. For all play intents run the validated script first, unless the request needs external resolution.+1. Play anything (track, album, artist, playlist, genre, mood, era) → `music.play`.+2. Queue something to play next or after the queue ("play X next", "add X to the queue") → `music.play` with `enqueue`.+3. Transport (pause, resume, skip, previous, stop, fast-forward, rewind, seek, shuffle, repeat) → `music.transport`.+4. Volume → system volume via `shell_exec` (see below).+5. What's playing → `music.status`.+6. The user's own playlists (list, create, add songs, read contents) → `music.playlist`.## Step 2: Resolve the query when needed-Most requests pass straight to the script. Use web.search (or llm.generate for pure music knowledge) ONLY when information is missing or indirect: "latest album from X", "new song by X", "song from <movie/show/game>", "song that goes <lyrics>", "the viral song that says …", "top song by X", "the original version of …". Prefer reliable music sources (artist discographies, Wikipedia, Genius, MusicBrainz). Convert the result into a compact Apple Music query, include the artist when it reduces ambiguity, and don't mention the search step unless playback fails.--Examples: "play the latest album from Taylor Swift" → resolve the current latest album → `<that album> Taylor Swift`. "play the song from Titanic" → `My Heart Will Go On Celine Dion`. "the song that goes never gonna give you up" → `Never Gonna Give You Up Rick Astley`.--If resolution is uncertain, still make the best reasonable attempt.--## Step 3: Run the validated script--`skill_run` with `skillID=music`, `scriptID=scripts-play-media-by-search`, input = the normalized query in plain words. The script plays from the user's library when they own a match (instant); otherwise it resolves the most popular catalog match for the query, deep-links straight to that track in Music, starts playback, and verifies playback really started before claiming success.--Good inputs: `baby don't cry` · `my heart will go on celine dion` · `coldplay` · `top 80s hits` · `abbey road beatles`.-Bad inputs: `play baby don't cry` · `listen to coldplay` — no command phrases, and no "by" unless it is part of the actual title.+Most requests pass straight to `music.play`. Use web.search (or llm.generate for pure music knowledge) ONLY when information is missing or indirect: "latest album from X", "song from <movie/show/game>", "the song that goes <lyrics>". Convert the result into a compact query, include the artist when it reduces ambiguity, and don't mention the search step unless playback fails. If resolution is uncertain, still make the best reasonable attempt.-## Step 4: Read the script status (the source of truth)+## Step 3: Play-- `status=played` → playback started and was verified. Tell the user briefly what is playing, using `playedTitle`/`playedArtist`.-- `status=not_found` → read the script's `hint=` field; it states what happened and what to do next. Do NOT re-run the same query, and do not focus/open/activate Music — the script already left the right page on screen. If the hint suggests a visual click, do `vision.capture` then `vision.click` on the named song row, then verify playback. If it still won't start, say the likely reason plainly instead of retrying.-- Script error → don't loop. Try one improved query only if the error clearly indicates the query was malformed or too ambiguous; otherwise explain the failure briefly.+`music.play` with `query` = the music in plain words. It plays the user's own library first (owned or downloaded content, which needs no subscription), then falls back to the catalog, playing the top match and preferring songs. Steer it with `kind` when the request names a shape: `kind=album` for albums, `kind=playlist` or `kind=station` for hits/genre/mood/era requests. When the right item is ambiguous enough to matter, run `music.search` first and play an exact result with `kind`+`id`.-## Step 5: Verify playback+Good queries: `baby don't cry` · `my heart will go on celine dion` · `coldplay` · `top 80s hits` · `abbey road beatles`.+Bad queries: `play baby don't cry` · `listen to coldplay` — no command phrases, and no "by" unless it is part of the actual title.-Prefer the script's own verification. Manual check: `osascript -e 'tell application "Music" to player position'` — the position must ADVANCE over time. Never trust `player state` alone: Music can report "playing" while no real track is loaded. Never verify with screenshots.+## Step 4: Trust the tool's verification-## Direct AppleScript (transport / volume / now playing)+A successful `music.play` already verified playback — the play position was sampled until it advanced. Report what's playing and `run.complete`; do not re-verify with another tool. A failure summary states the exact cause (permission not granted, no Apple Music subscription, app signing/token problem, item unavailable). Relay that cause plainly, do not retry the same call, and never fall back to driving the Music app's GUI.-- Pause: `osascript -e 'tell application "Music" to pause'` · resume: `… to play` · toggle: `… to playpause`-- Next: `… to next track` · previous: `… to previous track`-- Volume: `… to set sound volume to 60`-- Now playing: `… to (get name of current track) & " — " & (get artist of current track)`-- Library-only play: `… to play (item 1 of (search library playlist 1 for "Coldplay"))`+## Transport, volume, now playing-AppleScript library search only sees music the user owns — it cannot search or play the streaming catalog. If a library search comes back empty, do not keep scripting; run the validated script. Avoid hand-building shell commands around titles with apostrophes or quotes — the script takes raw titles safely.+- Transport: `music.transport` with `action` = `pause` | `resume` | `stop` | `next` | `previous`.+- Fast-forward / rewind: `action=forward` or `action=rewind`, `seconds` optional (default 15). Jump to a spot: `action=seek` with `seconds` from the start ("skip the intro" → seek to ~30–60s, "start over" → seek to 0).+- Shuffle: `action=shuffle` `mode=on|off`. Repeat: `action=repeat` `mode=off|one|all`.+- Queue: "play X next" / "then play X" → `music.play` with `enqueue=next` (or `enqueue=last` for the end of the queue) — the current song keeps playing. Stations can't be queued, only played.+- Volume: set the Mac's output volume with `shell_exec` → `osascript -e 'set volume output volume 60'` (system volume, not the Music app — never script the Music app for anything).+- Now playing: `music.status`. Position advancing is the only trustworthy "it is playing" signal — never trust a status string alone.+- Boundary: the `music.*` tools control ONLY playback this assistant started. If `music.status` shows nothing playing but the user says music is audible, that audio was started manually in the Music app — say so and let the user control it there. Never script or click the Music app, even then.-## UI fallback in Music+## Playlists-Music's catalog UI is mostly NOT in the Accessibility tree: search-result tiles and album track rows don't appear in `ax.observe`, and `ax.click` fails there with "cannot be clicked" — do not retry AX clicks on catalog rows. Use `vision.capture` + `vision.click` instead, and only after the script's hint says the right page is on screen: capture → click the best visible song row or play button → verify player position advances → report. Perform one visual-click fallback only, unless the first click clearly selected the wrong element.+- "play my X playlist" → `music.playlist` action=list, match the name from the typed results, then `music.play` kind=playlist id=<that id>.+- "make me a playlist" → `music.playlist` action=create with a name; to fill it, find ALL the song ids in ONE `music.search` call with the queries separated by " | " (they run concurrently — never search one song per step), then one `music.playlist` action=add with the ids comma-separated in `songIDs`.+- "add this song to X" → the currently playing song's id is in the world model facts (`music.playing.id`) when this run started it; otherwise `music.search` for it. Then action=add.+- "what's in X" → action=entries.+- A successful create/add is confirmed by the Apple Music API — that is the evidence; report it and complete. Use action=entries only when the user asks what's inside.+- Removing tracks, deleting playlists, and renaming are NOT possible — Apple provides no API. Say so plainly and point the user to the Music app; never claim success and never fall back to the GUI.## Ambiguity-Pick the best likely match for ordinary ambiguity: "play hello" / "play baby don't cry" → the most popular likely match; "play drake" → owned Drake music or a popular catalog result; "play 80s music" → a popular 80s playlist/station. Ask only when the user explicitly wants to choose between versions, when interpretations are equally likely AND very different, or when the request isn't actually about music. Keep it short: "Which one did you mean: Adele, Lionel Richie, or another artist?"+Pick the best likely match for ordinary ambiguity: "play hello" → the most popular likely match; "play drake" → a popular Drake result; "play 80s music" → `kind=playlist` or `kind=station`. Ask only when the user explicitly wants to choose between versions, when interpretations are equally likely AND very different, or when the request isn't actually about music. Keep it short: "Which one did you mean: Adele, Lionel Richie, or another artist?"## Failure behavior-Never fail silently; never say playback started unless it was verified; never retry the same query repeatedly; never open a web player; never claim catalog playback is possible through direct AppleScript. State the likely reason plainly: Apple Music streaming not active on this Mac, item unavailable, Music exposed no clickable result, the query couldn't be resolved, or no library match and catalog playback failed. Example: "I found the result in Music, but playback did not start. This usually means Apple Music streaming is not active on this Mac or the item is unavailable."+Never fail silently; never say playback started unless the tool verified it; never retry the same query repeatedly; never open a web player; never drive the Music app GUI. The tool's failure summary names the exact blocker — pass it on, e.g. "I couldn't start playback: this Mac's Apple ID has no active Apple Music subscription."## Response stylediff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music/scripts/play-media-by-search.applescript b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music/scripts/play-media-by-search.applescriptdeleted file mode 100644index 6841984b..00000000--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music/scripts/play-media-by-search.applescript+++ /dev/null@@ -1,84 +0,0 @@-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---- 1) Local library first: instant, Automation-only, and a broad term (artist, mood word) plays--- whatever the user owns. `search` matches the query across title/artist/album.-tell application id "com.apple.Music"- activate- set matches to (search library playlist 1 for trimmedQuery)- if (count of matches) is not 0 then- set chosen to item 1 of matches- play chosen- delay 0.6- return "status=played" & linefeed & "source=local_library" & linefeed & "query=" & trimmedQuery & linefeed & "playedTitle=" & (name of chosen) & linefeed & "playedArtist=" & (artist of chosen)- end if-end tell---- 2) Not owned: resolve the MOST POPULAR catalog match via the iTunes Search API — one curl,--- no UI, popularity-ranked, and it gives back the exact track/album link. This replaces the--- old type-into-the-search-field dance, which could surface results but never start playback.-set resolvedTitle to ""-set resolvedArtist to ""-set resolvedURL to ""-try- -- limit=5, first result taken: asking the API for limit=1 invokes a different (worse)- -- ranking tier, e.g. returning a cover instead of the popular original.- set apiJSON to do shell script "curl -s -m 4 -G 'https://itunes.apple.com/search' --data-urlencode 'entity=song' --data-urlencode 'limit=5' --data-urlencode " & quoted form of ("term=" & trimmedQuery)- set firstResult to do shell script "printf '%s' " & quoted form of apiJSON & " | awk -F'\"wrapperType\"' '{print $2}'"- set resolvedTitle to do shell script "printf '%s' " & quoted form of firstResult & " | sed -nE 's/.*\"trackName\":\"([^\"]+)\".*/\\1/p' | head -1"- set resolvedArtist to do shell script "printf '%s' " & quoted form of firstResult & " | sed -nE 's/.*\"artistName\":\"([^\"]+)\".*/\\1/p' | head -1"- set resolvedURL to do shell script "printf '%s' " & quoted form of firstResult & " | sed -nE 's/.*\"trackViewUrl\":\"([^\"]+)\".*/\\1/p' | head -1"-end try--if resolvedURL does not start with "https://music.apple.com/" then set resolvedURL to ""--if resolvedURL is not "" then- -- music:// routes the link into the Music app natively (https:// would not navigate it)- -- and lands on the album page with the requested track highlighted.- set deepLink to "music" & (text 6 thru -1 of resolvedURL)- do shell script "open " & quoted form of deepLink- delay 1.5- tell application id "com.apple.Music"- play- -- Verify with the player position AND the track name, not `player state`: state can- -- report "playing" while nothing is loaded (position pinned at 0, e.g. with no Apple- -- Music subscription), and a bare `play` can resume a previously loaded track instead- -- of the requested one.- set verified to false- repeat 5 times- delay 0.7- try- if player state is playing and player position > 0.3 then- set nowName to ""- try- set nowName to name of current track- end try- if nowName is not "" and (nowName contains resolvedTitle or resolvedTitle contains nowName) then- set verified to true- exit repeat- end if- end if- end try- end repeat- if verified then- set playedTitle to resolvedTitle- set playedArtist to resolvedArtist- try- set playedTitle to name of current track- set playedArtist to artist of current track- end try- return "status=played" & linefeed & "source=streaming" & linefeed & "query=" & trimmedQuery & linefeed & "playedTitle=" & playedTitle & linefeed & "playedArtist=" & playedArtist- end if- end tell- -- The exact track's album page is on screen but playback would not start from script-level- -- `play`. A real click on the song row (the vision agent) is the remaining move; if even that- -- does not play, it's a Music account/subscription problem the user must fix — say so.- return "status=not_found" & linefeed & "query=" & trimmedQuery & linefeed & "resolvedTitle=" & resolvedTitle & linefeed & "resolvedArtist=" & resolvedArtist & linefeed & "hint=The track's album page is open in Music but scripted playback did not start. Vision-click the song row to play it. If playback still does not start, ask the user to check Music's sign-in / Apple Music subscription — do not keep retrying." & linefeed & "escalate.app=Music" & linefeed & "escalate.goal=Double-click the song row " & resolvedTitle & " on the album page now on screen, then verify player position advances"-end if---- 3) Nothing owned and the catalog lookup failed (offline or no API match): report honestly.-return "status=not_found" & linefeed & "query=" & trimmedQuery & linefeed & "hint=No local library match and the catalog lookup returned nothing. Ask the user or try a different query wording." & linefeed & "escalate.app=Music" & linefeed & "escalate.goal=Search Music for " & trimmedQuery & " and play the top song result"diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppSkillCommandTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppSkillCommandTests.swiftindex d14f6ecf..6cc4b9cc 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AppSkillCommandTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AppSkillCommandTests.swift@@ -72,16 +72,16 @@ struct AppSkillCommandTests {@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.+ func musicSkillRoutesToNativePlaybackTools() async {+ // The music skill is discovered like any other app skill (its `apps:` frontmatter, no+ // hardcoded list). It ships no scripts — playback is owned by the native music.* tools —+ // and its playbook must say so.for key in ["Music", "Apple Music", "com.apple.Music"] {let result = await lookup(key)#expect(result?.metadata["found"] == "true")#expect(result?.metadata["skillID"] == "music")- #expect(result?.metadata["scriptIDs"]?.contains("scripts-play-media-by-search") == true)- #expect(result?.summary.contains("skill_run") == true)+ #expect(result?.metadata["scriptIDs"]?.isEmpty != false)+ #expect(result?.summary.contains("music.play") == true)}}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swiftindex 39976241..875f2105 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift@@ -10,13 +10,13 @@ struct HarnessStepPromptTests {}/// The installed-skill catalog must reach the planner prompt verbatim, with routing instructions —- /// this is what lets the planner run a validated `skill_run` script for "play music"/"save a note"+ /// this is what lets the planner route "save a note"/"play music" to a skill's documented tools/// instead of improvising osascript when no GUI app is the drive target (the loop the user hit).@Testfunc includesSkillCatalogAndRoutingInstruction() {- let catalog = " - music — Play music locally in Apple Music · apps: Music · skill_run: scripts-play-media-by-search (Play Media By Search)"+ let catalog = " - notes — Capture notes by script · apps: Notes · skill_run: scripts-save-note (Save Note)"let prompt = DonkeyPrompts.harnessStep(- task: task(goal: "play some coldplay"),+ task: task(goal: "note this down"),descriptors: [],appName: "iTerm2",appGuidance: nil,@@ -25,7 +25,7 @@ struct HarnessStepPromptTests {skillCatalog: catalog)#expect(prompt.contains("authoritative playbooks for these apps/domains"))- #expect(prompt.contains("scripts-play-media-by-search"))+ #expect(prompt.contains("scripts-save-note"))#expect(prompt.contains("skill_run"))}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaybackToolsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaybackToolsTests.swiftnew file mode 100644index 00000000..d18cf6b4--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaybackToolsTests.swift@@ -0,0 +1,631 @@+import DonkeyContracts+import DonkeyHarness+import Foundation+import Testing+@testable import DonkeyRuntime++@Suite+@MainActor+struct MusicPlaybackToolsTests {+ @Test+ func playByQueryReportsVerifiedPlaybackWithEvidence() async {+ let service = FakeMusicService()+ service.searchHits = [+ MusicSearchHit(kind: .song, id: "123", title: "JUMP", artist: "BLACKPINK", album: "JUMP")+ ]+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(provider, tool: MusicPlaybackToolProvider.ToolName.play, input: ["query": "blackpink"])++ #expect(result.status == .succeeded)+ #expect(result.summary.contains("JUMP"))+ #expect(result.summary.contains("BLACKPINK"))+ #expect(result.summary.contains("position advancing"))+ #expect(result.observations.facts["music.playing.title"] == "JUMP")+ #expect(service.playedItems.map(\.id) == ["123"])+ }++ @Test+ func playByKindAndIDSkipsSearch() async {+ let service = FakeMusicService()+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.play,+ input: ["kind": "album", "id": "456"]+ )++ #expect(result.status == .succeeded)+ #expect(service.playedItems.map(\.id) == ["456"])+ #expect(service.searchQueries.isEmpty)+ }++ @Test+ func playWithoutQueryOrIDIsInvalidInput() async {+ let provider = MusicPlaybackToolProvider(service: FakeMusicService())++ let result = await run(provider, tool: MusicPlaybackToolProvider.ToolName.play, input: [:])++ #expect(result.status == .invalidInput)+ }++ @Test+ func playFailureSurfacesTheExactActionableCause() async {+ let service = FakeMusicService()+ service.playError = .developerTokenUnavailable(+ "MusicKit could not get a developer token. The app must be signed with a real "+ + "development identity (not ad-hoc) and its bundle id must have the MusicKit "+ + "app service enabled in the Apple Developer portal."+ )+ service.searchHits = [MusicSearchHit(kind: .song, id: "123", title: "JUMP", artist: "BLACKPINK")]+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(provider, tool: MusicPlaybackToolProvider.ToolName.play, input: ["query": "blackpink"])++ #expect(result.status == .failed)+ #expect(result.metadata["reason"] == "developerTokenUnavailable")+ #expect(result.summary.contains("developer token"))+ #expect(result.summary.contains("MusicKit app service"))+ }++ @Test+ func setupClassFailuresCarryAHardStopDirective() async {+ // A signing/consent/subscription failure cannot be fixed by any tool in the run. Without an+ // imperative right in the result, the planner drifts into AppleScript/GUI fallbacks the+ // doctrine forbids (observed live: minutes of osascript attempts after a token failure).+ let causes: [MusicPlaybackError] = [+ .developerTokenUnavailable("no token"),+ .notAuthorized("denied"),+ .subscriptionRequired("no subscription")+ ]+ for cause in causes {+ let service = FakeMusicService()+ service.playError = cause+ service.searchHits = [MusicSearchHit(kind: .song, id: "1", title: "JUMP")]+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(provider, tool: MusicPlaybackToolProvider.ToolName.play, input: ["query": "blackpink"])++ #expect(result.status == .failed)+ #expect(result.summary.contains("Do NOT retry"), "missing stop directive for \(cause)")+ #expect(result.summary.contains("run.failSafe"))+ }++ // A transient/not-found failure must NOT carry the stop directive — a better query is a+ // legitimate next step there.+ let service = FakeMusicService()+ service.playError = .notFound("nothing for that query")+ service.searchHits = [MusicSearchHit(kind: .song, id: "1", title: "JUMP")]+ let provider = MusicPlaybackToolProvider(service: service)+ let result = await run(provider, tool: MusicPlaybackToolProvider.ToolName.play, input: ["query": "blackpink"])+ #expect(!result.summary.contains("Do NOT retry"))+ }++ @Test+ func searchListsTypedHits() async {+ let service = FakeMusicService()+ service.searchHits = [+ MusicSearchHit(kind: .song, id: "1", title: "JUMP", artist: "BLACKPINK", album: "JUMP"),+ MusicSearchHit(kind: .album, id: "2", title: "BORN PINK", artist: "BLACKPINK")+ ]+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(provider, tool: MusicPlaybackToolProvider.ToolName.search, input: ["query": "blackpink"])++ #expect(result.status == .succeeded)+ #expect(result.summary.contains("song:1 — JUMP (BLACKPINK)"))+ #expect(result.summary.contains("album:2 — BORN PINK (BLACKPINK)"))+ }++ @Test+ func transportRejectsUnknownAction() async {+ let provider = MusicPlaybackToolProvider(service: FakeMusicService())++ let result = await run(provider, tool: MusicPlaybackToolProvider.ToolName.transport, input: ["action": "louder"])++ #expect(result.status == .invalidInput)+ }++ @Test+ func transportPauseReportsResultingState() async {+ let service = FakeMusicService()+ service.snapshot = MusicPlaybackSnapshot(status: .paused, title: "JUMP", artist: "BLACKPINK", positionSeconds: 12.3)+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(provider, tool: MusicPlaybackToolProvider.ToolName.transport, input: ["action": "pause"])++ #expect(result.status == .succeeded)+ #expect(service.transportActions == ["pause"])+ #expect(result.summary.contains("paused"))+ #expect(result.summary.contains("12.3s"))+ }++ @Test+ func transportForwardAndRewindDefaultTo15Seconds() async {+ let service = FakeMusicService()+ let provider = MusicPlaybackToolProvider(service: service)++ _ = await run(provider, tool: MusicPlaybackToolProvider.ToolName.transport, input: ["action": "forward"])+ _ = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.transport,+ input: ["action": "rewind", "seconds": "30"]+ )++ #expect(service.transportActions == ["seek(by:15.0)", "seek(by:-30.0)"])+ }++ @Test+ func transportSeekRequiresSeconds() async {+ let service = FakeMusicService()+ let provider = MusicPlaybackToolProvider(service: service)++ let missing = await run(provider, tool: MusicPlaybackToolProvider.ToolName.transport, input: ["action": "seek"])+ #expect(missing.status == .invalidInput)++ let result = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.transport,+ input: ["action": "seek", "seconds": "90"]+ )+ #expect(result.status == .succeeded)+ #expect(service.transportActions == ["seek(to:90.0)"])+ }++ @Test+ func transportShuffleAndRepeatSetModesAndReportState() async {+ let service = FakeMusicService()+ service.snapshot = MusicPlaybackSnapshot(+ status: .playing, positionSeconds: 5.0, shuffleOn: true, repeatSetting: .all+ )+ let provider = MusicPlaybackToolProvider(service: service)++ let shuffle = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.transport,+ input: ["action": "shuffle", "mode": "on"]+ )+ let repeatAll = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.transport,+ input: ["action": "repeat", "mode": "all"]+ )++ #expect(service.transportActions == ["shuffle(on)", "repeat(all)"])+ #expect(shuffle.summary.contains("shuffle on"))+ #expect(repeatAll.summary.contains("repeat all"))++ let badMode = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.transport,+ input: ["action": "repeat", "mode": "twice"]+ )+ #expect(badMode.status == .invalidInput)+ }++ @Test+ func playWithEnqueueQueuesTheTopMatchWithoutInterrupting() async {+ let service = FakeMusicService()+ service.searchHits = [+ MusicSearchHit(kind: .song, id: "123", title: "JUMP", artist: "BLACKPINK")+ ]+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.play,+ input: ["query": "blackpink jump", "enqueue": "next"]+ )++ #expect(result.status == .succeeded)+ #expect(service.playedItems.isEmpty)+ #expect(service.enqueuedItems.map(\.id) == ["123"])+ #expect(service.enqueuedItems.first?.next == true)+ #expect(result.summary.contains("Queued song \"JUMP\""))+ #expect(result.observations.facts["music.queued.id"] == "123")+ }++ @Test+ func enqueueRejectsStationsAndUnknownPositions() async {+ let service = FakeMusicService()+ service.searchHits = [MusicSearchHit(kind: .station, id: "st.1", title: "BLACKPINK Radio")]+ let provider = MusicPlaybackToolProvider(service: service)++ let station = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.play,+ input: ["query": "blackpink radio", "kind": "station", "enqueue": "last"]+ )+ #expect(station.status == .invalidInput)+ #expect(station.summary.contains("Stations cannot be queued"))++ let badPosition = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.play,+ input: ["query": "blackpink", "enqueue": "soon"]+ )+ #expect(badPosition.status == .invalidInput)+ #expect(service.enqueuedItems.isEmpty)+ }++ @Test+ func statusReportsAdvancementEvidence() async {+ let service = FakeMusicService()+ service.snapshot = MusicPlaybackSnapshot(+ status: .playing, title: "JUMP", artist: "BLACKPINK", positionSeconds: 5.0, positionAdvancing: true+ )+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(provider, tool: MusicPlaybackToolProvider.ToolName.status, input: [:])++ #expect(result.status == .succeeded)+ #expect(result.summary.contains("position advancing"))+ #expect(result.observations.facts["music.status"] == "playing")+ }++ @Test+ func playDescriptorMarksItsResultAsEvidence() {+ let play = MusicPlaybackToolProvider.descriptors.first { $0.name == MusicPlaybackToolProvider.ToolName.play }+ #expect(play?.metadata[HarnessToolDescriptor.resultIsEvidenceMetadataKey] == "true")+ }++ @Test+ func playlistReadOnlyMetadataDerivesFromTheDispatchedActions() {+ // The duplicate-action guard's read-only exemption must stay in lockstep with the actual+ // playlist actions: list/entries are pure reads, create/add mutate. Deriving the metadata+ // from PlaylistAction (the same enum the dispatch switch consumes) makes a rename update+ // both sites at once instead of drifting a hand-kept string out of sync.+ let playlist = MusicPlaybackToolProvider.descriptors.first { $0.name == MusicPlaybackToolProvider.ToolName.playlist }+ let declared = playlist?.metadata[HarnessToolDescriptor.readOnlyActionsMetadataKey]+ #expect(declared == "list,entries")++ let exempt = Set(declared?.split(separator: ",").map(String.init) ?? [])+ for action in MusicPlaybackToolProvider.PlaylistAction.allCases {+ #expect(exempt.contains(action.rawValue) == action.isReadOnly)+ }+ }++ @Test+ func topMatchPrefersRequestedKindThenSongFirstOrder() {+ let hits = [+ MusicSearchHit(kind: .playlist, id: "p", title: "80s Hits"),+ MusicSearchHit(kind: .song, id: "s", title: "Some Song"),+ MusicSearchHit(kind: .album, id: "a", title: "Some Album")+ ]++ #expect(MusicKitPlaybackService.topMatch(in: hits, preferredKind: .playlist)?.id == "p")+ #expect(MusicKitPlaybackService.topMatch(in: hits, preferredKind: nil)?.id == "s")+ #expect(MusicKitPlaybackService.topMatch(in: [], preferredKind: nil) == nil)+ }++ @Test+ func searchRunsPipeSeparatedQueriesConcurrentlyInOneCall() async {+ // Filling a playlist must cost one planning step, not one per song: a pipe-separated query+ // fans out concurrently and reports one section per query, including the misses, so partial+ // results stay usable.+ let service = FakeMusicService()+ service.hitsByQuery = [+ "Yellow Coldplay": [MusicSearchHit(kind: .song, id: "111", title: "Yellow", artist: "Coldplay")],+ "Say My Name Destiny's Child": [MusicSearchHit(kind: .song, id: "222", title: "Say My Name", artist: "Destiny's Child")],+ "No Such Song Nobody": []+ ]+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.search,+ input: ["query": "Yellow Coldplay | Say My Name Destiny's Child | No Such Song Nobody"]+ )++ #expect(result.status == .succeeded)+ #expect(Set(service.searchQueries) == ["Yellow Coldplay", "Say My Name Destiny's Child", "No Such Song Nobody"])+ #expect(result.summary.contains("Searched 3 queries concurrently"))+ #expect(result.summary.contains("song:111"))+ #expect(result.summary.contains("song:222"))+ #expect(result.summary.contains("For \"No Such Song Nobody\": nothing found."))+ #expect(result.observations.facts["music.search.queryCount"] == "3")+ #expect(result.observations.facts["music.search.hitCount"] == "2")+ }++ @Test+ func playlistListShowsIDsAndNames() async {+ let service = FakeMusicService()+ service.playlists = [+ MusicPlaylistSummary(id: "p.111", name: "Workout"),+ MusicPlaylistSummary(id: "p.222", name: "Chill")+ ]+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(provider, tool: MusicPlaybackToolProvider.ToolName.playlist, input: ["action": "list"])++ #expect(result.status == .succeeded)+ #expect(result.summary.contains("p.111 — Workout"))+ #expect(result.summary.contains("p.222 — Chill"))+ }++ @Test+ func playlistCreateReportsTheNewIDWithAPIConfirmation() async {+ let service = FakeMusicService()+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.playlist,+ input: ["action": "create", "name": "Blackpink Mix", "description": "by Donkey"]+ )++ #expect(result.status == .succeeded)+ #expect(service.createdPlaylists.map(\.name) == ["Blackpink Mix"])+ #expect(service.createdPlaylists.first?.description == "by Donkey")+ #expect(result.summary.contains("confirmed by the Apple Music API"))+ #expect(result.observations.facts["music.playlist.created.id"] == "p.new")+ }++ @Test+ func playlistCreateFailureDetailNamesStatusBodyAndVerificationResult() {+ let emptyBody = MusicKitPlaybackService.playlistCreateFailureDetail(+ name: "Best of 2000", httpStatus: 204, body: Data()+ )+ #expect(emptyBody.contains("HTTP 204"))+ #expect(emptyBody.contains("an empty body"))+ #expect(emptyBody.contains("found no playlist named \"Best of 2000\""))+ #expect(emptyBody.contains("Do not retry the same call"))++ let withBody = MusicKitPlaybackService.playlistCreateFailureDetail(+ name: "Best of 2000", httpStatus: 400, body: Data(#"{"errors":[{"title":"Invalid"}]}"#.utf8)+ )+ #expect(withBody.contains("HTTP 400"))+ #expect(withBody.contains(#"{"errors":[{"title":"Invalid"}]}"#))+ #expect(!withBody.contains("an empty body"))+ }++ @Test+ func playlistCreateFailureSurfacesTheExactCauseToThePlanner() async {+ // The live loop: create kept failing with an empty, cause-less message and the planner+ // plausibly retried variants for minutes. The failure the tool relays must carry the HTTP+ // status and the do-not-retry directive verbatim.+ let service = FakeMusicService()+ service.createError = .requestFailed(+ MusicKitPlaybackService.playlistCreateFailureDetail(name: "Best of 2000", httpStatus: 204, body: Data())+ )+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.playlist,+ input: ["action": "create", "name": "Best of 2000"]+ )++ #expect(result.status == .failed)+ #expect(result.metadata["reason"] == "requestFailed")+ #expect(result.summary.contains("HTTP 204"))+ #expect(result.summary.contains("Do not retry the same call"))+ #expect(service.createdPlaylists.isEmpty)+ }++ @Test+ func playlistAddParsesCommaSeparatedSongIDs() async {+ let service = FakeMusicService()+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.playlist,+ input: ["action": "add", "playlistID": "p.111", "songIDs": "123, 456 ,789"]+ )++ #expect(result.status == .succeeded)+ #expect(service.addedSongs.count == 1)+ #expect(service.addedSongs.first?.playlistID == "p.111")+ #expect(service.addedSongs.first?.songIDs == ["123", "456", "789"])+ #expect(result.summary.contains("Added 3 song(s)"))+ }++ @Test+ func playlistAddWithoutSongIDsIsInvalidInput() async {+ let provider = MusicPlaybackToolProvider(service: FakeMusicService())++ let result = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.playlist,+ input: ["action": "add", "playlistID": "p.111"]+ )++ #expect(result.status == .invalidInput)+ }++ @Test+ func playlistRemoveIsHonestlyUnsupported() async {+ // Apple ships no API for removing tracks or deleting playlists. The tool must say so+ // plainly instead of failing generically or pretending.+ let provider = MusicPlaybackToolProvider(service: FakeMusicService())++ let result = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.playlist,+ input: ["action": "remove", "playlistID": "p.111"]+ )++ #expect(result.status == .failed)+ #expect(result.metadata["reason"] == "unsupportedByPlatform")+ #expect(result.summary.contains("no API"))+ }++ @Test+ func playlistEntriesListsTitlesAndArtists() async {+ let service = FakeMusicService()+ service.entries = [+ MusicPlaylistEntry(title: "JUMP", artist: "BLACKPINK"),+ MusicPlaylistEntry(title: "Pink Venom", artist: "BLACKPINK")+ ]+ let provider = MusicPlaybackToolProvider(service: service)++ let result = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.playlist,+ input: ["action": "entries", "playlistID": "p.111"]+ )++ #expect(result.status == .succeeded)+ #expect(result.summary.contains("JUMP — BLACKPINK"))+ #expect(result.summary.contains("Pink Venom — BLACKPINK"))+ }++ @Test+ func playlistWireParsersReadTheAppleMusicAPIShape() {+ let createResponse = Data("""+ {"data":[{"id":"p.abc","type":"library-playlists","attributes":{"name":"Blackpink Mix"}}]}+ """.utf8)+ let summaries = MusicKitPlaybackService.parsePlaylistSummaries(from: createResponse)+ #expect(summaries == [MusicPlaylistSummary(id: "p.abc", name: "Blackpink Mix")])++ let tracksResponse = Data("""+ {"data":[+ {"id":"i.1","attributes":{"name":"JUMP","artistName":"BLACKPINK"}},+ {"id":"i.2","attributes":{"name":"Pink Venom","artistName":"BLACKPINK"}}+ ]}+ """.utf8)+ let entries = MusicKitPlaybackService.parsePlaylistEntries(from: tracksResponse)+ #expect(entries == [+ MusicPlaylistEntry(title: "JUMP", artist: "BLACKPINK"),+ MusicPlaylistEntry(title: "Pink Venom", artist: "BLACKPINK")+ ])++ #expect(MusicKitPlaybackService.parsePlaylistSummaries(from: Data("not json".utf8)).isEmpty)+ }++ // MARK: - Helpers++ private func run(+ _ provider: MusicPlaybackToolProvider,+ tool: String,+ input: [String: String]+ ) async -> HarnessToolResult {+ let tools = provider.makeTools()+ let harnessTool = tools.first { $0.descriptor.name == tool }!+ let context = HarnessToolExecutionContext(+ taskID: "task-1",+ call: HarnessToolCall(name: tool, input: input),+ descriptor: harnessTool.descriptor,+ worldModel: HarnessWorldModel(),+ grantedPermissions: []+ )+ return await harnessTool.execute(context)+ }+}++@MainActor+private final class FakeMusicService: MusicPlaybackServicing {+ var searchHits: [MusicSearchHit] = []+ /// Per-query results for batched-search tests; falls back to `searchHits` when a query is absent.+ var hitsByQuery: [String: [MusicSearchHit]] = [:]+ var snapshot = MusicPlaybackSnapshot(status: .playing, positionSeconds: 1.4, positionAdvancing: true)+ var playError: MusicPlaybackError?++ private(set) var searchQueries: [String] = []+ private(set) var playedItems: [(kind: MusicSearchHit.Kind, id: String)] = []+ private(set) var transportActions: [String] = []+ private(set) var enqueuedItems: [(kind: MusicSearchHit.Kind, id: String, next: Bool)] = []++ func search(query: String, limit: Int) async throws -> [MusicSearchHit] {+ searchQueries.append(query)+ return hitsByQuery[query] ?? searchHits+ }++ func play(kind: MusicSearchHit.Kind, id: String) async throws -> MusicPlaybackSnapshot {+ if let playError { throw playError }+ playedItems.append((kind, id))+ return snapshot+ }++ func playTopMatch(query: String, preferredKind: MusicSearchHit.Kind?) async throws+ -> (hit: MusicSearchHit, snapshot: MusicPlaybackSnapshot) {+ searchQueries.append(query)+ if let playError { throw playError }+ guard let hit = MusicKitPlaybackService.topMatch(in: searchHits, preferredKind: preferredKind) else {+ throw MusicPlaybackError.notFound("nothing for \(query)")+ }+ playedItems.append((hit.kind, hit.id))+ return (hit, snapshot)+ }++ func pause() async throws -> MusicPlaybackSnapshot {+ transportActions.append("pause")+ return snapshot+ }++ func resume() async throws -> MusicPlaybackSnapshot {+ transportActions.append("resume")+ return snapshot+ }++ func stop() async throws -> MusicPlaybackSnapshot {+ transportActions.append("stop")+ return snapshot+ }++ func skipToNext() async throws -> MusicPlaybackSnapshot {+ transportActions.append("next")+ return snapshot+ }++ func skipToPrevious() async throws -> MusicPlaybackSnapshot {+ transportActions.append("previous")+ return snapshot+ }++ func enqueue(kind: MusicSearchHit.Kind, id: String, next: Bool) async throws -> MusicPlaybackSnapshot {+ if let playError { throw playError }+ enqueuedItems.append((kind, id, next))+ return snapshot+ }++ func seek(toSeconds: Double) async throws -> MusicPlaybackSnapshot {+ transportActions.append("seek(to:\(toSeconds))")+ return snapshot+ }++ func seek(bySeconds: Double) async throws -> MusicPlaybackSnapshot {+ transportActions.append("seek(by:\(bySeconds))")+ return snapshot+ }++ func setShuffle(_ enabled: Bool) async throws -> MusicPlaybackSnapshot {+ transportActions.append("shuffle(\(enabled ? "on" : "off"))")+ return snapshot+ }++ func setRepeat(_ setting: MusicRepeatSetting) async throws -> MusicPlaybackSnapshot {+ transportActions.append("repeat(\(setting.rawValue))")+ return snapshot+ }++ func status() async -> MusicPlaybackSnapshot {+ snapshot+ }++ var playlists: [MusicPlaylistSummary] = []+ var entries: [MusicPlaylistEntry] = []+ var createError: MusicPlaybackError?+ private(set) var createdPlaylists: [(name: String, description: String?)] = []+ private(set) var addedSongs: [(playlistID: String, songIDs: [String])] = []++ func libraryPlaylists(limit: Int) async throws -> [MusicPlaylistSummary] {+ playlists+ }++ func createPlaylist(name: String, description: String?) async throws -> MusicPlaylistSummary {+ if let createError { throw createError }+ createdPlaylists.append((name, description))+ return MusicPlaylistSummary(id: "p.new", name: name)+ }++ func addToPlaylist(playlistID: String, songIDs: [String]) async throws {+ addedSongs.append((playlistID, songIDs))+ }++ func playlistEntries(playlistID: String, limit: Int) async throws -> [MusicPlaylistEntry] {+ entries+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaylistLiveE2ETests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaylistLiveE2ETests.swiftnew file mode 100644index 00000000..c01051ea--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaylistLiveE2ETests.swift@@ -0,0 +1,178 @@+import DonkeyContracts+import DonkeyHarness+import DonkeyRuntime+import Foundation+import Testing++/// LIVE end-to-end run of "Create a playlist of the 10 best songs from 2000" — the real harness+/// runtime, the real tool registry, the real MusicKit-backed music tools against the real Apple+/// Music API, and the real thread transcript. The one substituted piece is the hosted LLM planner:+/// a scripted planner issues exactly the calls the music skill prescribes (search each song →+/// create → add → entries → complete), so the run is deterministic and needs no backend login.+///+/// Opt-in via `DONKEY_LIVE_MUSIC_E2E=1` because it:+/// - needs Media & Apple Music consent for the test runner and an Apple Music subscription,+/// - CREATES A REAL PLAYLIST in the signed-in library, and Apple provides no delete API — clean+/// up by hand in the Music app afterwards (the name carries a timestamp to spot it).+///+/// Run: `DONKEY_LIVE_MUSIC_E2E=1 DEVELOPER_DIR=/Applications/Xcode.app swift test --filter MusicPlaylistLiveE2ETests`+@Suite(.enabled(if: ProcessInfo.processInfo.environment["DONKEY_LIVE_MUSIC_E2E"] == "1"))+@MainActor+struct MusicPlaylistLiveE2ETests {+ nonisolated static let command = "Create a playlist of the 10 best songs from 2000"++ /// The list the live run settled on (from web research) — known-good catalog hits from 2000.+ nonisolated static let songs: [(title: String, artist: String)] = [+ ("Bye Bye Bye", "NSYNC"),+ ("Oops!... I Did It Again", "Britney Spears"),+ ("The Real Slim Shady", "Eminem"),+ ("Yellow", "Coldplay"),+ ("Kryptonite", "3 Doors Down"),+ ("Beautiful Day", "U2"),+ ("Ms. Jackson", "OutKast"),+ ("One More Time", "Daft Punk"),+ ("It's My Life", "Bon Jovi"),+ ("Say My Name", "Destiny's Child")+ ]++ /// Replays the music skill's documented flow off the task's typed state: tool history decides+ /// the phase, world-model facts carry the created playlist id, and song ids come from the+ /// `song:<id>` lines music.search prints.+ struct ScriptedPlaylistPlanner: HarnessNextStepPlanning {+ let playlistName: String++ func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {+ let history = task.toolHistory+ let searches = history.filter { $0.call.name == MusicPlaybackToolProvider.ToolName.search }+ if searches.isEmpty {+ // The skill doctrine's batched form: every song in ONE pipe-separated search.+ let batch = MusicPlaylistLiveE2ETests.songs+ .map { "\($0.title) \($0.artist)" }+ .joined(separator: " | ")+ return HarnessToolCall(+ name: MusicPlaybackToolProvider.ToolName.search,+ input: ["query": batch, "limit": "1"]+ )+ }+ func ranPlaylistAction(_ action: String) -> Bool {+ history.contains {+ $0.call.name == MusicPlaybackToolProvider.ToolName.playlist && $0.call.input["action"] == action+ }+ }+ if !ranPlaylistAction("create") {+ return HarnessToolCall(+ name: MusicPlaybackToolProvider.ToolName.playlist,+ input: [+ "action": "create",+ "name": playlistName,+ "description": "The 10 best songs from the year 2000 — Donkey live E2E"+ ]+ )+ }+ guard let playlistID = task.worldModel.facts["music.playlist.created.id"] else {+ return HarnessToolCall(name: "run.failSafe", input: ["reason": "noCreatedPlaylistID"])+ }+ if !ranPlaylistAction("add") {+ let songIDs = searches.flatMap { Self.songIDs(in: $0.summary) }+ return HarnessToolCall(+ name: MusicPlaybackToolProvider.ToolName.playlist,+ input: ["action": "add", "playlistID": playlistID, "songIDs": songIDs.joined(separator: ",")]+ )+ }+ if !ranPlaylistAction("entries") {+ return HarnessToolCall(+ name: MusicPlaybackToolProvider.ToolName.playlist,+ input: ["action": "entries", "playlistID": playlistID, "limit": "25"]+ )+ }+ return HarnessToolCall(name: "run.complete", input: ["reason": "Playlist created, filled, and read back"])+ }++ /// Every id from the `song:<id> — title (artist)` lines of a music.search summary — a+ /// batched search reports one hit section per query.+ static func songIDs(in summary: String) -> [String] {+ summary.split(separator: "\n")+ .filter { $0.hasPrefix("song:") }+ .compactMap { $0.dropFirst("song:".count).split(separator: " ").first.map(String.init) }+ }+ }++ @Test+ func createsTheBestOf2000PlaylistForReal() async throws {+ let formatter = DateFormatter()+ formatter.dateFormat = "yyyyMMdd-HHmmss"+ let stamp = formatter.string(from: Date())+ // Timestamped so reruns never collide — also keeps createPlaylist's confirm-by-name+ // verification read unambiguous, and makes the playlist easy to find for manual cleanup.+ let playlistName = "Best of 2000 (Donkey E2E \(stamp))"++ let coordinator = HarnessTaskCoordinator()+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ let provider = MusicPlaybackToolProvider(service: MusicKitPlaybackService())+ for tool in provider.makeTools() {+ await registry.register(tool)+ }+ let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)+ let task = await coordinator.createTask(+ id: "live-music-e2e-\(stamp)",+ threadID: "t",+ goal: Self.command,+ grantedPermissions: [.lifecycle]+ )++ // The same transcript wiring the real route uses, written under a temp root so the run+ // leaves a readable thread.md to inspect.+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("donkey-live-music-e2e-\(stamp)", isDirectory: true)+ let transcript = ThreadTranscript(id: task.id, root: root)+ transcript.begin(id: task.id, app: "Music")+ transcript.userMessage(Self.command)+ transcript.planning(+ goal: Self.command,+ targetApp: "Music",+ parameters: ["year": "2000", "count": "10", "playlistName": playlistName],+ successCriteria: "A library playlist named \"\(playlistName)\" exists and lists the 10 songs"+ )++ let steps = await runtime.run(taskID: task.id, planner: ScriptedPlaylistPlanner(playlistName: playlistName)) { step in+ guard let result = step.toolResult else { return }+ transcript.step(+ number: step.task.toolHistory.count,+ thought: nil,+ reason: nil,+ tool: result.toolName,+ input: step.task.toolHistory.last?.call.input ?? [:],+ status: result.status.rawValue,+ output: result.summary+ )+ }++ let finalTask = await coordinator.task(id: task.id)+ let threadText = (try? String(contentsOfFile: transcript.threadPath, encoding: .utf8)) ?? ""+ print("Live E2E thread (\(transcript.threadPath)):\n\(threadText)")++ // The run completed end to end: one batched search + create + add + entries + run.complete.+ #expect(+ finalTask?.status == .completed,+ "final status \(finalTask?.status.rawValue ?? "nil") — last step: \(steps.last?.toolResult?.summary ?? "none")"+ )+ #expect(steps.count == 5)++ // The real-world outcome, read back from the Apple Music API: the playlist lists the songs.+ let entriesSummary = steps+ .first { $0.toolResult?.toolName == MusicPlaybackToolProvider.ToolName.playlist+ && $0.toolResult?.metadata["reason"] == "entries" }?+ .toolResult?.summary ?? ""+ #expect(entriesSummary.contains("entries (10)"), "entries read-back: \(entriesSummary)")+ #expect(entriesSummary.contains("Bye Bye Bye"))+ #expect(entriesSummary.contains("Say My Name"))++ // And the thread reads as the grouped trace: planning block, step blocks, real outputs.+ #expect(threadText.contains("🗺️ assistant · planning"))+ #expect(threadText.contains("**Goal:** \(Self.command)"))+ #expect(threadText.contains("## Step 1"))+ #expect(threadText.contains("## Step 5"))+ #expect(threadText.contains("**Action:** `music.playlist`"))+ #expect(threadText.contains("### 📄 Output — `succeeded`"))+ }+}diff --git a/docs/guides/authoring-skills.md b/docs/guides/authoring-skills.mdindex 4f815b28..2264467e 100644--- a/docs/guides/authoring-skills.md+++ b/docs/guides/authoring-skills.md@@ -87,7 +87,7 @@ Three kinds of app-specific facts deserve explicit statements:## CompactnessSeveral skills can load in the same turn, so every line costs context.-Built-in packs run 11–75 lines (`music`, the fullest, is 75). Prefer short+Built-in packs run 11–65 lines (`music`, the fullest, is ~65). Prefer shortrules, exact commands, known pitfalls, and script statuses; cut long examples,edge-case inventories, and anything the global prompt already says. If asection keeps growing, the content probably belongs in a validated script or a@@ -103,7 +103,7 @@ script that takes raw input safely.A skill may ship validated scripts in a `scripts/` subfolder — discovery picksthem up automatically, with no frontmatter line. The script id is the sluggedrelative path without extension-(`scripts/play-media-by-search.applescript` → `scripts-play-media-by-search`).+(`scripts/save-note.applescript` → `scripts-save-note`).AppleScript, shell, and JavaScript files are recognized; bundled scripts countas validated, learned ones start as pending validation.@@ -113,15 +113,17 @@ returns, and what to do for each status — including whether fallback isallowed:```text-`skill_run` with `scriptID=scripts-play-media-by-search`, input = the-normalized query. `status=played` → verified, report what's playing.-`status=not_found` → read `hint=`; do not rerun the same query.+`skill_run` with `scriptID=scripts-save-note`, input = the note body.+`status=saved` → verified, report the note title.+`status=error` → read `hint=`; do not rerun the same input.```Scripts are bounded and deterministic: one search-and-play, one note created,one export. No open-ended browsing, retry loops, or unbounded polling.-See existing packs under `BuiltInSkills/` for the shape — `music` is the-fullest example (script statuses, an AX limitation, verification, failure-behavior); `notes` and `mail` are simpler app skills; `system-tools` is an-other-skill.+A skill may instead route to native harness tools when the capability is built+into the app: `music` ships no scripts and directs the planner to the+`music.*` playback tools. See existing packs under `BuiltInSkills/` for the+shape — `music` is a tool-backed skill (query shaping, verification doctrine,+failure behavior); `notes` and `mail` are simpler app skills; `system-tools`+is an other-skill.diff --git a/scripts/evals/run_music_playlist_e2e.sh b/scripts/evals/run_music_playlist_e2e.shnew file mode 100755index 00000000..6f16b216--- /dev/null+++ b/scripts/evals/run_music_playlist_e2e.sh@@ -0,0 +1,182 @@+#!/usr/bin/env bash+set -euo pipefail++# Live end-to-end check of the music-playlist flow: submit+# "Create a playlist of the 10 best songs from 2000" to Donkey Dev as a real user turn —+# real hosted planning, real MusicKit, real Apple Music library — wait for the run to finish,+# then verify the outcome independently:+# 1. the turn's slice of thread.md shows the planning block and grouped step blocks and ends+# with "Run finished: completed",+# 2. the Music app really has the created playlist with the expected tracks (read via+# AppleScript, never trusted from the agent's own claims).+#+# A follow-up turn APPENDS to an existing thread.md (the app reuses the conversation thread), so+# every check runs against the content appended after submission, never the whole file.+#+# Requirements: persisted Donkey Dev login, an Apple Music subscription, the site dev server on+# :3000 (or DONKEY_WEB_BASE_URL pointing elsewhere), and Accessibility permission for the+# terminal running this script (System Events keystrokes drive the prompt).+#+# This CREATES A REAL PLAYLIST and Apple provides no delete API — remove it by hand in the+# Music app afterwards (the output names it).+#+# Usage: scripts/evals/run_music_playlist_e2e.sh+# DONKEY_E2E_TIMEOUT seconds to wait for the run to finish (default 600)+# DONKEY_E2E_MIN_TRACKS minimum tracks for a pass (default 8 — the model may miss a search)++# BSD grep under a C locale silently fails to match multibyte patterns, so pin UTF-8 and keep all+# grep patterns ASCII-only anyway (the thread headings contain emoji and "·").+export LC_ALL=en_US.UTF-8++REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+COMMAND_TEXT="Create a playlist of the 10 best songs from 2000"+THREADS_DIR="$HOME/Library/Application Support/Donkey/Threads"+TIMEOUT_SECONDS="${DONKEY_E2E_TIMEOUT:-600}"+MIN_TRACKS="${DONKEY_E2E_MIN_TRACKS:-8}"++THREAD_MD=""+BASE_LINES=0++# The turn's slice of the thread: everything appended after submission.+turn_text() {+ tail -n +"$((BASE_LINES + 1))" "$THREAD_MD"+}++fail() {+ echo "FAIL: $1" >&2+ if [ -n "$THREAD_MD" ] && [ -f "$THREAD_MD" ]; then+ echo "--- turn slice tail ($THREAD_MD from line $((BASE_LINES + 1))) ---" >&2+ turn_text | tail -n 40 >&2+ fi+ exit 1+}++# 1. Make sure Donkey Dev is running (build + launch when it is not).+if ! pgrep -xq "Donkey Dev"; then+ echo "Donkey Dev is not running — building and launching (this takes a few minutes)…"+ DONKEY_START_SITE=0 DONKEY_LAUNCH_APP=0 "$REPO_ROOT/scripts/run-donkey-dev.sh"+ DEV_APP_BINARY="$(find "$REPO_ROOT/apps/Donkey/.build" -path "*/debug/Donkey Dev.app/Contents/MacOS/Donkey Dev" | head -n 1)"+ [ -n "$DEV_APP_BINARY" ] || fail "built Donkey Dev binary not found under apps/Donkey/.build"+ "$DEV_APP_BINARY" > /tmp/donkey-music-e2e-stdout.log 2>&1 &+ for _ in $(seq 1 30); do+ pgrep -xq "Donkey Dev" && break+ sleep 1+ done+ pgrep -xq "Donkey Dev" || fail "Donkey Dev did not start"+ sleep 5 # let the overlay finish coming up+fi+echo "Donkey Dev is running."++# 2. Snapshot every existing thread.md's length, so the new turn is found by what got APPENDED.+SNAPSHOT="$(mktemp)"+trap 'rm -f "$SNAPSHOT"' EXIT+for md in "$THREADS_DIR"/*/thread.md; do+ [ -f "$md" ] || continue+ printf '%s %s\n' "$(wc -l < "$md" | tr -d ' ')" "$md"+done > "$SNAPSHOT"++# 3. Submit the command: double-tap Command opens the centered prompt focused, then type + return.+osascript <<'OSA'+tell application "System Events"+ key down command+ key up command+ delay 0.12+ key down command+ key up command+end tell+OSA+sleep 1.2+osascript -e 'on run argv' -e 'tell application "System Events" to keystroke (item 1 of argv)' -e 'end run' "$COMMAND_TEXT"+sleep 0.4+osascript -e 'tell application "System Events" to key code 36'+echo "Submitted: $COMMAND_TEXT"++# 4. Find the thread this turn landed in: new file, or existing file whose appended slice carries+# the command.+for _ in $(seq 1 30); do+ while IFS= read -r dir; do+ md="$THREADS_DIR/$dir/thread.md"+ [ -f "$md" ] || continue+ old="$(grep -F " $md" "$SNAPSHOT" | head -n 1 | awk '{print $1}')"+ old="${old:-0}"+ if tail -n +"$((old + 1))" "$md" | grep -F "$COMMAND_TEXT" >/dev/null; then+ THREAD_MD="$md"+ BASE_LINES="$old"+ break+ fi+ done < <(ls -t "$THREADS_DIR" | head -n 5)+ [ -n "$THREAD_MD" ] && break+ sleep 2+done+[ -n "$THREAD_MD" ] || fail "no thread.md picked up the command within 60s — did the prompt open?"+echo "Thread: $THREAD_MD (turn starts after line $BASE_LINES)"++# 5. Wait for THIS turn's run to finish (the transcript's lifecycle event is the signal).+elapsed=0+until turn_text | grep "Run finished:" >/dev/null; do+ sleep 5+ elapsed=$((elapsed + 5))+ [ "$elapsed" -lt "$TIMEOUT_SECONDS" ] || fail "run did not finish within ${TIMEOUT_SECONDS}s"+done+echo "Run finished after ~${elapsed}s."++# 6. Assert the turn reads as the grouped trace and the run completed. Step numbers continue+# across turns on a reused thread, so match any step heading. The planning block depends on the+# 15s understanding deadline; the documented fallback line is the acceptable absence.+if turn_text | grep -E "^### .*assistant.*planning" >/dev/null; then+ echo "Planning block present."+elif turn_text | grep "Understanding was unavailable" >/dev/null; then+ echo "WARN: understanding timed out this turn — planning block legitimately absent."+else+ fail "turn has neither a planning block nor the understanding-unavailable event"+fi+turn_text | grep "^## Step " >/dev/null || fail "turn has no grouped step blocks"+# A completed run logs "Run finished: ok"; anything else (failedSafe, stuckRepeatingFailure…) fails.+turn_text | grep -E "Run finished: (ok|completed)" >/dev/null || fail "run did not complete: $(turn_text | grep 'Run finished:')"++# 7. Independent verification: read the created playlist straight from the Music app. The name+# comes from the LAST create action recorded in the thread — a rerun on a reused thread may+# fill a playlist created in an earlier turn, so the whole file is searched, not just the+# slice. The track count comes from AppleScript. Cloud-created playlists can take a moment to+# sync into the local library, so retry briefly.+PLAYLIST_NAME="$(awk '/^action: create$/{f=1; next} f && /^name: /{sub(/^name: /,""); last=$0; f=0} END{print last}' "$THREAD_MD")"+[ -n "$PLAYLIST_NAME" ] || fail "no music.playlist create action with a name found in the thread"+echo "Created playlist (per thread): $PLAYLIST_NAME"++# Cloud-created playlists and their tracks sync into the local library on their own schedule —+# observed taking several minutes. Poll generously, take the MAX track count across all playlists+# with the name (an older empty duplicate must not mask the filled one), and relaunch Music once a+# minute — it pulls the cloud library on launch, which reliably nudges a stalled sync.+SYNC_TIMEOUT="${DONKEY_E2E_SYNC_TIMEOUT:-360}"+TRACK_COUNT=""+sync_elapsed=0+while [ "$sync_elapsed" -lt "$SYNC_TIMEOUT" ]; do+ TRACK_COUNT="$(osascript \+ -e 'on run argv' \+ -e 'set best to -1' \+ -e 'tell application "Music"' \+ -e 'repeat with p in (every user playlist whose name is (item 1 of argv))' \+ -e 'set trackCount to (count of tracks of p)' \+ -e 'if trackCount > best then set best to trackCount' \+ -e 'end repeat' \+ -e 'end tell' \+ -e 'if best is -1 then return ""' \+ -e 'return best' \+ -e 'end run' "$PLAYLIST_NAME" 2>/dev/null || true)"+ if [ -n "$TRACK_COUNT" ] && [ "$TRACK_COUNT" -ge "$MIN_TRACKS" ]; then+ break+ fi+ echo "Waiting for library sync (playlist: ${TRACK_COUNT:-absent})…"+ sleep 10+ sync_elapsed=$((sync_elapsed + 10))+ if [ $((sync_elapsed % 60)) -eq 0 ]; then+ osascript -e 'tell application "Music" to quit' 2>/dev/null || true+ sleep 3+ fi+done+[ -n "$TRACK_COUNT" ] || fail "playlist \"$PLAYLIST_NAME\" never appeared in the Music app library"+[ "$TRACK_COUNT" -ge "$MIN_TRACKS" ] || fail "playlist \"$PLAYLIST_NAME\" has only $TRACK_COUNT track(s), expected >= $MIN_TRACKS"++echo "PASS: \"$PLAYLIST_NAME\" exists in Music with $TRACK_COUNT tracks."+echo "Thread: $THREAD_MD"+echo "Reminder: Apple has no playlist-delete API — remove \"$PLAYLIST_NAME\" in the Music app when done."