@audiofool/moondog 0.3.0-beta.16 → 0.3.0-beta.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  <h1 align="center">Moondog</h1>
6
6
 
7
- <p align="center">Source candidate 0.3.0-beta.16</p>
7
+ <p align="center">Source candidate 0.3.0-beta.17</p>
8
8
 
9
9
  <p align="center"><strong>On the air, just for you.</strong></p>
10
10
 
@@ -172,7 +172,7 @@ Songs Moondog chose for you do not count as your own taste.
172
172
  | --- | --- |
173
173
  | A model through Pi | Conversation, discovery, and playlists built together. |
174
174
  | A web search service | `/web` lookups with links to their sources, through DeepSeek (`/auth deepseek`, which also reads pages), Brave Search (`/auth brave`), or your own signed-in Codex CLI. |
175
- | Spotify sign-in | Playback, and private playlists made only when you ask. |
175
+ | Spotify sign-in | Playback, and playlists made only when you ask. |
176
176
  | NetEase Music | Whole songs through its own `ncm-cli`, for listeners in mainland China. |
177
177
 
178
178
  Your profile never touches the network.
@@ -188,6 +188,7 @@ Read the [connection and data details](docs/TERMINAL_GUIDE.md) before you connec
188
188
  `/library save` keeps what is playing, and `/library play Night drive` plays a playlist on the service you chose.
189
189
  `/library import <link>` copies a Spotify, Apple Music, NetEase Music or QQ Music playlist into it.
190
190
  A playlist you made on Spotify also shapes your taste; for any other one, you decide.
191
+ `/library export Night drive` puts a copy of a playlist on Spotify, and exporting it again updates that copy.
191
192
 
192
193
  ## Music it makes
193
194
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@audiofool/moondog",
3
- "version": "0.3.0-beta.16",
3
+ "version": "0.3.0-beta.17",
4
4
  "type": "module",
5
5
  "description": "A local-first AI radio host, just for you.",
6
6
  "license": "Apache-2.0",
@@ -1046,6 +1046,8 @@ async function main() {
1046
1046
  process.stdout.write(
1047
1047
  `${options.json ? JSON.stringify(value, null, 2) : formatLocalResult(options.command, value)}\n`,
1048
1048
  );
1049
+ // A failed required check makes the checkup fail, so scripts can rely on it.
1050
+ if (options.command === "doctor" && !value.ok) process.exitCode = 1;
1049
1051
  return;
1050
1052
  }
1051
1053
 
@@ -592,20 +592,6 @@ const catalog = [
592
592
  label: N_("Change a Spotify playlist"),
593
593
  },
594
594
  },
595
- {
596
- id: "spotify.playlist.write",
597
- version: "1",
598
- state: "enabled",
599
- effect: "write_external",
600
- description:
601
- "Create one private Spotify playlist from the exact validated playlist plan explicitly requested by the user.",
602
- requires_spotify: true,
603
- requires_playlist_services: true,
604
- agent_tool: {
605
- name: "moondog_spotify_playlist_write",
606
- label: N_("Save the playlist to Spotify"),
607
- },
608
- },
609
595
  {
610
596
  id: "collection.list",
611
597
  version: "1",
@@ -661,6 +647,30 @@ const catalog = [
661
647
  label: N_("Play from the library"),
662
648
  },
663
649
  },
