@audiofool/moondog 0.3.0-beta.9 → 0.3.0

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.
Files changed (66) hide show
  1. package/README.md +40 -12
  2. package/package.json +5 -4
  3. package/scripts/moondog.mjs +47 -9
  4. package/src/core/apple-projection-domain-services.mjs +4 -0
  5. package/src/core/capability-catalog.mjs +46 -14
  6. package/src/core/host.mjs +30 -0
  7. package/src/core/library-store.mjs +82 -6
  8. package/src/core/listening-now.mjs +7 -2
  9. package/src/core/listening-profile-domain-services.mjs +4 -0
  10. package/src/core/moondog-application.mjs +412 -144
  11. package/src/i18n/messages/de.mjs +4 -3
  12. package/src/i18n/messages/en.mjs +4 -3
  13. package/src/i18n/messages/es.mjs +4 -3
  14. package/src/i18n/messages/fr.mjs +4 -3
  15. package/src/i18n/messages/it.mjs +4 -3
  16. package/src/i18n/messages/ja.mjs +4 -3
  17. package/src/i18n/messages/ko.mjs +4 -3
  18. package/src/i18n/messages/pt.mjs +4 -3
  19. package/src/i18n/messages/zh-Hant.mjs +4 -3
  20. package/src/i18n/messages/zh.mjs +4 -3
  21. package/src/i18n/screen/es.mjs +52 -6
  22. package/src/i18n/screen/ja.mjs +52 -6
  23. package/src/i18n/screen/pt.mjs +52 -6
  24. package/src/i18n/screen/zh.mjs +52 -6
  25. package/src/importers/zip-reader.mjs +61 -0
  26. package/src/integrations/apple-music/music-app.mjs +3 -2
  27. package/src/integrations/lastfm/history.mjs +2 -1
  28. package/src/integrations/lyrics/lrclib.mjs +1 -1
  29. package/src/integrations/netease/ncm-cli-player.mjs +62 -20
  30. package/src/integrations/open-music-similarity/artist-radio.mjs +3 -3
  31. package/src/integrations/playlist-links.mjs +114 -0
  32. package/src/integrations/public-playlists.mjs +41 -8
  33. package/src/integrations/spotify/account-data-history.mjs +63 -57
  34. package/src/integrations/spotify/authentication.mjs +2 -22
  35. package/src/integrations/spotify/extended-streaming-history.mjs +48 -40
  36. package/src/integrations/spotify/history-archive.mjs +2 -13
  37. package/src/integrations/spotify/service.mjs +88 -58
  38. package/src/integrations/spotify/web-api-client.mjs +12 -4
  39. package/src/integrations/user-agent.mjs +6 -0
  40. package/src/integrations/web/codex-web.mjs +3 -1
  41. package/src/integrations/web/deepseek-web.mjs +1 -1
  42. package/src/integrations/web/web-research.mjs +84 -17
  43. package/src/integrations/web/web-result.mjs +60 -12
  44. package/src/integrations/youtube-music/takeout.mjs +11 -16
  45. package/src/profile/history-import.mjs +3 -1
  46. package/src/profile/listening-history-store.mjs +55 -1
  47. package/src/profile/listening-profile-projection.mjs +1 -1
  48. package/src/profile/music-import-bundle.mjs +3 -1
  49. package/src/profile/music-providers.mjs +3 -0
  50. package/src/runtime/pi/agent-runtime.mjs +244 -146
  51. package/src/runtime/pi/configured-runtime.mjs +3 -0
  52. package/src/runtime/pi/image-input.mjs +148 -0
  53. package/src/runtime/pi/model-roles.mjs +121 -0
  54. package/src/runtime/pi/model-settings.mjs +112 -6
  55. package/src/runtime/pi/model-transport.mjs +9 -0
  56. package/src/runtime/pi/moondog-model.mjs +158 -0
  57. package/src/runtime/pi/next-songs.mjs +71 -0
  58. package/src/runtime/pi/persistent-credential-store.mjs +2 -0
  59. package/src/runtime/pi/public-model-catalog.mjs +10 -3
  60. package/src/runtime/pi/runtime-settings.mjs +7 -3
  61. package/src/surfaces/cli/brand-components.mjs +1 -1
  62. package/src/surfaces/cli/command-completions.mjs +43 -3
  63. package/src/surfaces/cli/format-output.mjs +19 -7
  64. package/src/surfaces/cli/invite-command.mjs +65 -0
  65. package/src/surfaces/cli/model-roles-command.mjs +60 -0
  66. package/src/surfaces/cli/tui.mjs +87 -5
