PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / PulseCanvasMCPService.swift
| 1 | #if os(macOS) && DIRECT_BUILD && !STORE_BUILD |
| 2 | import AVFoundation |
| 3 | import Combine |
| 4 | import Foundation |
| 5 | |
| 6 | @MainActor |
| 7 | final class PulseMCPService: ObservableObject { |
| 8 | typealias Object = PulseMCP.Object |
| 9 | private var access: PulseMCPAccess! |
| 10 | private var audio: AudioController! |
| 11 | private var studio: StudioStore! |
| 12 | private var radio: RadioController! |
| 13 | private var render: RenderState! |
| 14 | private var exporter: SocialExportController! |
| 15 | private var jobs: PulseMCPJobs! |
| 16 | private let library = ProjectMPresets.shared |
| 17 | private var preparing = false |
| 18 | private var radioCatalog: (source: URL, catalog: RadioCatalog, url: URL, stationID: String)? |
| 19 | |
| 20 | func attach(access: PulseMCPAccess, audio: AudioController, studio: StudioStore, radio: RadioController, |
| 21 | render: RenderState, exporter: SocialExportController) { |
| 22 | guard self.access == nil else { return } |
| 23 | self.access = access |
| 24 | self.audio = audio |
| 25 | self.studio = studio |
| 26 | self.radio = radio |
| 27 | self.render = render |
| 28 | self.exporter = exporter |
| 29 | jobs = PulseMCPJobs(access: access, exporter: exporter) |
| 30 | } |
| 31 | |
| 32 | func call(_ name: String, _ args: Object) async -> Object { |
| 33 | do { |
| 34 | guard let tool = PulseMCP.tools.first(where: { $0.name == name }), PulseMCP.valid(args, schema: tool.input) else { |
| 35 | throw PulseMCPError("INVALID_ARGUMENTS", "Use the published input schema.") |
| 36 | } |
| 37 | if name == "get_app_status" { |
| 38 | return ["value": ["running": true, "enabled": access.enabled, |
| 39 | "edition": PulseMCPAccess.edition, "version": PulseMCPAccess.version, |
| 40 | "editing": access.enabled && access.editing, "playback": access.enabled && access.playback, |
| 41 | "rendering": access.enabled && access.rendering, |
| 42 | "pendingExports": access.enabled ? jobs.pendingCount : 0]] |
| 43 | } |
| 44 | guard access.enabled else { |
| 45 | throw PulseMCPError("CONNECTION_DISABLED", "Enable local agent access in PulseCanvas Studio → Settings → Agent access.") |
| 46 | } |
| 47 | if let permission = tool.permission { try require(permission) } |
| 48 | return ["value": try await execute(name, args)] |
| 49 | } catch { |
| 50 | return ["error": PulseMCPJobs.error(error, defaultCode: "OPERATION_FAILED").payload] |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | private func execute(_ name: String, _ args: Object) async throws -> Object { |
| 55 | switch name { |
| 56 | case "get_capabilities": return capabilities() |
| 57 | case "list_visualizers": return listVisualizers(args) |
| 58 | case "get_visualizer": return visualizer(try scene(args.string("id")), detailed: true) |
| 59 | case "list_favorites": |
| 60 | let kind = args.string("kind") |
| 61 | let items = kind == "visualizer" |
| 62 | ? library.availableScenes.filter(library.isFavorite).map { visualizer($0) } |
| 63 | : radio.favoriteSongs.map { song($0.track) } |
| 64 | return ["kind": kind, "favorites": items] |
| 65 | case "list_radio_songs": |
| 66 | let tracks: [RadioTrack] |
| 67 | if let current = radio.catalog, !radio.isPersonalMusic { tracks = current.tracks } |
| 68 | else { tracks = try await radioFavoritesCatalog().catalog.tracks } |
| 69 | return page(tracks.map { song($0) }, args: args, key: "songs") |
| 70 | case "set_favorite": return try await setFavorite(args) |
| 71 | case "get_playback_state": return try playback() |
| 72 | case "load_song": |
| 73 | try checkRevision(args) |
| 74 | let source = try authorizedAudio(args.string("path")) |
| 75 | let prepared = try await prepare(source, args: args, permission: "playback") |
| 76 | try install(prepared) |
| 77 | studio.segments = []; studio.detectedBPM = nil; studio.generationSeed = nil |
| 78 | return try playback() |
| 79 | case "set_playback_state": |
| 80 | try checkStudio() |
| 81 | guard audio.selectedURL != nil else { throw audioUnavailable() } |
| 82 | switch args.string("state") { |
| 83 | case "play": |
| 84 | if !audio.isPlaying { audio.playFullSoundtrack() } |
| 85 | guard audio.isPlaying else { throw PulseMCPError("PLAYBACK_FAILED", "PulseCanvas could not start the audio engine.") } |
| 86 | case "pause": audio.pause() |
| 87 | default: audio.stop() |
| 88 | } |
| 89 | return try playback() |
| 90 | case "seek": |
| 91 | try checkStudio() |
| 92 | guard audio.selectedURL != nil, audio.duration > 0 else { throw audioUnavailable() } |
| 93 | let position = args.double("seconds") |
| 94 | guard position <= audio.duration else { throw PulseMCPError("INVALID_POSITION", "Seek within the reported soundtrack duration.") } |
| 95 | audio.seek(fraction: position / audio.duration) |
| 96 | return try playback() |
| 97 | case "set_volume": |
| 98 | let volume = Float(args.double("volume")) |
| 99 | if radio.isActive { radio.volume = volume } else { audio.volume = volume } |
| 100 | return try playback() |
| 101 | case "get_project": |
| 102 | try checkStudio() |
| 103 | return try projectDetails(document(), duration: audio.duration) |
| 104 | case "create_project": |
| 105 | try checkStudio(); try checkRevision(args) |
| 106 | studio.cloudProjectID = UUID().uuidString |
| 107 | studio.generationSeed = nil; studio.isStudio = true |
| 108 | studio.barsPerSection = args["barsPerScene"] as? Int ?? 4 |
| 109 | studio.segments = []; studio.selectedSegment = 0 |
| 110 | studio.detectedBPM = audio.segmentPlan(beatsPerSection: studio.beatsPerSection)?.bpm |
| 111 | return try projectDetails(document(), duration: audio.duration) |
| 112 | case "open_project": return try await openProject(args) |
| 113 | case "save_project": return try saveProject(args) |
| 114 | case "analyze_song": |
| 115 | try checkStudio() |
| 116 | guard let grid = audio.segmentPlan(beatsPerSection: args["beatsPerSection"] as? Int ?? 1) else { throw audioUnavailable() } |
| 117 | var info: Object = ["boundariesSeconds": grid.boundaries] |
| 118 | info["bpm"] = grid.bpm |
| 119 | return info |
| 120 | case "set_timeline": |
| 121 | try checkStudio(); try checkRevision(args) |
| 122 | let entries = args["segments"] as? [Object] ?? [] |
| 123 | let segments = try entries.map { |
| 124 | StudioSegment(start: $0.double("startSeconds"), end: $0.double("endSeconds"), |
| 125 | scene: try scene($0.string("visualizerId")), bars: $0["bars"] as? Int) |
| 126 | } |
| 127 | try checkWholeSong(segments, duration: audio.duration) |
| 128 | var appearances = studio.presets |
| 129 | for index in Set(segments.map(\.scene)) where appearances[index] == nil { |
| 130 | appearances[index] = library.favoriteAppearance(for: index) ?? .defaults(for: index) |
| 131 | } |
| 132 | studio.presets = appearances |
| 133 | studio.isStudio = true; studio.segments = segments; studio.generationSeed = nil |
| 134 | studio.follow(time: audio.playbackSeconds, render: render) |
| 135 | return try projectDetails(document(), duration: audio.duration) |
| 136 | case "set_visualizer": |
| 137 | try checkStudio(); try checkRevision(args) |
| 138 | let index = try scene(args.string("id")) |
| 139 | if let section = args["section"] as? Int { |
| 140 | guard studio.segments.indices.contains(section) else { |
| 141 | throw PulseMCPError("INVALID_TIMELINE", "Read the project and choose an existing section index.") |
| 142 | } |
| 143 | studio.assignScene(index, at: section, render: render) |
| 144 | studio.generationSeed = nil |
| 145 | } else { |
| 146 | studio.selectScene(index, render: render) |
| 147 | } |
| 148 | return try projectDetails(document(), duration: audio.duration) |
| 149 | case "set_visualizer_settings": |
| 150 | try checkStudio(); try checkRevision(args) |
| 151 | let index = try scene(args.string("id")) |
| 152 | let changes = args["settings"] as? Object ?? [:] |
| 153 | let controls = controls(for: index) |
| 154 | guard changes.keys.allSatisfy({ controls[$0] != nil }) else { |
| 155 | throw PulseMCPError("UNSUPPORTED_SETTING", "Read get_visualizer for controls that apply to this effect.") |
| 156 | } |
| 157 | let updated = try appearance(for: index, changes: changes) |
| 158 | if studio.presets[index] != updated { studio.presets[index] = updated } |
| 159 | if index == render.scene { updated.apply(to: render) } |
| 160 | return try projectDetails(document(), duration: audio.duration) |
| 161 | case "start_export", "render_preview": return try startExport(name, args) |
| 162 | case "get_export_status": return ["job": jobs.details(try jobs.job(args.string("id")))] |
| 163 | case "list_exports": return ["jobs": try jobs.recent(args["limit"] as? Int ?? 25).map(jobs.details)] |
| 164 | case "cancel_export": return ["job": jobs.details(try jobs.cancel(args.string("id")))] |
| 165 | case "create_music_video": return try await createMusicVideo(args) |
| 166 | default: throw PulseMCPError("UNKNOWN_TOOL", "Use tools/list to discover the supported tools.") |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | private func require(_ permission: String) throws { |
| 171 | guard access.enabled, access.permits(permission) else { |
| 172 | throw PulseMCPError("PERMISSION_REQUIRED", "Enable \(permission) access in PulseCanvas Studio → Settings → Agent access.") |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | private func capabilities() -> Object { |
| 177 | var result: Object = [ |
| 178 | "edition": PulseMCPAccess.edition, "resolutions": SocialExportController.supportedResolutions, |
| 179 | "frameRates": SocialExportController.supportedFrameRates.filter { [24, 30, 60].contains($0) }, |
| 180 | "aspects": SocialAspect.allCases.map(\.agentName), |
| 181 | "engines": library.entries.isEmpty ? ["metal"] : ["metal", "projectM"], |
| 182 | "videoCodec": "h264", "audioCodec": "aac", "controls": PulseMCP.controlProperties, |
| 183 | "maxPendingExports": PulseMCPJobs.maxPending |
| 184 | ] |
| 185 | result["inputFolder"] = access.scope(.input)?.url.path |
| 186 | result["outputFolder"] = access.scope(.output)?.url.path |
| 187 | return result |
| 188 | } |
| 189 | |
| 190 | private func checkStudio() throws { |
| 191 | guard !radio.isActive else { |
| 192 | throw PulseMCPError("RADIO_ACTIVE", "Studio operations preserve the current Radio session. Load an authorized song to switch to Studio.") |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | private func scene(_ id: String) throws -> Int { |
| 197 | let index = id.hasPrefix("native:") ? Int(id.dropFirst(7)) : library.scene(for: id) |
| 198 | guard let index, library.availableScenes.contains(index), library.identity(for: index) == id else { |
| 199 | throw PulseMCPError("UNSUPPORTED_EFFECT", "The visualizer ID is unknown or unavailable in this edition. Read list_visualizers.") |
| 200 | } |
| 201 | return index |
| 202 | } |
| 203 | |
| 204 | private func visualizer(_ index: Int, detailed: Bool = false) -> Object { |
| 205 | var item: Object = ["id": library.identity(for: index), "name": library.sceneNames[index], |
| 206 | "category": library.category(for: index), |
| 207 | "engine": library.preset(for: index) == nil ? "metal" : "projectM", |
| 208 | "available": true, "favorite": library.isFavorite(index)] |
| 209 | if detailed { |
| 210 | if let data = try? JSONEncoder().encode(look(index)) { |
| 211 | item["settings"] = try? JSONSerialization.jsonObject(with: data) |
| 212 | } |
| 213 | item["controls"] = controls(for: index) |
| 214 | } |
| 215 | return item |
| 216 | } |
| 217 | |
| 218 | private func listVisualizers(_ args: Object) -> Object { |
| 219 | let query = args["query"] as? String |
| 220 | let engine = args["engine"] as? String |
| 221 | let category = args["category"] as? String |
| 222 | let hits = library.availableScenes.lazy.map { self.visualizer($0) }.filter { |
| 223 | (engine == nil || $0.string("engine") == engine) && |
| 224 | (category == nil || $0.string("category").localizedCaseInsensitiveCompare(category!) == .orderedSame) && |
| 225 | (args["favoritesOnly"] as? Bool != true || $0["favorite"] as? Bool == true) && |
| 226 | (query == nil || $0.string("name").localizedCaseInsensitiveContains(query!) || |
| 227 | $0.string("id").localizedCaseInsensitiveContains(query!)) |
| 228 | } |
| 229 | return page(Array(hits), args: args, key: "visualizers") |
| 230 | } |
| 231 | |
| 232 | private func page(_ items: [Object], args: Object, key: String) -> Object { |
| 233 | let offset = min(args["offset"] as? Int ?? 0, items.count) |
| 234 | let end = min(offset + (args["limit"] as? Int ?? 50), items.count) |
| 235 | var response: Object = [key: Array(items[offset..<end]), "total": items.count] |
| 236 | if end < items.count { response["nextOffset"] = end } |
| 237 | return response |
| 238 | } |
| 239 | |
| 240 | private func song(_ track: RadioTrack) -> Object { |
| 241 | ["id": track.id, "title": track.title, "genre": track.genre, "durationSeconds": track.duration, |
| 242 | "favorite": radio.isFavoriteSong(track)] |
| 243 | } |
| 244 | |
| 245 | private func setFavorite(_ args: Object) async throws -> Object { |
| 246 | let id = args.string("id"), kind = args.string("kind"), desired = args["favorite"] as? Bool == true |
| 247 | if kind == "visualizer" { |
| 248 | let index = try scene(id) |
| 249 | if library.isFavorite(index) != desired { library.toggleFavorite(index, appearance: look(index)) } |
| 250 | } else { |
| 251 | if desired, !radio.favoriteSongs.contains(where: { $0.id == id }), |
| 252 | !radio.setFavoriteSong(id: id, favorite: true) { |
| 253 | let resolved = try await radioFavoritesCatalog() |
| 254 | guard let track = resolved.catalog.tracks.first(where: { $0.id == id }) else { |
| 255 | throw PulseMCPError("SONG_NOT_FOUND", "Read list_radio_songs to find an available Radio track ID.") |
| 256 | } |
| 257 | try require("editing") |
| 258 | let song = FavoriteRadioSong(track: track, sourceURL: resolved.source, catalogURL: resolved.url, |
| 259 | stationID: resolved.stationID, folderBookmark: radio.studioMusicFolderBookmark) |
| 260 | guard radio.setFavoriteSong(id: id, favorite: true, candidate: song) else { |
| 261 | throw PulseMCPError("FAVORITE_NOT_SAVED", "Verify the Radio catalog and the saved favorites limit.") |
| 262 | } |
| 263 | } else if !desired { |
| 264 | guard UUID(uuidString: id) != nil else { |
| 265 | throw PulseMCPError("SONG_NOT_FOUND", "Supply a Radio track ID from list_radio_songs or list_favorites.") |
| 266 | } |
| 267 | _ = radio.setFavoriteSong(id: id, favorite: false) |
| 268 | } |
| 269 | } |
| 270 | return ["kind": kind, "id": id, "favorite": desired] |
| 271 | } |
| 272 | |
| 273 | /// Resolve the app's configured Radio library without starting playback or |
| 274 | /// changing the active station. Local libraries still require an input grant. |
| 275 | private func radioFavoritesCatalog() async throws -> (source: URL, catalog: RadioCatalog, url: URL, stationID: String) { |
| 276 | let configured = radio.studioMusicSource |
| 277 | let authorized = configured.isFileURL ? try access.authorize(configured.path, in: [.input]) : nil |
| 278 | let source = authorized?.url ?? configured |
| 279 | defer { withExtendedLifetime(authorized?.scope) {} } |
| 280 | if let radioCatalog, radioCatalog.source == source { return radioCatalog } |
| 281 | do { |
| 282 | let resolved = try await radio.studioMusicLibrary.completeCatalog(at: source) |
| 283 | guard access.enabled, radio.studioMusicSource == configured else { |
| 284 | throw PulseMCPError("RADIO_CATALOG_CHANGED", "The Radio source or agent access changed. Read the current catalog and retry.") |
| 285 | } |
| 286 | if source.isFileURL { _ = try access.authorize(resolved.url.path, in: [.input]) } |
| 287 | let entry = (source: source, catalog: resolved.catalog, url: resolved.url, stationID: resolved.stationID) |
| 288 | radioCatalog = entry |
| 289 | return entry |
| 290 | } catch let failure as PulseMCPError { throw failure } |
| 291 | catch { |
| 292 | throw PulseMCPError("RADIO_CATALOG_UNAVAILABLE", "The configured Radio catalog could not be loaded. Check the Radio source or connection.") |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | private func controls(for index: Int) -> Object { |
| 297 | var controls = PulseMCP.controlProperties |
| 298 | if library.preset(for: index) != nil { |
| 299 | // The preset supplies its own colors, particle sizes and depth. |
| 300 | for key in ["palette", "particleSize", "fog"] { controls.removeValue(forKey: key) } |
| 301 | } |
| 302 | if NativeEffects.effect(index)?.detailLabel == nil { controls.removeValue(forKey: "liquidDetail") } |
| 303 | if index != 28 { controls.removeValue(forKey: "haloCount") } |
| 304 | return controls |
| 305 | } |
| 306 | |
| 307 | private func look(_ index: Int) -> VisualPreset { |
| 308 | if index == render.scene { return studio.preset(render) } |
| 309 | return studio.presets[index] ?? library.favoriteAppearance(for: index) ?? .defaults(for: index) |
| 310 | } |
| 311 | |
| 312 | private func appearance(for index: Int, changes: Object) throws -> VisualPreset { |
| 313 | let data = try JSONEncoder().encode(look(index)) |
| 314 | let existing = try JSONSerialization.jsonObject(with: data) as? Object ?? [:] |
| 315 | let merged = existing.merging(changes) { _, new in new } |
| 316 | return try JSONDecoder().decode(VisualPreset.self, from: JSONSerialization.data(withJSONObject: merged)) |
| 317 | } |
| 318 | |
| 319 | private func audioUnavailable() -> PulseMCPError { |
| 320 | PulseMCPError("AUDIO_UNAVAILABLE", "Load an existing local audio file from the authorized input folder.") |
| 321 | } |
| 322 | |
| 323 | private func authorizedAudio(_ path: String) throws -> PulseMCPAccess.AuthorizedPath { |
| 324 | do { return try access.authorize(path, in: [.input]) } |
| 325 | catch let error as PulseMCPError where error.code == "FILE_UNAVAILABLE" { |
| 326 | throw PulseMCPError("AUDIO_UNAVAILABLE", error.message) |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | private func prepare(_ source: PulseMCPAccess.AuthorizedPath, args: Object, permission: String) async throws -> PreparedSoundtrack { |
| 331 | guard !preparing else { throw PulseMCPError("PROJECT_BUSY", "Wait for the other song or project preparation to finish.") } |
| 332 | preparing = true |
| 333 | defer { preparing = false } |
| 334 | let original = try PulseMCPJobs.sourceIdentity(source.url) |
| 335 | defer { withExtendedLifetime(source.scope) {} } |
| 336 | let preparation = Task.detached(priority: .userInitiated) { try PreparedSoundtrack(url: source.url) } |
| 337 | let prepared: PreparedSoundtrack |
| 338 | do { |
| 339 | prepared = try await withTaskCancellationHandler { try await preparation.value } onCancel: { preparation.cancel() } |
| 340 | } catch { throw PulseMCPJobs.error(error, defaultCode: "AUDIO_UNAVAILABLE") } |
| 341 | let current = try PulseMCPJobs.sourceIdentity(source.url) |
| 342 | guard current.bytes == original.bytes, current.modified == original.modified else { |
| 343 | throw PulseMCPError("AUDIO_CHANGED", "The file changed during preparation. Retry with a stable local copy.") |
| 344 | } |
| 345 | try require(permission) |
| 346 | _ = try authorizedAudio(source.url.path) |
| 347 | try checkRevision(args) |
| 348 | guard prepared.analyzer.duration > 0, prepared.analyzer.duration <= 86_400 else { throw audioUnavailable() } |
| 349 | return prepared |
| 350 | } |
| 351 | |
| 352 | private func install(_ prepared: PreparedSoundtrack) throws { |
| 353 | radio.leave() |
| 354 | guard audio.install(prepared) else { throw audioUnavailable() } |
| 355 | studio.timelineSoundtrack = audio.selectedURL |
| 356 | } |
| 357 | |
| 358 | private func document() -> CreatorProject { |
| 359 | studio.document(audio: audio, render: render, exporter: exporter) |
| 360 | } |
| 361 | |
| 362 | private func revision(_ project: CreatorProject) throws -> String { |
| 363 | var stable = project |
| 364 | if let scene = stable.timeline?.first?.scene, stable.studioEnabled == true { |
| 365 | stable.scene = scene |
| 366 | stable.appearance = stable.visualPresets?[scene] ?? .defaults(for: scene) |
| 367 | } |
| 368 | return UserBackup.hash(try stable.encoded()) |
| 369 | } |
| 370 | |
| 371 | private func checkRevision(_ args: Object) throws { |
| 372 | guard try revision(document()) == args.string("expectedRevision") else { |
| 373 | throw PulseMCPError("PROJECT_CONFLICT", "The Studio project changed. Read the current revision and review the new project before retrying.") |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | private func projectDetails(_ project: CreatorProject, duration: Double) throws -> Object { |
| 378 | let aspect = SocialAspect(rawValue: project.aspect) ?? .wide |
| 379 | var result: Object = ["revision": try revision(project), "durationSeconds": min(duration, 86_400), |
| 380 | "visualizerId": library.identity(for: project.scene), |
| 381 | "studioEnabled": project.studioEnabled ?? false, |
| 382 | "timeline": timeline(project).map(\.payload), |
| 383 | "exportSettings": ["aspect": aspect.agentName, "resolution": project.resolution, "fps": project.fps]] |
| 384 | result["id"] = project.cloudProjectID |
| 385 | result["seed"] = project.generationSeed |
| 386 | if let path = project.soundtrack?.path, (try? authorizedAudio(path)) != nil { |
| 387 | result["soundtrackPath"] = path |
| 388 | } |
| 389 | result["barsPerScene"] = project.barsPerSection.flatMap { (1...128).contains($0) ? $0 : nil } |
| 390 | return result |
| 391 | } |
| 392 | |
| 393 | private func timeline(_ project: CreatorProject) -> [PulseMCPScene] { |
| 394 | (project.timeline ?? []).map { |
| 395 | PulseMCPScene(visualizerId: project.effectIdentities?[$0.scene] ?? library.identity(for: $0.scene), |
| 396 | startSeconds: $0.start, endSeconds: $0.end, bars: $0.bars) |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | private func playback() throws -> Object { |
| 401 | ["ready": audio.selectedURL != nil, "playing": audio.isPlaying, "positionSeconds": min(audio.playbackSeconds, 86_400), |
| 402 | "durationSeconds": min(audio.duration, 86_400), "volume": audio.volume, |
| 403 | "mode": radio.isActive ? "radio" : "studio", "title": audio.title, "revision": try revision(document())] |
| 404 | } |
| 405 | |
| 406 | private func checkWholeSong(_ segments: [StudioSegment], duration: Double) throws { |
| 407 | guard duration > 0, !segments.isEmpty, |
| 408 | StudioTimeline.valid(segments, sceneCount: library.sceneNames.count), |
| 409 | let end = segments.last?.end, abs(end - duration) <= 0.001 else { |
| 410 | throw PulseMCPError("INVALID_TIMELINE", "Supply contiguous sections from zero through the exact soundtrack duration.") |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | private func outputPath(_ path: String, extension expected: String) throws -> PulseMCPAccess.AuthorizedPath { |
| 415 | let output = try access.authorize(path, in: [.output], writing: true) |
| 416 | guard output.url.pathExtension.lowercased() == expected else { |
| 417 | throw PulseMCPError("INVALID_PATH", "Use a .\(expected) filename in the authorized output folder.") |
| 418 | } |
| 419 | return output |
| 420 | } |
| 421 | |
| 422 | private func openProject(_ args: Object) async throws -> Object { |
| 423 | try checkRevision(args) |
| 424 | let input = try access.authorize(args.string("path"), in: [.input, .output]) |
| 425 | defer { withExtendedLifetime(input.scope) {} } |
| 426 | guard input.url.pathExtension.lowercased() == "pulsecanvas", |
| 427 | let size = try input.url.resourceValues(forKeys: [.fileSizeKey]).fileSize, size <= 8_000_000 else { |
| 428 | throw PulseMCPError("INVALID_PROJECT", "Choose a PulseCanvas project file under 8 MB.") |
| 429 | } |
| 430 | let data = try Data(contentsOf: input.url) |
| 431 | let saved = try JSONDecoder().decode(CreatorProject.self, from: data) |
| 432 | let referenced = Set((saved.timeline ?? []).map(\.scene)).union([saved.scene]) |
| 433 | for index in referenced { |
| 434 | if library.isRetiredScene(index, identities: saved.effectIdentities) { |
| 435 | throw PulseMCPError("UNSUPPORTED_EFFECT", "This project uses a retired effect. Open it in Studio if you want to choose a replacement.") |
| 436 | } |
| 437 | } |
| 438 | let project: CreatorProject |
| 439 | do { project = try saved.remapped(using: library) } |
| 440 | catch { throw PulseMCPError("UNSUPPORTED_EFFECT", error.localizedDescription) } |
| 441 | let aspect = try project.checkedAspect() |
| 442 | if let source = try BundledSoundtrack.resolve(identifier: project.bundledSoundtrack, externalURL: project.soundtrack) { |
| 443 | try require("playback") |
| 444 | let prepared = try await prepare(try authorizedAudio(source.path), args: args, permission: "editing") |
| 445 | try require("playback") |
| 446 | guard (project.timeline?.last?.end ?? 0) <= prepared.analyzer.duration + 0.05 else { |
| 447 | throw PulseMCPError("INVALID_TIMELINE", "The project's timeline extends beyond its authorized soundtrack.") |
| 448 | } |
| 449 | try install(prepared) |
| 450 | } else { |
| 451 | guard (project.timeline?.last?.end ?? 0) == 0 else { throw audioUnavailable() } |
| 452 | try require("playback") |
| 453 | radio.leave(); audio.clear(); studio.timelineSoundtrack = nil |
| 454 | } |
| 455 | studio.applyDocument(project, aspect: aspect, audio: audio, render: render, exporter: exporter) |
| 456 | try UserBackup.rememberProject(data, name: input.url.path) |
| 457 | return try projectDetails(document(), duration: audio.duration) |
| 458 | } |
| 459 | |
| 460 | private func signature(_ tool: String, _ args: Object) -> String { |
| 461 | UserBackup.hash(Data((tool + "\n" + PulseMCP.jsonText(args)).utf8)) |
| 462 | } |
| 463 | |
| 464 | private func writeProject(_ project: CreatorProject, to url: URL, overwrite: Bool) throws { |
| 465 | try PulseMCPJobs.checkDestination(url, overwrite: overwrite) |
| 466 | let staging = url.deletingLastPathComponent().appendingPathComponent(".PulseCanvas-project-" + UUID().uuidString) |
| 467 | let data = try project.encoded() |
| 468 | if overwrite && FileManager.default.fileExists(atPath: url.path) { |
| 469 | guard let current = project.cloudProjectID, |
| 470 | let size = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize, size <= 8_000_000, |
| 471 | let existing = try? JSONDecoder().decode(CreatorProject.self, from: Data(contentsOf: url)), |
| 472 | existing.cloudProjectID == current else { |
| 473 | throw PulseMCPError("OUTPUT_EXISTS", "Use a new name. PulseCanvas can replace only another save of this project.") |
| 474 | } |
| 475 | } |
| 476 | try data.write(to: staging, options: .withoutOverwriting) |
| 477 | defer { try? FileManager.default.removeItem(at: staging) } |
| 478 | try PulseMCPJobs.publish(staging, to: url, overwrite: overwrite) |
| 479 | try UserBackup.rememberProject(data, name: url.path) |
| 480 | } |
| 481 | |
| 482 | private func saveProject(_ args: Object) throws -> Object { |
| 483 | let key = args.string("requestKey"), signature = signature("save_project", args) |
| 484 | let target = try outputPath(args.string("path"), extension: "pulsecanvas") |
| 485 | defer { withExtendedLifetime(target.scope) {} } |
| 486 | if let receipt = try jobs.repeatSave(key: key, signature: signature) { |
| 487 | guard FileManager.default.fileExists(atPath: target.url.path) else { |
| 488 | throw PulseMCPError("PROJECT_NOT_FOUND", "The previously saved project is missing. Choose a destination and new request key.") |
| 489 | } |
| 490 | return ["path": receipt.path, "project": try projectDetails(receipt.project, duration: receipt.duration)] |
| 491 | } |
| 492 | try checkStudio(); try checkRevision(args) |
| 493 | var document = document() |
| 494 | if document.cloudProjectID == nil { document.cloudProjectID = UUID().uuidString } |
| 495 | try writeProject(document, to: target.url, overwrite: args["overwrite"] as? Bool == true) |
| 496 | try jobs.rememberSave(.init(key: key, signature: signature, path: target.url.path, project: document, duration: audio.duration)) |
| 497 | studio.cloudProjectID = document.cloudProjectID |
| 498 | return ["path": target.url.path, "project": try projectDetails(document, duration: audio.duration)] |
| 499 | } |
| 500 | |
| 501 | private func exportFormat(_ args: Object) throws -> PulseMCPJobs.Format { |
| 502 | let aspect = args["aspect"] as? String ?? exporter.aspect.agentName |
| 503 | let resolution = args["resolution"] as? Int ?? exporter.resolution |
| 504 | let fps = args["fps"] as? Int ?? exporter.fps |
| 505 | guard SocialExportController.supportedResolutions.contains(resolution), |
| 506 | SocialExportController.supportedFrameRates.contains(fps), [24, 30, 60].contains(fps) else { |
| 507 | throw PulseMCPError("UNSUPPORTED_FORMAT", "Choose a resolution and frame rate from get_capabilities.") |
| 508 | } |
| 509 | return .init(aspect: aspect, resolution: resolution, fps: fps) |
| 510 | } |
| 511 | |
| 512 | private func startExport(_ tool: String, _ args: Object) throws -> Object { |
| 513 | let key = args.string("requestKey"), signature = signature(tool, args) |
| 514 | if let previous = try jobs.repeatJob(key: key, signature: signature) { return ["job": jobs.details(previous)] } |
| 515 | try checkStudio(); try checkRevision(args) |
| 516 | guard let soundtrack = audio.selectedURL, audio.duration > 0 else { throw audioUnavailable() } |
| 517 | let source = try authorizedAudio(soundtrack.path) |
| 518 | let target = try outputPath(args.string("path"), extension: "mp4") |
| 519 | defer { withExtendedLifetime((source.scope, target.scope)) {} } |
| 520 | let preview = tool == "render_preview" ? (args["previewSeconds"] as? Double ?? 5) : nil |
| 521 | guard tool == "render_preview" || args["previewSeconds"] == nil else { |
| 522 | throw PulseMCPError("INVALID_ARGUMENTS", "Use render_preview for a short clip.") |
| 523 | } |
| 524 | let project = document() |
| 525 | if project.studioEnabled == true { try checkWholeSong(project.timeline ?? [], duration: audio.duration) } |
| 526 | let job = try makeJob(args: args, signature: signature, project: project, source: source.url, destination: target.url, |
| 527 | format: exportFormat(args), projectPath: nil, preview: preview, duration: audio.duration, fallback: false) |
| 528 | try jobs.submit(job) |
| 529 | return ["job": jobs.details(job)] |
| 530 | } |
| 531 | |
| 532 | private func makeJob(args: Object, signature: String, project: CreatorProject, source: URL, destination: URL, |
| 533 | format: PulseMCPJobs.Format, projectPath: String?, preview: Double?, duration: Double, |
| 534 | fallback: Bool) throws -> PulseMCPJobs.Job { |
| 535 | let overwrite = args["overwrite"] as? Bool == true |
| 536 | try jobs.checkCapacity(destination: destination) |
| 537 | try jobs.checkOutput(destination, overwrite: overwrite) |
| 538 | let identity = try PulseMCPJobs.sourceIdentity(source) |
| 539 | _ = try scene(library.identity(for: project.scene)) |
| 540 | for entry in timeline(project) { _ = try scene(entry.visualizerId) } |
| 541 | return .init(id: UUID().uuidString, signature: signature, requestKey: args.string("requestKey"), |
| 542 | destination: destination.path, projectPath: projectPath, sourcePath: source.path, |
| 543 | sourceBytes: identity.bytes, sourceModified: identity.modified, settings: format, |
| 544 | previewSeconds: preview, overwrite: overwrite, project: project, |
| 545 | timeline: timeline(project), duration: duration, usedFallback: fallback) |
| 546 | } |
| 547 | |
| 548 | private func creationResult(_ job: PulseMCPJobs.Job) throws -> Object { |
| 549 | guard let path = job.projectPath else { |
| 550 | throw PulseMCPError("PROJECT_NOT_FOUND", "The job does not have an editable project.") |
| 551 | } |
| 552 | let saved = try? access.authorize(path, in: [.output]) |
| 553 | defer { withExtendedLifetime(saved?.scope) {} } |
| 554 | guard saved != nil else { |
| 555 | throw PulseMCPError(job.errorCode ?? "PROJECT_NOT_FOUND", |
| 556 | job.errorMessage ?? "The editable project is unavailable in the authorized folder.") |
| 557 | } |
| 558 | return ["projectPath": path, "project": try projectDetails(job.project, duration: job.duration), |
| 559 | "job": jobs.details(job), "usedFallback": job.usedFallback] |
| 560 | } |
| 561 | |
| 562 | private func createMusicVideo(_ args: Object) async throws -> Object { |
| 563 | try require("editing"); try require("playback") |
| 564 | let key = args.string("requestKey"), signature = signature("create_music_video", args) |
| 565 | if let previous = try jobs.repeatJob(key: key, signature: signature) { return try creationResult(previous) } |
| 566 | try checkRevision(args) |
| 567 | let source = try authorizedAudio(args.string("songPath")) |
| 568 | let projectPath = try outputPath(args.string("projectPath"), extension: "pulsecanvas") |
| 569 | let output = try outputPath(args.string("outputPath"), extension: "mp4") |
| 570 | defer { withExtendedLifetime((source.scope, projectPath.scope, output.scope)) {} } |
| 571 | try jobs.checkCapacity(destination: output.url) |
| 572 | try PulseMCPJobs.checkDestination(output.url, overwrite: false) |
| 573 | try PulseMCPJobs.checkDestination(PulseMCPJobs.manifestURL(output.url), overwrite: false) |
| 574 | try PulseMCPJobs.checkDestination(projectPath.url, overwrite: false) |
| 575 | let format = try exportFormat(args) |
| 576 | let isPreview = args["previewOnly"] as? Bool == true |
| 577 | guard isPreview || args["previewSeconds"] == nil else { |
| 578 | throw PulseMCPError("INVALID_ARGUMENTS", "Set previewOnly to true to use previewSeconds.") |
| 579 | } |
| 580 | let prepared = try await prepare(source, args: args, permission: "editing") |
| 581 | try require("playback"); try require("rendering") |
| 582 | _ = try outputPath(projectPath.url.path, extension: "pulsecanvas") |
| 583 | _ = try outputPath(output.url.path, extension: "mp4") |
| 584 | let bars = args["barsPerScene"] as? Int ?? 4 |
| 585 | let seed = args["seed"] as? String ?? UUID().uuidString |
| 586 | var generator = PulseMCPSeed(seed) |
| 587 | let requested = try (args["visualizerIds"] as? [String] ?? []).map(scene) |
| 588 | var pool = requested.isEmpty ? library.availableScenes.filter(library.isFavorite) : requested |
| 589 | let fallback = pool.isEmpty |
| 590 | if fallback { |
| 591 | switch args.string("fallback") { |
| 592 | case "metal": pool = library.availableScenes.filter { library.preset(for: $0) == nil } |
| 593 | case "available": pool = library.availableScenes |
| 594 | default: throw PulseMCPError("EMPTY_STYLE_POOL", "Add a favorite, choose visualizer IDs, or request an explicit fallback.") |
| 595 | } |
| 596 | } |
| 597 | pool = Set(pool).sorted { library.identity(for: $0) < library.identity(for: $1) } |
| 598 | guard !pool.isEmpty else { throw PulseMCPError("EMPTY_STYLE_POOL", "Choose an installed visualizer.") } |
| 599 | pool.shuffle(using: &generator) |
| 600 | let grid = prepared.analyzer.segmentPlan(beatsPerSection: bars * 4) |
| 601 | let duration = prepared.analyzer.duration |
| 602 | let sections = StudioTimeline.sections(boundaries: grid.boundaries, bars: bars) { index, _ in pool[index % pool.count] } |
| 603 | try checkWholeSong(sections, duration: duration) |
| 604 | var appearances = studio.presets |
| 605 | for index in Set(sections.map(\.scene)) { |
| 606 | var settings = appearances[index] ?? library.favoriteAppearance(for: index) ?? .defaults(for: index) |
| 607 | settings.strobeEnabled = args["strobeEnabled"] as? Bool == true |
| 608 | appearances[index] = settings |
| 609 | } |
| 610 | let first = sections[0].scene |
| 611 | guard let aspect = SocialAspect.allCases.first(where: { $0.agentName == format.aspect }) else { |
| 612 | throw PulseMCPError("UNSUPPORTED_FORMAT", "Choose an aspect from get_capabilities.") |
| 613 | } |
| 614 | let bookmarked = try? prepared.access.readOnlyBookmark() |
| 615 | let project = CreatorProject(soundtrack: source.url, scene: first, appearance: appearances[first]!, |
| 616 | aspect: aspect.rawValue, resolution: format.resolution, fps: format.fps, timeline: sections, |
| 617 | studioEnabled: true, visualPresets: appearances, barsPerSection: bars, |
| 618 | effectIdentities: library.identities(for: Set(appearances.keys)), soundtrackBookmark: bookmarked, |
| 619 | loopPlayback: false, cloudProjectID: UUID().uuidString, generationSeed: seed) |
| 620 | let job = try makeJob(args: args, signature: signature, project: project, source: source.url, destination: output.url, |
| 621 | format: format, projectPath: projectPath.url.path, |
| 622 | preview: isPreview ? args["previewSeconds"] as? Double ?? 5 : nil, duration: duration, fallback: fallback) |
| 623 | try jobs.submit(job) |
| 624 | do { |
| 625 | try writeProject(project, to: projectPath.url, overwrite: false) |
| 626 | try install(prepared) |
| 627 | studio.applyDocument(project, aspect: aspect, audio: audio, render: render, exporter: exporter) |
| 628 | } catch { |
| 629 | jobs.failPreparation(job, error: error) |
| 630 | throw error |
| 631 | } |
| 632 | return try creationResult(job) |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | private extension Dictionary where Key == String, Value == Any { |
| 637 | func string(_ key: String) -> String { self[key] as? String ?? "" } |
| 638 | func double(_ key: String) -> Double { self[key] as? Double ?? 0 } |
| 639 | } |
| 640 | #endif |