650
+ {
651
+ id: "collection.plan_save",
652
+ version: "1",
653
+ state: "enabled",
654
+ effect: "write_external",
655
+ description: "Keep the exact validated playlist plan as a playlist in the listener's library, and send it to Spotify as that playlist's copy when the listener names Spotify.",
656
+ requires_playlist_services: true,
657
+ agent_tool: {
658
+ name: "moondog_playlist_save",
659
+ label: N_("Save the playlist"),
660
+ },
661
+ },
662
+ {
663
+ id: "collection.export",
664
+ version: "1",
665
+ state: "enabled",
666
+ effect: "write_external",
667
+ description: "Export a playlist from the listener's library to Spotify as a playlist there, or bring the copy an earlier export made up to date.",
668
+ requires_spotify: true,
669
+ agent_tool: {
670
+ name: "moondog_collection_export",
671
+ label: N_("Export a playlist"),
672
+ },
673
+ },
664
674
  {
665
675
  id: "music.generate.local",
666
676
  version: "1",
@@ -7,6 +7,9 @@
7
7
  // tracks the listener kept, first in the list, never renamed or deleted. An entry keeps what names the song
8
8
  // (title, artist, album, ISRC) and the ids each service found for it, so the same playlist plays on whichever
9
9
  // service the listener chose, and any one service can be dropped without losing it.
10
+ //
11
+ // A playlist is made and arranged here. A service gets a copy when the listener exports it: library_exports keeps
12
+ // where that copy is and what it held, so the next export brings the same copy up to date instead of making another.
10
13
  import { randomUUID } from "node:crypto";
11
14
  import { chmod, mkdir } from "node:fs/promises";
12
15
  import path from "node:path";
@@ -53,6 +56,16 @@ const schema = `
53
56
  added_by TEXT NOT NULL,
54
57
  added_at TEXT NOT NULL
55
58
  ) STRICT;
59
+ CREATE TABLE IF NOT EXISTS library_exports (
60
+ playlist_id TEXT NOT NULL REFERENCES library_playlists(playlist_id) ON DELETE CASCADE,
61
+ provider TEXT NOT NULL,
62
+ remote_id TEXT NOT NULL,
63
+ url TEXT,
64
+ count INTEGER NOT NULL,
65
+ signature TEXT,
66
+ exported_at TEXT NOT NULL,
67
+ PRIMARY KEY (playlist_id, provider)
68
+ ) STRICT;
56
69
  CREATE INDEX IF NOT EXISTS library_entries_by_playlist ON library_entries(playlist_id, position);
57
70
  CREATE INDEX IF NOT EXISTS library_entries_by_made ON library_entries(made_id) WHERE made_id IS NOT NULL;
58
71
  `;
@@ -270,9 +283,12 @@ export class LibraryStore {
270
283
  const row = this.#database.prepare("SELECT * FROM library_playlists WHERE playlist_id = ?").get(String(id ?? ""));
271
284
  if (!row) return null;
272
285
  const entries = this.#database.prepare("SELECT * FROM library_entries WHERE playlist_id = ? ORDER BY position, added_at").all(row.playlist_id).map(entryOf);
286
+ const exports = this.#database.prepare("SELECT provider, remote_id, url, count, signature, exported_at FROM library_exports WHERE playlist_id = ? ORDER BY provider")
287
+ .all(row.playlist_id).map((copy) => ({ provider: copy.provider, id: copy.remote_id, url: copy.url ?? null, count: copy.count,
288
+ signature: copy.signature ?? null, exportedAt: copy.exported_at }));
273
289
  return { id: row.playlist_id, folderId: row.folder_id ?? null, name: row.name, origin: row.origin,
274
290
  ...(row.source_json ? { source: JSON.parse(row.source_json) } : {}), createdAt: row.created_at, updatedAt: row.updated_at,
275
- ...(row.playlist_id === SAVED_PLAYLIST_ID ? { saved: true } : {}), entries };
291
+ ...(row.playlist_id === SAVED_PLAYLIST_ID ? { saved: true } : {}), ...(exports.length ? { exports } : {}), entries };
276
292
  }
277
293
 
278
294
  /** Playlists whose names hold the words, best first, for the agent and the terminal. */
@@ -455,6 +471,22 @@ export class LibraryStore {
455
471
  });
456
472
  }
457
473
 