package/README.md CHANGED
@@ -4,9 +4,9 @@
4
4
 
5
5
  <h1 align="center">Moondog</h1>
6
6
 
7
- <p align="center">Source candidate 0.3.0-beta.9</p>
7
+ <p align="center">Version 0.3.0</p>
8
8
 
9
- <p align="center"><strong>A listening room that shows its work.</strong></p>
9
+ <p align="center"><strong>On the air, just for you.</strong></p>
10
10
 
11
11
  <p align="center">
12
12
  <img src="assets/demo/moondog-tui-home.png" width="1000" alt="Moondog's listening room in charcoal: a lunar record beside the wordmark, a four-line tracklist, and the line Is there anybody out there">
@@ -14,11 +14,11 @@
14
14
 
15
15
  <p align="center"><sub>The real TUI, in charcoal, with fictional listening data.</sub></p>
16
16
 
17
- Moondog is a listening room in your terminal.
17
+ Moondog is a radio host just for you, and it works from a listening room in your terminal or on your Mac.
18
18
  It reads the history your music services already keep, and turns it into a profile you can open, question, and correct.
19
19
  The profile works without a model, an API key, or a music-service login.
20
- When you want company, an agent can talk music with you, find songs you have not heard, and shape a playlist.
21
- Your data stays on your machine.
20
+ When you want company, it can talk music with you, find songs you have not heard, shape a playlist, and on a Mac go on air with music it makes itself.
21
+ It shows its work, and your data stays on your machine.
22
22
  The room is built on [Pi](https://github.com/earendil-works/pi).
23
23
 
24
24
  ## Open the room
@@ -33,18 +33,21 @@ npm ci
33
33
  npm start
34
34
  ```
35
35
 
36
- [@audiofool/moondog](https://www.npmjs.com/package/@audiofool/moondog) 0.2.2 is the published package; `npm install --global @audiofool/moondog` installs it.
36
+ [@audiofool/moondog](https://www.npmjs.com/package/@audiofool/moondog) 0.3.0 is the published package; `npm install --global @audiofool/moondog` installs it.
37
37
  To see the agent work through fictional data, with no sign-in at all, run `npm run demo` from the checkout.
38
38
 
39
39
  The source version supports `moondog update` and `/update`, with stable (`latest`) and preview (`beta`) channels.
40
40
  Startup checks show a quiet notification; installation happens only when you request it.
41
41
  See [updating and release channels](docs/UPDATES.md), including the one-time upgrade needed for the older npm 0.1.0 package.
42
42
 
43
- ## Other ways in
43
+ ## On your Mac
44
44
 
45
- [Moondog for Mac](app/README.md) is a native window on the same core as the terminal room.
45
+ [Moondog desktop](app/README.md) is a native window on the same core as the terminal room, with build targets for macOS (Apple silicon), Windows (x64), and Linux (x64).
46
46
  It shares your profile, settings, sign-ins, and conversations with `moondog`, and draws its own conversation, now playing, and up next.
47
- Run it from this checkout with `cd app && npm ci && npm start`.
47
+ Download the notarized build for Apple silicon from the [project page](https://moondog.audiofool.ai), or run it from this checkout with `cd app && npm ci && npm start`.
48
+ It updates itself, on a Stable or Beta channel you choose in Settings.
49
+ The Windows and Linux desktop builds use Spotify playback and Apple Music previews; full Apple Music songs and reading the Music app require macOS.
50
+ Windows support applies to the desktop app; the terminal launcher and its updater remain supported on macOS and Linux.
48
51
 
49
52
  The [project page](https://moondog.audiofool.ai) plays a short scene in this window, in a browser, with a made-up listener ([how](site/README.md)).
50
53
 
@@ -147,11 +150,17 @@ OpenAI takes your ChatGPT subscription or an API key.
147
150
  In the Mac app, any service that speaks OpenAI's or Anthropic's API can be added as an endpoint by its address, and `/endpoint` does it in the terminal.
148
151
  You can switch models in the middle of a conversation.
149
152
  The [model setup guide](docs/TERMINAL_GUIDE.md#enable-agent-conversation) lists each provider and the environment variable it reads.
153
+ `/model roles` shows the models and services behind side tasks: a vision model for images, and the web search service.
154
+ Moondog takes images too: an image path in your message in the terminal, or a pasted or dropped image in the Mac app.
155
+ You can also change settings in your own words, such as which model answers or the language it replies in.
150
156
 
151
157
  While an answer is on the way, each step appears in the conversation as it starts.
152
158
  The steps stay above the reply, with a count of what finished, what failed, and what was not confirmed.
153
159
  The agent can use musical knowledge and web research to find candidates, then verify the recordings on Spotify before playing or queueing them.
154
160
  Without Spotify, it plays 30-second Apple Music previews from the terminal instead, each next to a link to the full song.
161
+ With NetEase Music, it plays whole songs through NetEase's own `ncm-cli`.
162
+ In the Mac app, Apple Music plays whole songs with a subscription.
163
+ `/service` chooses where Moondog plays.
155
164
  It also sees what you already play: the song and playlist in the Music app on a Mac, or on Spotify's active device, so “more like this playlist” needs no names.
156
165
  macOS asks once before Moondog may read the Music app.
157
166
  For example, “Pon doce de salsa clásica a la cola” asks it to add up to twelve verified songs directly; your history guides the choice without limiting it to your library.
@@ -163,14 +172,30 @@ Songs Moondog chose for you do not count as your own taste.
163
172
  | --- | --- |
164
173
  | A model through Pi | Conversation, discovery, and playlists built together. |
165
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. |
166
- | 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
+ | NetEase Music | Whole songs through its own `ncm-cli`, for listeners in mainland China. |
167
177
 
168
178
  Your profile never touches the network.
169
179
  The agent talks only to the services you set up.
170
180
  `/web` sends the question or the link you give it, and nothing from your profile, history, or files.
181
+ An image you attach goes to the model that reads it.
171
182
  A Spotify ZIP does not need a Spotify sign-in.
172
183
  Read the [connection and data details](docs/TERMINAL_GUIDE.md) before you connect anything.
173
184
 
185
+ ## Your library
186
+
187
+ `/library` keeps songs and the tracks Moondog made side by side: Saved, then your playlists.
188
+ `/library save` keeps what is playing, and `/library play Night drive` plays a playlist on the service you chose.
189
+ `/library import <link>` copies a Spotify, Apple Music, NetEase Music or QQ Music playlist into it.
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.
192
+
193
+ ## Music it makes
194
+
195
+ On an Apple silicon Mac, Moondog can make instrumental tracks offline with Stable Audio 3, powered by Stability AI.
196
+ `/generation download medium` sets it up after you agree to its licenses, and `/generation on` turns it on.
197
+ Ask for a track, or type `/onair` and Moondog keeps making music from your taste until you stop it.
198
+
174
199
  ## Getting around
175
200
 
176
201
  | Command or key | What it does |
@@ -186,7 +211,10 @@ Read the [connection and data details](docs/TERMINAL_GUIDE.md) before you connec
186
211
  | Enter while Moondog is working | Queue the next message. It sends when this one finishes. |
187
212
  | `/resume`, `/new` | Pick up a saved conversation, or start a fresh one. |
188
213
  | `/home` | Back to the sleeve, without clearing the conversation. |
189
- | `/skip`, `/stop` | Skip to the next song preview, or stop the previews. |
214
+ | `/skip`, `/stop` | Skip to the next song preview or stream track, or stop them. |
215
+ | `/library` | Your saved songs and playlists. |
216
+ | `/onair` | Go on air, or come off it. |
217
+ | `/rewind`, `/branch` | Change an earlier message, or go on in a new conversation. |
190
218
  | `/lyrics` | See which line is on the sleeve, and which song it came from. |
191
219
  | `/theme paper` | Black ink on white. |
192
220
  | `/theme charcoal` | Moonlight on a black sky. |
@@ -213,4 +241,4 @@ Your profile, and anything Moondog remembers, carry over.
213
241
 
214
242
  Moondog is open source under the [Apache License 2.0](LICENSE).
215
243
  Copyright 2026 Audiofool.
216
- Music making runs Stable Audio 3, which you install yourself; [NOTICE](NOTICE) holds its attribution, and [licenses/](licenses/stability-ai-community-license.md) holds the Stability AI Community License.
244
+ Music making runs Stable Audio 3, which Moondog downloads from Stability AI when you ask, or your own install; [NOTICE](NOTICE) holds its attribution, and [licenses/](licenses/stability-ai-community-license.md) holds the Stability AI Community License.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@audiofool/moondog",
3
- "version": "0.3.0-beta.9",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
- "description": "Local-first personal AI music agent.",
5
+ "description": "A local-first AI radio host, just for you.",
6
6
  "license": "Apache-2.0",
7
7
  "keywords": [
8
8
  "ai-agent",
@@ -63,7 +63,7 @@
63
63
  "verify": "npm run verify:release-tree && npm run verify:demo-history && npm run verify:demo && npm run verify:community && npm run verify:package && npm run validate:contracts && npm test",
64
64
  "doctor": "node --disable-warning=ExperimentalWarning scripts/moondog.mjs doctor",
65
65
  "validate:contracts": "node scripts/validate-contracts.mjs",
66
- "test": "node --test tests/contracts/*.test.mjs tests/core/*.test.mjs tests/importers/*.test.mjs tests/runtime/*.test.mjs"
66
+ "test": "node --test tests/contracts/*.test.mjs tests/core/*.test.mjs tests/importers/*.test.mjs tests/runtime/*.test.mjs gateway/tests/*.test.mjs"
67
67
  },
68
68
  "dependencies": {
69
69
  "@earendil-works/pi-agent-core": "1.0.1",
@@ -71,7 +71,8 @@
71
71
  "@earendil-works/pi-tui": "1.0.1",
72
72
  "ajv": "8.20.0",
73
73
  "ajv-formats": "3.0.1",
74
- "plist": "5.0.0"
74
+ "plist": "5.0.0",
75
+ "yauzl": "3.4.0"
75
76
  },
76
77
  "devDependencies": {
77
78
  "yaml": "2.9.0"
@@ -1,8 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { execFile } from "node:child_process";
4
- import { promisify } from "node:util";
5
3
  import { createApplicationUpdater } from "../src/core/application-update.mjs";
4
+ import { openInDefaultBrowser } from "../src/core/host.mjs";
6
5
  import { runUpdateCommand } from "../src/surfaces/cli/update-command.mjs";
7
6
 
8
7
  import { MoondogApplication } from "../src/core/moondog-application.mjs";
@@ -28,11 +27,13 @@ import {
28
27
  } from "../src/surfaces/cli/format-output.mjs";
29
28
  import { runAuthCommand } from "../src/surfaces/cli/auth-command.mjs";
30
29
  import { runEndpointCommand } from "../src/surfaces/cli/endpoint-command.mjs";
30
+ import { runInviteCommand } from "../src/surfaces/cli/invite-command.mjs";
31
31
  import { runDataCommand } from "../src/surfaces/cli/data-command.mjs";
32
32
  import { runCatalogCommand } from "../src/surfaces/cli/catalog-command.mjs";
33
33
  import { runProfileCommand } from "../src/surfaces/cli/profile-command.mjs";
34
34
  import { runListenerProfileCommand, savedProfileActions } from "../src/surfaces/cli/listener-profile-command.mjs";
35
35
  import { createWebResearch } from "../src/integrations/web/web-research.mjs";
36
+ import { runModelRolesCommand } from "../src/surfaces/cli/model-roles-command.mjs";
36
37
  import { runWebCommand } from "../src/surfaces/cli/web-command.mjs";
37
38
  import { openSpotifyConnection } from "../src/integrations/spotify/connection.mjs";
38
39
  import { preferredIdleDevice, thisComputerName } from "../src/integrations/spotify/service.mjs";
@@ -45,6 +46,7 @@ import {
45
46
  import { runSpotifyCommand } from "../src/surfaces/cli/spotify-command.mjs";
46
47
  import { runListenBrainzCommand } from "../src/surfaces/cli/listenbrainz-command.mjs";
47
48
  import { openListeningHistoryStore } from "../src/profile/listening-history-store.mjs";
49
+ import { musicHash, prepareMusicBundle } from "../src/profile/music-import-bundle.mjs";
48
50
  import { commitSpotifyQuickImport, prepareHistoryImport, prepareSpotifyQuickImport } from "../src/profile/history-import.mjs";
49
51
  import { persistAppleLibraryImport, refreshAppleLibraryImport } from "../src/profile/apple-library-import.mjs";
50
52
  import { IMPORT_GUIDE_URLS } from "../src/surfaces/cli/import-guides.mjs";
@@ -150,6 +152,28 @@ function parseArguments(argv) {
150
152
  };
151
153
  }
152
154
 
155
+ // A playlist imported into the library adds its songs to the listener's taste evidence, as a kept playlist, the
156
+ // same way a public playlist imported from the Import guide does. Its source names where it came from.
157
+ const PLAYLIST_TASTE_SOURCES = { spotify: "spotify_playlist", apple_music: "apple_music_playlist", netease: "netease", qq_music: "qq_music" };
158
+ async function addPlaylistToTaste(found) {
159
+ const provider = PLAYLIST_TASTE_SOURCES[found.provider];
160
+ if (!provider) throw new Error("This playlist's service can't shape the profile.");
161
+ const historyStore = await openListeningHistoryStore();
162
+ try {
163
+ const appleSubjectId = await optionalAppleMusicSubjectId();
164
+ const subjectId = historyStore.localSubjectId({ ...(appleSubjectId ? { preferredSubjectId: appleSubjectId } : {}), create: true });
165
+ const rows = found.tracks.map((track, index) => ({ id: track.id, title: track.title, artist: track.artist, ...(track.album ? { album: track.album } : {}),
166
+ playlistId: found.id, playlistName: found.name, position: index + 1, member: "playlist-link.json", listenerMade: found.owned === true }));
167
+ const bytes = Buffer.from(JSON.stringify({ provider, id: found.id, name: found.name, rows }));
168
+ const prepared = prepareMusicBundle({ provider, subjectId, capturedAt: new Date().toISOString(), rows, digest: musicHash(bytes), size: bytes.length,
169
+ members: ["playlist-link.json"], fileName: found.name,
170
+ scopeNote: "A playlist the listener imported into their library. It shows what they keep, not what they played." });
171
+ return historyStore.ingestImport(prepared.bundle);
172
+ } finally {
173
+ historyStore.close();
174
+ }
175
+ }
176
+
153
177
  async function optionalAppleMusicSubjectId() {
154
178
  const source = await readAppleMusicSourceStatus();
155
179
  if (source.state === "missing") return null;
@@ -383,9 +407,7 @@ async function prepareTuiHistoryImport(filePath, { recentPage, librarySnapshot,
383
407
  async function openImportHelp(destination) {
384
408
  const url = IMPORT_GUIDE_URLS[destination];
385
409
  if (!url) throw new Error("Unknown import guide.");
386
- await promisify(execFile)(process.platform === "darwin" ? "open" : "xdg-open", [url], {
387
- timeout: 10_000,
388
- });
410
+ await openInDefaultBrowser(url);
389
411
  }
390
412
 
391
413
  function tasteCoverage(profile) {
@@ -746,6 +768,11 @@ async function main() {
746
768
  return;
747
769
  }
748
770
 
771
+ if (options.command === "invite") {
772
+ await runInviteCommand({ args: options.rest, json: options.json });
773
+ return;
774
+ }
775
+
749
776
  if (options.command === "spotify") {
750
777
  await runSpotifySurface({
751
778
  args: options.rest,
@@ -974,6 +1001,8 @@ async function main() {
974
1001
  domainServices, domainServicesError, spotifyConnection, locale, playbackService, playbackSelection, languageSelection, modelSwitch,
975
1002
  webResearch, memoryStore, musicCatalog, musicPreviewPlayer: previewPlayer, neteasePlayer, localGenerator, atmosphereStream, musicSimilarity, artistIdentityResolver,
976
1003
  spotifyTopArtists, musicApp, libraryStore,
1004
+ // A playlist that shapes the taste reloads the profile services at once, so the evidence counts in this session.
1005
+ playlistTaste: async (found) => { const receipt = await addPlaylistToTaste(found); replaceDomainServices(await loadDomainServices()); return receipt; },
977
1006
  });
978
1007
  const application = new MoondogApplication(applicationOptions({
979
1008
  ...domainState, spotifyConnection, locale: await resolveListenerLocale(), playbackService,
@@ -1023,6 +1052,8 @@ async function main() {
1023
1052
  process.stdout.write(
1024
1053
  `${options.json ? JSON.stringify(value, null, 2) : formatLocalResult(options.command, value)}\n`,
1025
1054
  );
1055
+ // A failed required check makes the checkup fail, so scripts can rely on it.
1056
+ if (options.command === "doctor" && !value.ok) process.exitCode = 1;
1026
1057
  return;
1027
1058
  }
1028
1059
 
@@ -1210,10 +1241,14 @@ async function main() {
1210
1241
  // The desktop window lists models and signs in here, with no terminal.
1211
1242
  modelSettings,
1212
1243
  // A model chosen or a sign-in made on the other surface. Model variables fix the model at
1213
- // launch, so a saved choice has nothing to change then.
1214
- watchModelSettings: (onChange) => (process.env.MOONDOG_PROVIDER !== undefined || process.env.MOONDOG_MODEL !== undefined
1215
- ? () => {}
1216
- : watchRuntimeSettings({ environment: process.env, onChange })),
1244
+ // launch, so a saved choice has nothing to change then; a role chosen elsewhere still does.
1245
+ watchModelSettings: (onChange) => {
1246
+ const fixed = process.env.MOONDOG_PROVIDER !== undefined || process.env.MOONDOG_MODEL !== undefined;
1247
+ return watchRuntimeSettings({ environment: process.env, onChange: (selection, changed) => {
1248
+ if (changed === "roles") return void webResearch.refresh().then(() => onChange(selection, changed), () => {});
1249
+ if (!fixed) onChange(selection, changed);
1250
+ } });
1251
+ },
1217
1252
  // The one-time music service and model setup, shared by the terminal and the window.
1218
1253
  firstRun: createFirstRun({ environment: process.env }),
1219
1254
  // A host with its own terminal streams takes the sign-in prompts. The
@@ -1238,7 +1273,10 @@ async function main() {
1238
1273
  progressOutput: host.terminalStreams.output,
1239
1274
  }),
1240
1275
  }),
1276
+ // The room says what came of an invite code in its own words, so the command prints nothing.
1277
+ runInvite: (args) => runInviteCommand({ args, output: { write() {} }, settings: modelSettings }),
1241
1278
  runWeb: (args, options) => runWebCommand({ args, webResearch, ...options }),
1279
+ runModelRoles: (args) => runModelRolesCommand({ args: args.map(String), modelSettings, webResearch }),
1242
1280
  runProfileAction: (args) => runProfileCommand({
1243
1281
  args,
1244
1282
  commandPrefix: "/profile",
@@ -1296,6 +1296,10 @@ export class AppleProjectionDomainServices {
1296
1296
  return this.#listeningHistoryStore?.recentAttention?.({ subjectId: this.#subjectId }) ?? null;
1297
1297
  }
1298
1298
 
1299
+ listeningDays() {
1300
+ return this.#listeningHistoryStore?.listeningDays?.({ subjectId: this.#subjectId }) ?? null;
1301
+ }
1302
+
1299
1303
  // Moondog's suggestions ledger and the declared mix (src/profile/moondog-suggestions.mjs).
1300
1304
  recordMoondogSuggestions(entries) {
1301
1305
  return this.#listeningHistoryStore?.recordMoondogSuggestions?.({ entries }) ?? null;
@@ -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",
@@ -628,6 +614,28 @@ const catalog = [
628
614
  label: N_("Save to the library"),
629
615
  },
630
616
  },
617
+ {
618
+ id: "collection.edit",
619
+ version: "1",
620
+ state: "enabled",
621
+ effect: "write_local",
622
+ description: "Rename one of the listener's playlists on this Mac, take songs out of it, or move songs within it, when they ask.",
623
+ agent_tool: {
624
+ name: "moondog_collection_edit",
625
+ label: N_("Change a playlist"),
626
+ },
627
+ },
628
+ {
629
+ id: "collection.import",
630
+ version: "1",
631
+ state: "enabled",
632
+ effect: "write_local",
633
+ description: "Import a playlist link from Spotify, Apple Music, NetEase Music or QQ Music into the listener's library on this Mac.",
634
+ agent_tool: {
635
+ name: "moondog_collection_import",
636
+ label: N_("Import a playlist"),
637
+ },
638
+ },
631
639
  {
632
640
  id: "collection.play",
633
641
  version: "1",
@@ -639,6 +647,30 @@ const catalog = [
639
647
  label: N_("Play from the library"),
640
648
  },
641
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
+ },
642
674
  {
643
675
  id: "music.generate.local",
644
676
  version: "1",
@@ -0,0 +1,30 @@
1
+ // What differs between the operating systems the core runs on: the environment's PATH key and
2
+ // how a link opens in the listener's browser.
3
+ import { spawn } from "node:child_process";
4
+
5
+ /** Windows spells the PATH variable as it likes (often "Path"); the others use PATH. */
6
+ export function environmentPathKey(environment) {
7
+ return Object.keys(environment).find((key) => key.toUpperCase() === "PATH") ?? "PATH";
8
+ }
9
+
10
+ /** Opens a link in the default browser, and resolves once the opener has started. */
11
+ export function openInDefaultBrowser(url, platform = process.platform) {
12
+ const [command, args] =
13
+ platform === "darwin"
14
+ ? ["open", [url]]
15
+ : platform === "win32"
16
+ ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
17
+ : ["xdg-open", [url]];
18
+ return new Promise((resolve, reject) => {
19
+ const child = spawn(command, args, {
20
+ detached: true,
21
+ stdio: "ignore",
22
+ windowsHide: true,
23
+ });
24
+ child.once("error", reject);
25
+ child.once("spawn", () => {
26
+ child.unref();
27
+ resolve();
28
+ });
29
+ });
30
+ }
@@ -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";
@@ -16,7 +19,7 @@ export const LIBRARY_SCHEMA_VERSION = 1;
16
19
  export const SAVED_PLAYLIST_ID = "saved";
17
20
  export const MAX_DEPTH = 4;
18
21
  export const MAX_ENTRIES = 2000;
19
- const ORIGINS = new Set(["listener", "moondog", "spotify", "apple_music", "netease", "file"]);
22
+ const ORIGINS = new Set(["listener", "moondog", "spotify", "apple_music", "netease", "qq_music", "file"]);
20
23
  const ADDERS = new Set(["listener", "moondog"]);
21
24
 
22
25
  export const resolveLibraryPath = (environment = process.env) => path.join(resolveMoondogStateDirectory(environment), "library.sqlite");
@@ -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
  `;
@@ -125,6 +138,38 @@ const entryOf = (row) => ({
125
138
  added_at: row.added_at,
126
139
  });
127
140
 
141
+ // A word that goes on past a name is another word: @Night is not in @Nightfall. Chinese and Japanese run on without spaces, so they end it.
142
+ const WORD = /[\p{Script=Latin}\p{N}]/u;
143
+ // Saved goes by its name in each of the window's languages.
144
+ const SAVED_NAMES = ["Saved", "收藏", "保存済み", "저장됨", "Guardadas", "Enregistrés", "Gespeichert", "Salvas", "Salvati"];
145
+
146
+ /**
147
+ * The playlists and folders a listener's messages name with @, newest message first. A longer name wins over one
148
+ * it starts with, so @Night drive is not also @Night.
149
+ */
150
+ export function libraryMentions({ folders = [], playlists = [] } = {}, texts = [], { limit = 5 } = {}) {
151
+ const names = [
152
+ ...playlists.flatMap((playlist) => (playlist.saved ? SAVED_NAMES : [playlist.name]).map((name) => ({ kind: "playlist", id: playlist.id, name }))),
153
+ ...folders.map((folder) => ({ kind: "folder", id: folder.id, name: folder.name })),
154
+ ].sort((a, b) => b.name.length - a.name.length);
155
+ const found = new Map();
156
+ for (const text of [...texts].reverse()) {
157
+ let rest = String(text ?? "").toLowerCase();
158
+ if (!rest.includes("@")) continue;
159
+ for (const { kind, id, name } of names) {
160
+ const wanted = `@${name.toLowerCase()}`;
161
+ for (let at = rest.indexOf(wanted); at >= 0; at = rest.indexOf(wanted, at + 1)) {
162
+ const end = at + wanted.length;
163
+ if ((at > 0 && WORD.test(rest[at - 1])) || (end < rest.length && WORD.test(rest[end]) && WORD.test(wanted.at(-1)))) continue;
164
+ if (!found.has(`${kind}:${id}`)) found.set(`${kind}:${id}`, { kind, id });
165
+ rest = rest.slice(0, at) + " ".repeat(wanted.length) + rest.slice(end);
166
+ break;
167
+ }
168
+ }
169
+ }
170
+ return [...found.values()].slice(0, limit);
171
+ }
172
+
128
173
  export class LibraryStore {
129
174
  #database;
130
175
  #clock;
@@ -204,8 +249,9 @@ export class LibraryStore {
204
249
  }
205
250
 
206
251
  /**
207
- * The tree the sidebar draws: folders, and playlists with their counts and a cover (the first entry's
208
- * artwork, or the first made track, whose cover the window draws), Saved among them.
252
+ * The tree the sidebar draws: folders, and playlists with their counts and a cover (the playlist's own from
253
+ * where it was imported, else the first entry's artwork or the first made track, whose cover the window draws),
254
+ * Saved among them.
209
255
  */
210
256
  view() {
211
257
  this.#open();
@@ -220,12 +266,13 @@ export class LibraryStore {
220
266
  }
221
267
  return null;
222
268
  };
223
- const playlists = this.#database.prepare(`SELECT p.playlist_id, p.folder_id, p.name, p.origin, p.position, p.updated_at,
269
+ const ownCover = (row) => (row.source_json ? JSON.parse(row.source_json).cover : null);
270
+ const playlists = this.#database.prepare(`SELECT p.playlist_id, p.folder_id, p.name, p.origin, p.source_json, p.position, p.updated_at,
224
271
  (SELECT COUNT(*) FROM library_entries e WHERE e.playlist_id = p.playlist_id) AS count,
225
272
  (SELECT COUNT(*) FROM library_entries e WHERE e.playlist_id = p.playlist_id AND e.kind = 'made') AS made
226
273
  FROM library_playlists p`).all()
227
274
  .map((row) => ({ id: row.playlist_id, folderId: row.folder_id ?? null, name: row.name, origin: row.origin, position: row.position,
228
- updatedAt: row.updated_at, count: row.count, made: row.made, cover: coverOf(row.playlist_id),
275
+ updatedAt: row.updated_at, count: row.count, made: row.made, cover: ownCover(row) ? { artwork_url: ownCover(row) } : coverOf(row.playlist_id),
229
276
  ...(row.playlist_id === SAVED_PLAYLIST_ID ? { saved: true } : {}) }));
230
277
  return { folders, playlists };
231
278
  }
@@ -236,9 +283,12 @@ export class LibraryStore {
236
283
  const row = this.#database.prepare("SELECT * FROM library_playlists WHERE playlist_id = ?").get(String(id ?? ""));
237
284
  if (!row) return null;
238
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 }));
239
289
  return { id: row.playlist_id, folderId: row.folder_id ?? null, name: row.name, origin: row.origin,
240
290
  ...(row.source_json ? { source: JSON.parse(row.source_json) } : {}), createdAt: row.created_at, updatedAt: row.updated_at,
241
- ...(row.playlist_id === SAVED_PLAYLIST_ID ? { saved: true } : {}), entries };
291
+ ...(row.playlist_id === SAVED_PLAYLIST_ID ? { saved: true } : {}), ...(exports.length ? { exports } : {}), entries };
242
292
  }
243
293
 
244
294
  /** Playlists whose names hold the words, best first, for the agent and the terminal. */
@@ -411,6 +461,32 @@ export class LibraryStore {
411
461
  });
412
462
  }
413
463
 
464
+ /** An imported playlist's own cover, found after it came in. */
465
+ setPlaylistCover(playlistId, cover) {
466
+ return this.#transaction(() => {
467
+ const id = cleanId(playlistId, "Playlist");
468
+ const row = this.#database.prepare("SELECT source_json FROM library_playlists WHERE playlist_id = ?").get(id);
469
+ if (!row?.source_json) return;
470
+ this.#database.prepare("UPDATE library_playlists SET source_json = ? WHERE playlist_id = ?").run(JSON.stringify({ ...JSON.parse(row.source_json), cover }), id);
471
+ });
472
+ }
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
+
414
490
  /** Moves entries, in their order, before another entry or to the end. */
415
491
  moveEntries(playlistId, entryIds, beforeId = null) {
416
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
  };
@@ -506,6 +506,10 @@ export class ListeningProfileDomainServices {
506
506
  return this.#store.recentAttention?.({ subjectId: this.#subjectId }) ?? null;
507
507
  }
508
508
 
509
+ listeningDays() {
510
+ return this.#store.listeningDays?.({ subjectId: this.#subjectId }) ?? null;
511
+ }
512
+
509
513
  // Moondog's suggestions ledger and the declared mix (src/profile/moondog-suggestions.mjs).
510
514
  recordMoondogSuggestions(entries) {
511
515
  return this.#store.recordMoondogSuggestions?.({ entries }) ?? null;