474
+ /**
475
+ * Keeps where a playlist's copy on a service is, after an export: the copy's id and link there, how many songs
476
+ * it took, and a signature of what it held, which tells a later export whether the copy was changed there.
477
+ */
478
+ rememberExport(playlistId, { provider, id, url, count, signature } = {}) {
479
+ return this.#transaction(() => {
480
+ const playlist = cleanId(playlistId, "Playlist");
481
+ this.#requirePlaylist(playlist);
482
+ this.#database.prepare(`INSERT INTO library_exports(playlist_id, provider, remote_id, url, count, signature, exported_at) VALUES (?, ?, ?, ?, ?, ?, ?)
483
+ ON CONFLICT(playlist_id, provider) DO UPDATE SET remote_id = excluded.remote_id, url = excluded.url, count = excluded.count,
484
+ signature = excluded.signature, exported_at = excluded.exported_at`)
485
+ .run(playlist, cleanId(provider, "Service"), cleanId(id, "Copy"), cleanText(url, 400, "Link", { optional: true }),
486
+ Number.isInteger(count) && count >= 0 ? count : 0, cleanText(signature, 128, "Signature", { optional: true }), this.#now());
487
+ });
488
+ }
489
+
458
490
  /** Moves entries, in their order, before another entry or to the end. */
459
491
  moveEntries(playlistId, entryIds, beforeId = null) {
460
492
  return this.#transaction(() => {
@@ -156,6 +156,11 @@ export function createPlayerNow() {
156
156
  if (event?.type === "queue" && Array.isArray(event.tracks)) { this.queued(event.tracks); return; }
157
157
  if (!queue) return;
158
158
  if (event?.type === "stopped") { queue = null; return; }
159
+ // A song the listener took out of Up next keeps its place, so the positions the player reports still match.
160
+ if (event?.type === "removed") {
161
+ if (Number.isInteger(event.position) && event.position > queue.index + 1 && event.position <= queue.tracks.length) queue.tracks[event.position - 1].removed = true;
162
+ return;
163
+ }
159
164
  if (Number.isInteger(event?.position) && event.position >= 1 && event.position <= queue.tracks.length) queue.index = event.position - 1;
160
165
  if (event?.type === "playing" || event?.type === "paused" || event?.type === "loading") queue.state = event.type;
161
166
  },
@@ -164,7 +169,7 @@ export function createPlayerNow() {
164
169
  },
165
170
  /** The song playing and every one after it, for keeping the whole queue: read() shows only ten. */
166
171
  remaining() {
167
- return queue ? queue.tracks.slice(queue.index).map((track) => ({ ...track })) : [];
172
+ return queue ? queue.tracks.slice(queue.index).filter((track) => !track.removed).map((track) => ({ ...track })) : [];
168
173
  },
169
174
  /** null when nothing is queued, or { state, song, position, count, next } with up to ten songs after it. */
170
175
  read() {
@@ -175,7 +180,7 @@ export function createPlayerNow() {
175
180
  song: { ...queue.tracks[queue.index] },
176
181
  position: queue.index + 1,
177
182
  count: queue.tracks.length,
178
- next: queue.tracks.slice(queue.index + 1, queue.index + 11).map((track) => ({ ...track })),
183
+ next: queue.tracks.slice(queue.index + 1).filter((track) => !track.removed).slice(0, 10).map((track) => ({ ...track })),
179
184
  };
180
185
  },
181
186
  };
@@ -152,30 +152,12 @@ function explicitQuickPlaylistIntent(text) {
152
152
  return match ? { action: "remove_track", playlistName: match[1], title: match[2], artist: match[3] } : null;
153
153
  }
154
154
 
155
- function spotifyPlaylistDetails({ name, description } = {}) {
156
- if (
157
- typeof name !== "string" ||
158
- name.trim().length < 1 ||
159
- Array.from(name).length > 100
160
- ) {
161
- throw spotifyResolutionError(
162
- "invalid_playlist_name",
163
- "The Spotify playlist name is invalid.",
164
- );
165
- }
166
- if (
167
- description !== undefined &&
168
- (typeof description !== "string" || Array.from(description).length > 200)
169
- ) {
170
- throw spotifyResolutionError(
171
- "invalid_playlist_description",
172
- "The Spotify playlist description is invalid.",
173
- );
155
+ // The name a saved plan's playlist takes: Spotify's limit of 100 characters, so its copy there carries the same name.
156
+ function planPlaylistName(name) {
157
+ if (typeof name !== "string" || name.trim().length < 1 || Array.from(name).length > 100) {
158
+ throw spotifyResolutionError("invalid_playlist_name", "The playlist name is invalid.");
174
159
  }
175
- return {
176
- name: name.trim(),
177
- ...(description !== undefined ? { description: description.trim() } : {}),
178
- };
160
+ return name.trim();
179
161
  }
180
162
 
181
163
  const requiredDomainServiceMethods = Object.freeze([
@@ -246,6 +228,8 @@ export const CONVERSATION_NAME_TIMEOUT_MS = 20_000;
246
228
  export class MoondogApplication {
247
229
  // Model calls naming conversations, stopped when the application closes.
248
230
  #naming = new Set();
231
+ // Up next's picks the window offers now, by reference (upNextProposals).
232
+ #proposals = new Map();
249
233
 
250
234
  constructor({
251
235
  importsRoot = resolveAppleMusicImportsRoot(),
@@ -945,31 +929,7 @@ export class MoondogApplication {
945
929
  if (service === "spotify") {
946
930
  if (!this.spotifyPlaybackReady()) throw Object.assign(new Error("Spotify is not ready to play here."), { code: "spotify_not_ready" });
947
931
  const list = songs.slice(0, 100);
948
- const refs = [];
949
- const avoidedFound = [];
950
- // A recording's own title and credit can name more than the entry does (a feature); an Avoid holds against it.
951
- const allowed = (title, credit) => this.avoidAllows({ title, artist_credit: credit });
952
- const uris = await mapLimited(list, 4, async (entry) => {
953
- // A cached recording plays without a search, once its own credit passes today's Avoids.
954
- if (entry.refs?.spotify_uri && entry.refs.spotify_credit) {
955
- if (allowed(entry.refs.spotify_title ?? entry.title, entry.refs.spotify_credit)) return entry.refs.spotify_uri;
956
- avoidedFound.push(entry.id);
957
- return null;
958
- }
959
- const { matched } = await this.spotifyResolveSongs([{ title: entry.title, artist: entry.artist_credit }], { signal }).catch(() => ({ matched: [] }));
960
- // A match reaches the model without its URI; the host keeps it under the match's reference.
961
- const ref = matched[0]?.item_ref_id;
962
- const known = ref ? this.spotifyHostReadItems().find((item) => item.item_ref_id === ref) : null;
963
- const uri = typeof known?.uri === "string" ? known.uri : typeof matched[0]?.uri === "string" ? matched[0].uri : null;
964
- if (!uri) return null;
965
- const title = known?.name ?? matched[0]?.name ?? entry.title;
966
- const credit = (known?.artists ?? matched[0]?.artists ?? []).join(", ") || entry.artist_credit;
967
- refs.push({ entryId: entry.id, refs: { spotify_uri: uri, spotify_title: title, spotify_credit: credit } });
968
- if (!allowed(title, credit)) { avoidedFound.push(entry.id); return null; }
969
- return uri;
970
- });
971
- signal?.throwIfAborted();
972
- this.libraryStore.rememberRefs(refs);
932
+ const { uris, avoidedFound } = await this.#spotifyUrisOf(list, { signal });
973
933
  const playable = uris.filter(Boolean);
974
934
  const skipped = avoided.length + avoidedFound.length;
975
935
  Object.assign(extra, skipped ? { skipped_avoided_count: skipped } : {});
@@ -992,6 +952,154 @@ export class MoondogApplication {
992
952
  throw Object.assign(new Error("No player here can play this playlist."), { code: "library_no_player" });
993
953
  }
994
954
 
955
+ // The Spotify recording of each library song, in the songs' order: the one a play or an export found before, or a
956
+ // search by title and artist, kept on the entry for next time. null stands for a song Spotify doesn't have or an
957
+ // Avoid holds back; avoidedFound names the second kind.
958
+ async #spotifyUrisOf(list, { signal } = {}) {
959
+ const refs = [];
960
+ const avoidedFound = [];
961
+ // A recording's own title and credit can name more than the entry does (a feature); an Avoid holds against it.
962
+ const allowed = (title, credit) => this.avoidAllows({ title, artist_credit: credit });
963
+ const uris = await mapLimited(list, 4, async (entry) => {
964
+ // A cached recording needs no search, once its own credit passes today's Avoids.
965
+ if (entry.refs?.spotify_uri && entry.refs.spotify_credit) {
966
+ if (allowed(entry.refs.spotify_title ?? entry.title, entry.refs.spotify_credit)) return entry.refs.spotify_uri;
967
+ avoidedFound.push(entry.id);
968
+ return null;
969
+ }
970
+ signal?.throwIfAborted();
971
+ const { matched } = await this.spotifyResolveSongs([{ title: entry.title, artist: entry.artist_credit }], { signal }).catch(() => ({ matched: [] }));
972
+ // A match reaches the model without its URI; the host keeps it under the match's reference.
973
+ const ref = matched[0]?.item_ref_id;
974
+ const known = ref ? this.spotifyHostReadItems().find((item) => item.item_ref_id === ref) : null;
975
+ const uri = typeof known?.uri === "string" ? known.uri : typeof matched[0]?.uri === "string" ? matched[0].uri : null;
976
+ if (!uri) return null;
977
+ const title = known?.name ?? matched[0]?.name ?? entry.title;
978
+ const credit = (known?.artists ?? matched[0]?.artists ?? []).join(", ") || entry.artist_credit;
979
+ refs.push({ entryId: entry.id, refs: { spotify_uri: uri, spotify_title: title, spotify_credit: credit } });
980
+ if (!allowed(title, credit)) { avoidedFound.push(entry.id); return null; }
981
+ return uri;
982
+ });
983
+ signal?.throwIfAborted();
984
+ this.libraryStore.rememberRefs(refs);
985
+ return { uris, avoidedFound };
986
+ }
987
+
988
+ /**
989
+ * Exports a library playlist to a music service, as a copy there. The playlist stays the listener's own, here;
990
+ * the copy follows it: the first export makes a playlist there, and a later one brings that same playlist up
991
+ * to date. A copy changed on the service since the last export is left alone (changed_on_service) until the
992
+ * listener says to replace it. Spotify is the service that takes a playlist so far. Tracks Moondog made have
993
+ * no recording there, so they stay out (left_out_made).
994
+ */
995
+ async exportLibraryPlaylist({ playlistId, service = "spotify", replace = false } = {}, { signal } = {}) {
996
+ const library = this.requireLibrary();
997
+ if (service !== "spotify") throw Object.assign(new Error("Only Spotify takes a playlist from the library so far."), { code: "library_export_unsupported" });
998
+ const playlist = library.playlist(playlistId);
999
+ if (!playlist) throw Object.assign(new Error("That playlist is not in the library."), { code: "library_playlist_not_found" });
1000
+ const named = { id: playlist.id, name: playlist.saved ? "Saved" : playlist.name };
1001
+ if (!this.spotifyReady()) throw Object.assign(new Error("Connect Spotify first, so Moondog can make a playlist there."), { code: "spotify_not_ready" });
1002
+ this.requireSpotifyWriteScopes(["playlist-modify-private"]);
1003
+ const songs = playlist.entries.filter((entry) => entry.kind === "song");
1004
+ const leftOut = playlist.entries.length - songs.length;
1005
+ const avoided = songs.filter((entry) => !this.avoidAllows({ title: entry.title, artist_credit: entry.artist_credit }));
1006
+ const list = songs.filter((entry) => !avoided.includes(entry));
1007
+ const found = await this.#spotifyUrisOf(list, { signal });
1008
+ // A song the playlist holds twice, or two entries Spotify answers with one recording, goes over once.
1009
+ const uris = [...new Set(found.uris.filter(Boolean))];
1010
+ const skipped = avoided.length + found.avoidedFound.length;
1011
+ const counts = { not_found: found.uris.filter((uri) => !uri).length - found.avoidedFound.length, left_out_made: leftOut,
1012
+ ...(skipped ? { skipped_avoided_count: skipped } : {}) };
1013
+ if (!uris.length) return { state: songs.length ? "not_found" : "empty", service, playlist: named, ...counts };
1014
+ const previous = playlist.exports?.find((copy) => copy.provider === service);
1015
+ const remember = (copy) => library.rememberExport(playlist.id, { provider: service, id: copy.playlistId,
1016
+ url: `https://open.spotify.com/playlist/${copy.playlistId}`, count: copy.track_count, signature: copy.signature });
1017
+ this.invalidateSpotifyQuickEditContext();
1018
+ let receipt;
1019
+ try {
1020
+ receipt = await this.requireSpotifyService().exportPlaylist({ name: named.name, uris, replace: replace === true,
1021
+ ...(previous ? { previous: { playlistId: previous.id, signature: previous.signature } } : {}) }, { signal });
1022
+ } catch (error) {
1023
+ if (error?.exportedCopy) remember(error.exportedCopy);
1024
+ throw error;
1025
+ }
1026
+ if (receipt.state === "changed_on_spotify") {
1027
+ return { state: "changed_on_service", service, playlist: named, url: previous.url, on_service: receipt.playlist.track_count, would_export: uris.length, ...counts };
1028
+ }
1029
+ remember({ playlistId: receipt.playlist_id, track_count: uris.length, signature: receipt.signature });
1030
+ return { state: receipt.state, service, playlist: named, url: `https://open.spotify.com/playlist/${receipt.playlist_id}`, exported: uris.length, ...counts };
1031
+ }
1032
+
1033
+ // Up next's picks: when the songs queued run low, the host picks what could come next (choose, the
1034
+ // conversation's model), and only the songs found playable on the player that plays now, past the listener's
1035
+ // Avoids, are offered. where is that player: "moondog" (Moondog's own, for Apple Music), "spotify" or "netease".
1036
+ // Each pick keeps what the player needs under a reference, so a click queues it without searching again.
1037
+ async upNextProposals({ playing, next = [], offered = [], where } = {}, { choose, signal } = {}) {
1038
+ const ready = where === "moondog" ? this.playbackService === "apple_music" && Boolean(this.musicCatalog) && typeof this.musicPreviewPlayer?.enqueue === "function"
1039
+ : where === "spotify" ? this.playbackService === "spotify" && this.spotifyPlaybackReady()
1040
+ : where === "netease" ? this.playbackService === "netease" && this.neteaseReady() : false;
1041
+ if (!ready || typeof choose !== "function" || !playing?.title) return [];
1042
+ const profile = await this.getListenerProfile().then(compactListenerProfile).catch(() => null);
1043
+ const brief = profile?.summary ? JSON.stringify({ summary: profile.summary, claims: (profile.claims ?? []).slice(0, 8),
1044
+ ...(profile.listener_choices ? { listener_choices: profile.listener_choices } : {}) }) : null;
1045
+ const picks = await choose({ playing, next, offered, profile: brief });
1046
+ signal?.throwIfAborted();
1047
+ const taken = new Set([playing, ...next].map((track) => `${track?.title ?? ""}`.toLowerCase()));
1048
+ const found = [];
1049
+ for (const pick of picks) {
1050
+ if (found.length >= 3) break;
1051
+ if (taken.has(pick.title.toLowerCase()) || !this.avoidAllows({ title: pick.title, artist_credit: pick.artist })) continue;
1052
+ const song = await this.#findUpNext(where, pick, { signal }).catch(() => null);
1053
+ signal?.throwIfAborted();
1054
+ if (!song || !this.avoidAllows({ title: song.title, artist_credit: song.artists.join(", "), artists: song.artists })) continue;
1055
+ taken.add(song.title.toLowerCase());
1056
+ const ref = `p${this.#proposals.size}-${Date.now().toString(36)}`;
1057
+ this.#proposals.set(ref, { where, ...song });
1058
+ while (this.#proposals.size > 30) this.#proposals.delete(this.#proposals.keys().next().value);
1059
+ found.push({ ref, title: song.title, artists: song.artists, image: song.image ?? null });
1060
+ }
1061
+ return found;
1062
+ }
1063
+
1064
+ async #findUpNext(where, { title, artist }, { signal } = {}) {
1065
+ if (where === "moondog") {
1066
+ const result = await this.musicCatalog.findPreview({ title, artist });
1067
+ if (result?.state !== "resolved") return null;
1068
+ const track = result.track;
1069
+ return { title: track.title, artists: [track.artist_credit].filter(Boolean), image: track.artwork_url ?? null, track };
1070
+ }
1071
+ if (where === "spotify") {
1072
+ const { matched } = await this.spotifyResolveSongs([{ title, artist }], { signal });
1073
+ const ref = matched[0]?.item_ref_id;
1074
+ const known = ref ? this.spotifyHostReadItems().find((item) => item.item_ref_id === ref) : null;
1075
+ const uri = typeof known?.uri === "string" ? known.uri : typeof matched[0]?.uri === "string" ? matched[0].uri : null;
1076
+ if (!uri) return null;
1077
+ return { title: known?.name ?? matched[0].name ?? title, artists: known?.artists ?? matched[0].artists ?? [artist], image: known?.image ?? null, uri };
1078
+ }
1079
+ const song = await this.requireNetease().find({ title, artist, intent: "为听者挑接下来的歌" });
1080
+ return song ? { title: song.title, artists: song.artists, image: song.image ?? null, id: song.id } : null;
1081
+ }
1082
+
1083
+ /** One of Up next's picks, added after what is queued on its player; it goes in the ledger as Moondog's suggestion. */
1084
+ async queueUpNextProposal(ref, { signal } = {}) {
1085
+ const song = this.#proposals.get(String(ref ?? ""));
1086
+ if (!song) return { state: "gone" };
1087
+ this.#proposals.delete(String(ref));
1088
+ if (song.where === "moondog") {
1089
+ if (!this.musicPreviewPlayer.enqueue(song.track)) return { state: "not_playing" };
1090
+ this.#noteSuggestions("apple_music", [{ action: "apple_music.queue.up_next", providerTrackId: song.track.catalog_id ? `apple_music:${song.track.catalog_id}` : null,
1091
+ isrc: song.track.isrc, title: song.title, artistCredit: song.track.artist_credit }]);
1092
+ return { state: "queued" };
1093
+ }
1094
+ if (song.where === "spotify") {
1095
+ await this.requireSpotifyService().addToQueue({ uri: song.uri }, { signal });
1096
+ this.#noteSuggestions("spotify", [{ action: "queue.up_next", providerTrackId: song.uri, title: song.title, artists: song.artists }]);
1097
+ return { state: "queued" };
1098
+ }
1099
+ const receipt = await this.playNetease({ items: [{ id: song.id }], mode: "queue", intent: "加入听者的接下来" });
1100
+ return { state: ["queued", "playing"].includes(receipt?.mode) ? "queued" : "not_found" };
1101
+ }
1102
+
995
1103
  // Makes one instrumental track from the listener's taste and plays it in Moondog's own player.
996
1104
  // The agent proposes sound descriptors, each with its source; the taste compiler keeps only the
997
1105
  // ones it can trace and none that names an artist or a song. The track and its receipt stay on
@@ -3718,30 +3826,6 @@ export class MoondogApplication {
3718
3826
  }
3719
3827
  }
3720
3828
 
3721
- async spotifyCreatePlaylist({ name, description, trackRefs } = {}, { signal } = {}) {
3722
- signal?.throwIfAborted();
3723
- this.requireSpotifyPlaylistCreationFlow();
3724
- if (
3725
- !Array.isArray(trackRefs) ||
3726
- !Array.isArray(this.validatedPlaylistTrackRefs) ||
3727
- trackRefs.length !== this.validatedPlaylistTrackRefs.length ||
3728
- trackRefs.some(
3729
- (trackRefId, index) =>
3730
- trackRefId !== this.validatedPlaylistTrackRefs[index],
3731
- )
3732
- ) {
3733
- throw spotifyResolutionError(
3734
- "spotify_playlist_plan_required",
3735
- "Spotify playlist writes require the exact validated playlist plan from this prompt.",
3736
- );
3737
- }
3738
- const details = spotifyPlaylistDetails({ name, description });
3739
- this.requireSpotifyWriteScopes(["playlist-modify-private"]);
3740
- const uris = this.requireSpotifyTrackUris(trackRefs);
3741
- const planned = new Map((this.pendingSpotifyPlaylist?.plan?.tracks ?? []).map((track) => [track.track_ref_id, track]));
3742
- return this.writeSpotifyPlaylist(details, uris, { signal, tracks: trackRefs.map((ref) => planned.get(ref) ?? null) });
3743
- }
3744
-
3745
3829
  pendingSpotifyPlaylistStatus() {
3746
3830
  const plan = this.pendingSpotifyPlaylist?.plan;
3747
3831
  if (!plan) return { state: "none" };
@@ -3781,44 +3865,63 @@ export class MoondogApplication {
3781
3865
  return structuredClone(this.pendingSpotifyPlaylist.plan);
3782
3866
  }
3783
3867
 
3784
- async spotifyCreatePendingPlaylist({ name, description } = {}, { signal } = {}) {
3868
+ /**
3869
+ * Keeps the validated playlist plan as a playlist in the listener's library, which is where a playlist is made
3870
+ * and arranged. The plan is this prompt's own (trackRefs, in its exact order) or the pending one the listener
3871
+ * approved. toSpotify also sends the new playlist to Spotify as its copy, through the library's export, so a
3872
+ * later export brings that same copy up to date. The library keeps the playlist even when the copy fails.
3873
+ * onSaved hears of the library playlist before anything is sent.
3874
+ */
3875
+ async savePlaylistPlan({ name, trackRefs, pending = false, toSpotify = false } = {}, { signal, onSaved } = {}) {
3785
3876
  signal?.throwIfAborted();
3786
3877
  this.requireSpotifyPlaylistCreationFlow();
3787
- if (!this.pendingSpotifyPlaylist) {
3788
- throw spotifyResolutionError(
3789
- "spotify_pending_playlist_unavailable",
3790
- "There is no pending validated playlist plan to save. Create a playlist plan first.",
3791
- );
3878
+ if (!pending && (!Array.isArray(trackRefs) || !Array.isArray(this.validatedPlaylistTrackRefs) ||
3879
+ trackRefs.length !== this.validatedPlaylistTrackRefs.length ||
3880
+ trackRefs.some((trackRefId, index) => trackRefId !== this.validatedPlaylistTrackRefs[index]))) {
3881
+ throw spotifyResolutionError("spotify_playlist_plan_required", "A playlist is saved from the exact validated playlist plan of this prompt.");
3792
3882
  }
3793
- const details = spotifyPlaylistDetails({ name, description });
3794
- this.requireSpotifyScopes(["user-read-private"]);
3795
- this.requireSpotifyWriteScopes(["playlist-modify-private"]);
3796
3883
  const draft = this.pendingSpotifyPlaylist;
3884
+ if (!draft?.plan) {
3885
+ throw spotifyResolutionError("spotify_pending_playlist_unavailable", "There is no pending validated playlist plan to save. Create a playlist plan first.");
3886
+ }
3887
+ const playlistName = planPlaylistName(name);
3888
+ const library = this.requireLibrary();
3797
3889
  const { kept, avoided } = this.#withoutAvoidedPlanTracks(draft.plan.tracks);
3798
- const result = await this.requireSpotifyResolver().resolve(
3799
- keptTrusted(draft, kept),
3800
- { signal },
3801
- );
3802
- signal?.throwIfAborted();
3803
- const resolvedByRef = new Map();
3804
- for (const resolution of result.resolutions ?? []) {
3805
- if (resolution.status === "resolved" && resolution.spotify?.uri) {
3806
- resolvedByRef.set(
3807
- resolution.track_ref_id,
3808
- resolution.spotify.uri,
3809
- );
3890
+ // For the copy, the resolver finds each song's Spotify recording from the plan's own track, which knows more
3891
+ // than a title and an artist. A song it can't place is searched by name at the export, and counted there.
3892
+ const uris = new Map();
3893
+ if (toSpotify && this.spotifyReady() && this.spotifyConnection?.resolver && draft.trustedTracks) {
3894
+ const result = await this.requireSpotifyResolver().resolve(keptTrusted(draft, kept), { signal })
3895
+ .catch((error) => (signal?.aborted ? Promise.reject(error) : { resolutions: [] }));
3896
+ for (const resolution of result.resolutions ?? []) {
3897
+ if (resolution.status === "resolved" && typeof resolution.spotify?.uri === "string") uris.set(resolution.track_ref_id, resolution.spotify.uri);
3810
3898
  }
3811
3899
  }
3812
- const uris = kept.map((track) =>
3813
- resolvedByRef.get(track.track_ref_id),
3814
- );
3815
- if (uris.some((uri) => typeof uri !== "string")) {
3816
- throw spotifyResolutionError(
3817
- "spotify_pending_playlist_unresolved",
3818
- "The pending playlist could not be fully resolved on Spotify, so no playlist was created.",
3819
- );
3900
+ signal?.throwIfAborted();
3901
+ if (this.pendingPlaylistPromptTransaction) this.pendingPlaylistPromptTransaction.playlistWriteAttempted = true;
3902
+ const made = library.savePlaylist({ name: playlistName, origin: "moondog", addedBy: "moondog", entries: kept.map((track) => ({
3903
+ kind: "song", title: track.title, artist_credit: track.artist_credit, ...(track.release ? { album: track.release } : {}),
3904
+ ...(uris.has(track.track_ref_id) ? { refs: { spotify_uri: uris.get(track.track_ref_id), spotify_title: track.title, spotify_credit: track.artist_credit } } : {}),
3905
+ })) });
3906
+ // Moondog chose these songs, so they go in the ledger under the service the listener plays them on.
3907
+ this.#noteSuggestions(toSpotify ? "spotify" : this.playbackService, kept.map((track) => ({ action: "playlist.write",
3908
+ ...(uris.has(track.track_ref_id) ? { providerTrackId: uris.get(track.track_ref_id) } : {}), title: track.title, artistCredit: track.artist_credit })));
3909
+ // The plan is a playlist now, so a cancelled prompt does not bring it back as pending.
3910
+ if (this.pendingPlaylistPromptTransaction) this.pendingPlaylistPromptTransaction.externalized = true;
3911
+ this.pendingSpotifyPlaylist = null;
3912
+ this.pendingPlaylistRevisionCandidateSet = null;
3913
+ const saved = { playlist: { id: made.id, name: library.playlist(made.id).name, track_count: made.added }, ...skippedAvoided(avoided) };
3914
+ onSaved?.(structuredClone(saved));
3915
+ if (!toSpotify) return saved;
3916
+ try {
3917
+ const sent = await this.exportLibraryPlaylist({ playlistId: made.id, service: "spotify" }, { signal });
3918
+ return { ...saved, spotify: { state: sent.state, ...(Number.isInteger(sent.exported) ? { exported: sent.exported } : {}), not_found: sent.not_found ?? 0 } };
3919
+ } catch (error) {
3920
+ if (signal?.aborted) throw error;
3921
+ // The playlist is in the library either way; the copy can be sent again with an export.
3922
+ return { ...saved, spotify: { state: error?.outcomeUnknown === true ? "unknown" : "failed",
3923
+ code: /^[a-z][a-z0-9_]{1,63}$/u.test(error?.code ?? "") ? error.code : "spotify_export_failed" } };
3820
3924
  }
3821
- return this.writeSpotifyPlaylist(details, uris, { signal, tracks: kept, avoided });
3822
3925
  }
3823
3926
 
3824
3927
  async spotifyPlayPendingPlan({ deviceId } = {}, { signal } = {}) {
@@ -4003,41 +4106,6 @@ export class MoondogApplication {
4003
4106
  ...(signal?.aborted ? { cancelled: true } : {}) };
4004
4107
  }
4005
4108
 
4006
- async writeSpotifyPlaylist(details, uris, { signal, tracks = [], avoided: leftOut = [] } = {}) {
4007
- signal?.throwIfAborted();
4008
- this.requireSpotifyPlaylistCreationFlow();
4009
- const { kept, avoided } = this.#withoutAvoidedPlanTracks(tracks);
4010
- if (avoided.length) {
4011
- uris = uris.filter((_uri, index) => kept.includes(tracks[index]));
4012
- tracks = kept;
4013
- }
4014
- if (this.pendingPlaylistPromptTransaction) this.pendingPlaylistPromptTransaction.playlistWriteAttempted = true;
4015
- this.invalidateSpotifyQuickEditContext();
4016
- try {
4017
- const receipt = await this.requireSpotifyService().createPlaylistWithTracks({
4018
- ...details,
4019
- uris,
4020
- }, { signal });
4021
- this.#noteSuggestions("spotify", tracks.flatMap((track, index) => track ? [{ action: "playlist.write",
4022
- providerTrackId: uris[index], title: track.title, artistCredit: track.artist_credit }] : []));
4023
- if (this.pendingPlaylistPromptTransaction) {
4024
- this.pendingPlaylistPromptTransaction.externalized = true;
4025
- }
4026
- this.pendingSpotifyPlaylist = null;
4027
- this.pendingPlaylistRevisionCandidateSet = null;
4028
- return { ...receipt, ...skippedAvoided([...leftOut, ...avoided]) };
4029
- } catch (error) {
4030
- if (error?.outcomeUnknown === true || ["playlist_created_without_tracks", "playlist_created_tracks_unknown"].includes(error?.code)) {
4031
- if (this.pendingPlaylistPromptTransaction) {
4032
- this.pendingPlaylistPromptTransaction.externalized = true;
4033
- }
4034
- this.pendingSpotifyPlaylist = null;
4035
- this.pendingPlaylistRevisionCandidateSet = null;
4036
- }
4037
- throw error;
4038
- }
4039
- }
4040
-
4041
4109
  async spotifySaveLibraryTracks({ trackRefs } = {}, { signal } = {}) {
4042
4110
  signal?.throwIfAborted();
4043
4111
  this.requireSpotifyWriteScopes(["user-library-modify"]);
@@ -4588,6 +4656,11 @@ export class MoondogApplication {
4588
4656
  const source = await this.sourceStatus();
4589
4657
  const profile = await this.profileStatus();
4590
4658
  const spotify = this.spotifyStatus();
4659
+ // A new install has imported nothing yet. That is a state to explain, not a failed check.
4660
+ const noLibrary = !this.profileServicesReady() && source.state === "missing" &&
4661
+ [null, "projection_subject_unavailable"].includes(this.domainServicesError);
4662
+ const similarityReady = this.musicSimilarityReady();
4663
+ const similarityWaits = noLibrary && !similarityReady && this.musicSimilarity !== null;
4591
4664
  const checks = [
4592
4665
  ...["search", "read"].map((kind) => {
4593
4666
  const lookup = this.webLookup(kind);
@@ -4607,14 +4680,15 @@ export class MoondogApplication {
4607
4680
  {
4608
4681
  id: "apple_music.source",
4609
4682
  ok: ["ready", "degraded"].includes(source.state),
4610
- state: source.state,
4611
- optional_for_local_commands: profile.state === "ready",
4683
+ state: noLibrary ? "no_library" : source.state,
4684
+ optional_for_local_commands: noLibrary || profile.state === "ready",
4612
4685
  },
4613
4686
  {
4614
4687
  id: "profile.projection",
4615
4688
  ok: profile.state === "ready",
4616
- state: profile.state,
4617
- ...(profile.error ? { error: profile.error } : {}),
4689
+ state: noLibrary ? "no_library" : profile.state,
4690
+ ...(profile.error && !noLibrary ? { error: profile.error } : {}),
4691
+ ...(noLibrary ? { optional_for_local_commands: true } : {}),
4618
4692
  },
4619
4693
  {
4620
4694
  id: "agent.runtime",
@@ -4624,8 +4698,9 @@ export class MoondogApplication {
4624
4698
  },
4625
4699
  {
4626
4700
  id: "music.discovery.open_similarity",
4627
- ok: this.musicSimilarityReady(),
4628
- state: this.musicSimilarityReady() ? "configured" : "unavailable",
4701
+ ok: similarityReady,
4702
+ state: similarityReady ? "configured" : similarityWaits ? "waiting_for_library" : "unavailable",
4703
+ ...(similarityWaits ? { optional_for_local_commands: true } : {}),
4629
4704
  },
4630
4705
  {
4631
4706
  id: "external.effects",
@@ -4662,6 +4737,7 @@ export class MoondogApplication {
4662
4737
  ok: checks
4663
4738
  .filter((check) => !check.optional_for_local_commands)
4664
4739
  .every((check) => check.ok),
4740
+ ...(noLibrary ? { library: "none" } : {}),
4665
4741
  checks,
4666
4742
  };
4667
4743
  }