@audiofool/moondog 0.4.0-beta.2 → 0.4.0-beta.4

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 (96) hide show
  1. package/README.md +19 -8
  2. package/package.json +1 -1
  3. package/scripts/moondog.mjs +130 -106
  4. package/src/core/apple-library-source-status.mjs +64 -18
  5. package/src/core/apple-projection-domain-services.mjs +67 -52
  6. package/src/core/capability-catalog.mjs +18 -2
  7. package/src/core/import-source-history.mjs +28 -0
  8. package/src/core/library-draft.mjs +16 -0
  9. package/src/core/library-names.mjs +12 -0
  10. package/src/core/library-store.mjs +361 -23
  11. package/src/core/listener-avoids.mjs +31 -0
  12. package/src/core/listening-action.mjs +41 -0
  13. package/src/core/listening-moment.mjs +67 -0
  14. package/src/core/listening-now.mjs +69 -28
  15. package/src/core/listening-profile-domain-services.mjs +32 -18
  16. package/src/core/listening-scope.mjs +119 -0
  17. package/src/core/moondog-application.mjs +1045 -270
  18. package/src/core/play-follower.mjs +104 -0
  19. package/src/core/portable-playlist.mjs +125 -0
  20. package/src/core/profile-discovery-draft.mjs +35 -0
  21. package/src/core/track-title.mjs +70 -4
  22. package/src/i18n/import-history.mjs +647 -0
  23. package/src/i18n/messages/de.mjs +3 -3
  24. package/src/i18n/messages/en.mjs +3 -3
  25. package/src/i18n/messages/es.mjs +3 -3
  26. package/src/i18n/messages/fr.mjs +3 -3
  27. package/src/i18n/messages/it.mjs +3 -3
  28. package/src/i18n/messages/ja.mjs +3 -3
  29. package/src/i18n/messages/ko.mjs +3 -3
  30. package/src/i18n/messages/pt.mjs +3 -3
  31. package/src/i18n/messages/zh-Hant.mjs +3 -3
  32. package/src/i18n/messages/zh.mjs +3 -3
  33. package/src/i18n/screen/es.mjs +90 -26
  34. package/src/i18n/screen/ja.mjs +89 -25
  35. package/src/i18n/screen/pt.mjs +90 -26
  36. package/src/i18n/screen/zh.mjs +89 -25
  37. package/src/importers/apple-music-library/import-batch.mjs +64 -32
  38. package/src/importers/apple-music-library/normalize.mjs +36 -6
  39. package/src/importers/apple-music-library/save-time.mjs +17 -0
  40. package/src/importers/zip-reader.mjs +24 -2
  41. package/src/integrations/apple-music/catalog-playlist-reader.mjs +111 -0
  42. package/src/integrations/apple-music/catalog.mjs +84 -25
  43. package/src/integrations/apple-music/music-app-listening.mjs +107 -0
  44. package/src/integrations/apple-music/music-app.mjs +6 -2
  45. package/src/integrations/apple-music/song-id.mjs +13 -0
  46. package/src/integrations/apple-music/terminal-preview-player.mjs +154 -44
  47. package/src/integrations/listenbrainz/history-file.mjs +63 -35
  48. package/src/integrations/netease/ncm-cli-player.mjs +355 -68
  49. package/src/integrations/netease/queue-occurrence.mjs +138 -0
  50. package/src/integrations/playlist-links.mjs +93 -30
  51. package/src/integrations/public-playlists.mjs +21 -15
  52. package/src/integrations/spotify/account-data-history.mjs +9 -10
  53. package/src/integrations/spotify/account-data-profile.mjs +1 -0
  54. package/src/integrations/spotify/extended-streaming-history.mjs +57 -52
  55. package/src/integrations/spotify/history-archive.mjs +8 -18
  56. package/src/integrations/spotify/library-snapshot.mjs +2 -1
  57. package/src/integrations/spotify/service.mjs +29 -11
  58. package/src/integrations/spotify/web-api-client.mjs +2 -2
  59. package/src/integrations/stable-audio/local-generator.mjs +13 -5
  60. package/src/integrations/youtube-music/takeout.mjs +12 -8
  61. package/src/memory/local-memory-store.mjs +479 -27
  62. package/src/memory/reflection-worker.mjs +19 -0
  63. package/src/profile/apple-library-import.mjs +56 -2
  64. package/src/profile/history-import.mjs +58 -27
  65. package/src/profile/listener-corrections.mjs +2 -4
  66. package/src/profile/listener-profile-build.mjs +133 -46
  67. package/src/profile/listener-profile-store.mjs +57 -4
  68. package/src/profile/listener-profile-verification.mjs +11 -5
  69. package/src/profile/listener-profile-worker.mjs +36 -10
  70. package/src/profile/listening-history-store.mjs +975 -354
  71. package/src/profile/listening-profile-projection.mjs +130 -160
  72. package/src/profile/local-file-import.mjs +172 -0
  73. package/src/profile/moondog-suggestions.mjs +40 -11
  74. package/src/profile/profile-exploration.mjs +36 -6
  75. package/src/profile/recorded-measures.mjs +5 -0
  76. package/src/profile/spotify-archive-taste.mjs +41 -65
  77. package/src/runtime/pi/agent-runtime.mjs +368 -221
  78. package/src/runtime/pi/custom-endpoints.mjs +30 -8
  79. package/src/runtime/pi/memory-agent-runtime.mjs +45 -3
  80. package/src/runtime/pi/moondog-model.mjs +6 -0
  81. package/src/runtime/pi/playback-rules.mjs +100 -0
  82. package/src/runtime/pi/profile-build-runtime.mjs +85 -24
  83. package/src/surfaces/cli/brand-components.mjs +9 -6
  84. package/src/surfaces/cli/command-completions.mjs +8 -1
  85. package/src/surfaces/cli/format-output.mjs +207 -34
  86. package/src/surfaces/cli/history-import-view.mjs +130 -21
  87. package/src/surfaces/cli/listenbrainz-command.mjs +7 -2
  88. package/src/surfaces/cli/listener-profile-command.mjs +67 -8
  89. package/src/surfaces/cli/listening-menu.mjs +3 -0
  90. package/src/surfaces/cli/profile-command.mjs +1 -0
  91. package/src/surfaces/cli/spotify-command.mjs +17 -25
  92. package/src/surfaces/cli/taste-period.mjs +22 -0
  93. package/src/surfaces/cli/taste-profile-model.mjs +52 -32
  94. package/src/surfaces/cli/tui.mjs +557 -170
  95. package/src/surfaces/html/tasteprint.mjs +181 -93
  96. package/src/surfaces/import-source-history.mjs +80 -0
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  <h1 align="center">Moondog</h1>
6
6
 
7
- <p align="center">Version 0.4.0-beta.2</p>
7
+ <p align="center">Version 0.4.0-beta.4</p>
8
8
 
9
9
  <p align="center"><strong>On the air, just for you.</strong></p>
10
10
 
@@ -92,7 +92,8 @@ Moondog shows you what is inside before anything is saved, and the original file
92
92
 
93
93
  The [terminal guide](docs/TERMINAL_GUIDE.md#import-and-inspect-listening-history) has every format.
94
94
 
95
- With a model connected, Moondog writes a reading of everything you imported, usually in a few minutes.
95
+ With a model connected, choose **Build reading** in the desktop Taste page or enter `/profile build` in the terminal.
96
+ Moondog writes a reading of the imported evidence, usually in a few minutes.
96
97
  It names the threads in your listening, keeps what you played apart from what you saved, and marks its interpretations as interpretations.
97
98
  A second pass checks the draft for contradictions and invented claims, and the build fixes what it finds before saving.
98
99
 
@@ -112,6 +113,18 @@ Find a song or artist, see why it is there, and choose **I like this** or **Keep
112
113
  You can also say it to the host, for example “never play this again”.
113
114
  `/taste report` walks the years one song at a time and ends on what play counts can never tell anyone; you can keep it as a private page that works offline.
114
115
 
116
+ ## What it learns
117
+
118
+ Moondog also learns a small set of working practices from finished conversations.
119
+ A practice is a procedure, not a taste claim: for example, how you asked for the first picks in an open request.
120
+ Only an explicit instruction, quoted exactly from your own words, can become one automatically.
121
+ It is kept in the same local database as memory, with every revision, and never grants a new capability or permission.
122
+
123
+ A new conversation sees only the practice names and descriptions.
124
+ The full instructions load when the current request needs one.
125
+ Open them with `moondog skills list` and `moondog skills show <name>`, turn one off with `moondog skills archive <name>`, and bring it back with `moondog skills restore <name>`.
126
+ The learned practices note records the transaction, validation, and limits.
127
+
115
128
  ## On the air
116
129
 
117
130
  Ask for music in your own words, in any of ten languages.
@@ -120,7 +133,9 @@ What it reads about the wider music world stays separate from what it knows abou
120
133
  Under a set of songs, one line names the mix: how many you know well, how many come back after a while, and how many are new to you.
121
134
 
122
135
  - **Up next.** The desktop player shows the queue: play a song now, or take one out. When it runs low, the host offers a few picks.
123
- - **Your library.** Saved songs, your playlists, and the tracks Moondog made sit side by side. Import a Spotify, Apple Music, NetEase Music, or QQ Music playlist by its link, and export a playlist to Spotify.
136
+ - **Your library.** Saved songs, your playlists, and the tracks Moondog made sit side by side.
137
+ Import a playlist from Spotify, Apple Music, NetEase Music, or QQ Music by its link.
138
+ Export a copy to Spotify, or choose **Export playlist files…** to keep an M3U8, a JSON playlist, and the available audio for tracks Moondog made.
124
139
  - **Music it makes.** Ask for an instrumental and Moondog can write a score and play it on its built-in synthesizer.
125
140
  For Stable Audio 3, powered by Stability AI, choose Medium or Small Music in Settings › Playback or use `/generation download medium`.
126
141
  After you accept the licenses and download a model, it runs offline on Apple silicon, Windows x64, or Linux x64 or ARM64.
@@ -145,7 +160,7 @@ Tab on an empty input steps onto the tracklist, and Ctrl+P searches every comman
145
160
  | `/import` | Bring your history. |
146
161
  | `/library` | Your saved songs and playlists. |
147
162
  | `/onair` | Go on air, or come off it. |
148
- | `/skip`, `/stop` | Skip to the next song or stream track, or stop. |
163
+ | `/skip`, `/stop` | Skip the current track or stop playback. On Spotify, `/stop` pauses the active device. |
149
164
  | `/resume`, `/new` | Pick up a saved conversation, or start a fresh one. |
150
165
  | `/rewind`, `/branch` | Change an earlier message, or go on in a new conversation. |
151
166
  | `/home` | Back to the sleeve, without clearing the conversation. |
@@ -169,10 +184,6 @@ Read the [connection and data details](docs/TERMINAL_GUIDE.md) before you connec
169
184
  - [Project page](site/README.md): how the page plays the scene in the app's real window, in a browser, on made-up data.
170
185
  - [Private Tasteprint](docs/PRIVATE_TASTEPRINT.md): what the evidence can support, and what a report reveals about you.
171
186
  - [Product charter](docs/PRODUCT_CHARTER.md) and [public roadmap](docs/ROADMAP.md): where Moondog is headed, and what it will not do.
172
- - [Voice](docs/VOICE.md): how Moondog talks, and where Pink Floyd shows up.
173
- - [The listening loop](docs/LISTENING_LOOP.md): how the agent keeps your choices, your recent listening, and its own picks apart.
174
- - [The agent harness](docs/AGENT_HARNESS.md): how the tools keep the model's part small, so every supported model can play what you ask.
175
- - [Runtime architecture](docs/ADR_0001_AGENT_RUNTIME_AND_CLI.md) and [data contracts](contracts/README.md): how the pieces fit together.
176
187
  - [Contribution guide](CONTRIBUTING.md): local setup, checks, and how private data is kept out.
177
188
  - [Release status](docs/PUBLIC_RELEASE_READINESS.md): what is published, and what the checks cover.
178
189
  - [Translating Moondog](docs/TRANSLATING.md): how replies choose a language, and how to add one.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@audiofool/moondog",
3
- "version": "0.4.0-beta.2",
3
+ "version": "0.4.0-beta.4",
4
4
  "type": "module",
5
5
  "description": "A local-first AI radio host, just for you.",
6
6
  "license": "Apache-2.0",
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import { randomUUID } from "node:crypto";
3
4
  import { createApplicationUpdater } from "../src/core/application-update.mjs";
4
5
  import { openInDefaultBrowser } from "../src/core/host.mjs";
5
6
  import { runUpdateCommand } from "../src/surfaces/cli/update-command.mjs";
@@ -13,14 +14,17 @@ import {
13
14
  } from "../src/core/apple-projection-domain-services.mjs";
14
15
  import { readAppleMusicSourceStatus } from "../src/core/apple-library-source-status.mjs";
15
16
  import { createListeningProfileDomainServices } from "../src/core/listening-profile-domain-services.mjs";
16
- import { runMemoryReflection } from "../src/memory/reflection-worker.mjs";
17
+ import { runMemoryReflection, runMemoryReflectionIfDue } from "../src/memory/reflection-worker.mjs";
17
18
  import { createConfiguredRuntime } from "../src/runtime/pi/configured-runtime.mjs";
18
19
  import { createModelSettings } from "../src/runtime/pi/model-settings.mjs";
19
20
  import { createToolTrace } from "../src/runtime/pi/tool-trace.mjs";
20
21
  import { watchRuntimeSettings, writePiRuntimeSelection } from "../src/runtime/pi/runtime-settings.mjs";
21
22
  import {
23
+ collectionCoverageLines,
22
24
  formatLocalResult,
23
25
  formatDemoResult,
26
+ formatLearnedSkill,
27
+ formatLearnedSkills,
24
28
  formatMemoryReflection,
25
29
  helpText,
26
30
  sanitizeTerminalText,
@@ -36,7 +40,6 @@ import { createWebResearch } from "../src/integrations/web/web-research.mjs";
36
40
  import { runModelRolesCommand } from "../src/surfaces/cli/model-roles-command.mjs";
37
41
  import { runWebCommand } from "../src/surfaces/cli/web-command.mjs";
38
42
  import { openSpotifyConnection } from "../src/integrations/spotify/connection.mjs";
39
- import { preferredIdleDevice, thisComputerName } from "../src/integrations/spotify/service.mjs";
40
43
  import {
41
44
  openSpotifyResolutionCache,
42
45
  } from "../src/integrations/spotify/resolution-cache.mjs";
@@ -45,16 +48,18 @@ import {
45
48
  } from "../src/integrations/spotify/settings.mjs";
46
49
  import { runSpotifyCommand } from "../src/surfaces/cli/spotify-command.mjs";
47
50
  import { runListenBrainzCommand } from "../src/surfaces/cli/listenbrainz-command.mjs";
48
- import { openListeningHistoryStore } from "../src/profile/listening-history-store.mjs";
51
+ import { openListeningHistoryStore, readListeningImportSubject } from "../src/profile/listening-history-store.mjs";
52
+ import { createMusicAppListening, projectMusicAppPlays } from "../src/integrations/apple-music/music-app-listening.mjs";
49
53
  import { musicHash, prepareMusicBundle } from "../src/profile/music-import-bundle.mjs";
50
- import { commitSpotifyQuickImport, prepareHistoryImport, prepareSpotifyQuickImport } from "../src/profile/history-import.mjs";
51
- import { persistAppleLibraryImport, refreshAppleLibraryImport } from "../src/profile/apple-library-import.mjs";
54
+ import { prepareListeningImport } from "../src/profile/local-file-import.mjs";
55
+ import { refreshAppleLibraryImport } from "../src/profile/apple-library-import.mjs";
52
56
  import { IMPORT_GUIDE_URLS } from "../src/surfaces/cli/import-guides.mjs";
53
57
  import { readLastfmConfiguration, writeLastfmConfiguration } from "../src/integrations/lastfm/settings.mjs";
54
58
  import { runMoondogTui } from "../src/surfaces/cli/tui.mjs";
55
59
  import { createLyricService } from "../src/core/lyric-service.mjs";
56
60
  import { startListeningUpkeep } from "../src/core/listening-upkeep.mjs";
57
61
  import { createAppleMusicCatalog } from "../src/integrations/apple-music/catalog.mjs";
62
+ import { readCatalogPlaylist } from "../src/integrations/apple-music/catalog-playlist-reader.mjs";
58
63
  import { createTerminalPreviewPlayer } from "../src/integrations/apple-music/terminal-preview-player.mjs";
59
64
  import { createNeteasePlayer } from "../src/integrations/netease/ncm-cli-player.mjs";
60
65
  import { createAtmosphereStream, createLocalGenerator } from "../src/integrations/stable-audio/local-generator.mjs";
@@ -323,6 +328,20 @@ async function syncRecentSpotifyListening({ signal } = {}) {
323
328
  }
324
329
  }
325
330
 
331
+ // Stores finished Music app plays in an existing history. Like Spotify's recent plays, they never
332
+ // start one: a listener who has imported nothing yet still chooses when to begin.
333
+ async function recordMusicAppPlays(plays) {
334
+ const store = await openListeningHistoryStore();
335
+ try {
336
+ const appleSubjectId = await optionalAppleMusicSubjectId();
337
+ const subjectId = store.localSubjectId(appleSubjectId ? { preferredSubjectId: appleSubjectId } : {});
338
+ if (!subjectId) return null;
339
+ return store.ingest(projectMusicAppPlays({ subjectId, plays }));
340
+ } finally {
341
+ store.close();
342
+ }
343
+ }
344
+
326
345
  async function runSpotifySurface(options) {
327
346
  const syncContext = await spotifyRecentSyncContext(options.args);
328
347
  try {
@@ -357,51 +376,12 @@ async function runListenBrainzSurface(options) {
357
376
  }
358
377
 
359
378
  async function prepareTuiHistoryImport(filePath, { recentPage, librarySnapshot, libraryUnavailable, provider, onProgress, signal } = {}) {
360
- const historyStore = await openListeningHistoryStore();
361
- try {
362
- const appleSubjectId = await optionalAppleMusicSubjectId();
363
- const subjectId = historyStore.localSubjectId({
364
- ...(appleSubjectId ? { preferredSubjectId: appleSubjectId } : {}),
365
- create: true,
366
- });
367
- const prepared = recentPage ? prepareSpotifyQuickImport({ page: recentPage, librarySnapshot, libraryUnavailable, subjectId }) : await prepareHistoryImport({
368
- filePath, subjectId, provider, capturedAt: new Date().toISOString(), onProgress, signal,
369
- });
370
- let closed = false;
371
- let committed = false;
372
- return {
373
- provider: prepared.provider,
374
- preview: prepared.preview,
375
- async commit() {
376
- if (closed || committed) throw new Error("That preview is gone. Open it again before importing.");
377
- const options = { args: ["import-history", filePath], stdout: { write() {} }, subjectId };
378
- // Commit the exact inspected bundle, even if the source file later changes.
379
- const receipt = prepared.provider === "spotify-quick"
380
- ? commitSpotifyQuickImport(historyStore, prepared)
381
- : prepared.provider === "apple-music-library"
382
- ? await persistAppleLibraryImport(prepared.bundle)
383
- : prepared.provider === "spotify"
384
- ? await runSpotifyCommand({
385
- ...options, recentActivityStore: historyStore,
386
- historyArchiveImporter: async () => prepared.bundle,
387
- })
388
- : prepared.provider === "listenbrainz" ? await runListenBrainzCommand({
389
- ...options, historyStore,
390
- historyFileImporter: async () => prepared.bundle,
391
- }) : { ...historyStore.ingestImport(prepared.bundle), provider: prepared.provider };
392
- committed = true;
393
- return receipt;
394
- },
395
- close() {
396
- if (closed) return;
397
- closed = true;
398
- historyStore.close();
399
- },
400
- };
401
- } catch (error) {
402
- historyStore.close();
403
- throw error;
404
- }
379
+ signal?.throwIfAborted();
380
+ const preferredSubjectId = await optionalAppleMusicSubjectId();
381
+ const subjectId = await readListeningImportSubject({ preferredSubjectId: preferredSubjectId ?? undefined }) ?? randomUUID();
382
+ signal?.throwIfAborted();
383
+ return prepareListeningImport({ filePath, subjectId, provider, capturedAt: new Date().toISOString(),
384
+ recentPage, librarySnapshot, libraryUnavailable, onProgress, signal });
405
385
  }
406
386
 
407
387
  async function openImportHelp(destination) {
@@ -411,11 +391,16 @@ async function openImportHelp(destination) {
411
391
  }
412
392
 
413
393
  function tasteCoverage(profile) {
394
+ const coverage = profile.coverage ?? {};
414
395
  return {
415
- effective_listening_events:
416
- profile.coverage?.effective_listening_events ?? null,
417
- listening_hours: profile.coverage?.listening_hours ?? null,
418
- distinct_tracks: profile.coverage?.listening_tracks ?? null,
396
+ effective_listening_events: coverage.effective_listening_events ?? null,
397
+ listening_hours: coverage.effective_listening_events === 0 || coverage.events_with_played_duration === 0
398
+ ? null : coverage.listening_hours ?? null,
399
+ distinct_tracks: coverage.listening_tracks ?? null,
400
+ ...(coverage.tracks_observed > 0 ? { apple_library_tracks: coverage.tracks_observed } : {}),
401
+ ...(coverage.collection_tracks > 0 ? { collection_tracks: coverage.collection_tracks } : {}),
402
+ ...(coverage.collection_sources?.length ? { collection_sources: coverage.collection_sources } : {}),
403
+ ...(coverage.profile_evidence_records > 0 ? { profile_evidence_records: coverage.profile_evidence_records } : {}),
419
404
  };
420
405
  }
421
406
 
@@ -449,12 +434,24 @@ async function emitTasteprintArtifact(
449
434
  if (json) {
450
435
  process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
451
436
  } else {
437
+ const { effective_listening_events: plays, distinct_tracks: tracks, listening_hours: hours } = result.coverage;
438
+ const collections = collectionCoverageLines(profile.coverage);
439
+ const counts = [];
440
+ if (plays > 0) {
441
+ counts.push(`${plays.toLocaleString("en-US")} ${plays === 1 ? "play" : "plays"}`);
442
+ if (hours !== null) {
443
+ const amount = hours === 0 && profile.coverage?.events_with_played_duration > 0 ? "<0.1" : hours.toLocaleString("en-US");
444
+ counts.push(`${amount} ${hours === 1 ? "hour" : "hours"}`);
445
+ }
446
+ if (tracks !== null) counts.push(`${tracks.toLocaleString("en-US")} ${tracks === 1 ? "track" : "tracks"}`);
447
+ }
452
448
  const lines = [
453
449
  format === "card"
454
450
  ? "Your recap card is ready."
455
- : "Your listening report is ready.",
451
+ : plays === 0 && collections.length ? "Your collection report is ready." : "Your listening report is ready.",
456
452
  `Saved to ${artifact.path}`,
457
- `Read from ${(result.coverage.effective_listening_events ?? 0).toLocaleString("en-US")} plays, ${(result.coverage.listening_hours ?? 0).toLocaleString("en-US")} hours, ${(result.coverage.distinct_tracks ?? 0).toLocaleString("en-US")} tracks.`,
453
+ ...(counts.length ? [`Read from ${counts.join(", ")}.`] : []),
454
+ ...collections,
458
455
  ];
459
456
  if (source?.persistent_import === false) {
460
457
  lines.push(
@@ -525,29 +522,6 @@ function watchMusicAppForStream(stream, { musicApp, interval = STREAM_MUSIC_APP_
525
522
  };
526
523
  }
527
524
 
528
- // Whether a /spotify command starts Spotify on this Mac: play on the device it resumes on (the active one,
529
- // or with none active the one it would pick), or a move onto this Mac with --play or while Spotify plays (a
530
- // move keeps playing what plays). A command its own checks refuse, or reads that fail, start nothing here.
531
- async function spotifyStartsHere(application, args, { signal } = {}) {
532
- if (!application.spotifyReady?.()) return false;
533
- // A trailing --json changes only how the result is written.
534
- if (args.at(-1) === "--json") args = args.slice(0, -1);
535
- const play = args[0] === "play" && args.length <= 2;
536
- const transfer = args[0] === "transfer" && args.length >= 2 && args.length <= 3 && (args.length === 2 || args[2] === "--play");
537
- if (!play && !transfer) return false;
538
- const service = application.requireSpotifyService();
539
- const [listed, player] = await Promise.all([service.devices({ signal }).catch(() => null), service.currentPlayer({ signal }).catch(() => null)]);
540
- const devices = listed?.devices ?? [];
541
- if (transfer) {
542
- const device = devices.find((entry) => entry.id === args[1]);
543
- const playing = player?.state === "available" && player.is_playing === true;
544
- return Boolean(device) && application.spotifyOnThisMac(device) && (args[2] === "--play" || playing);
545
- }
546
- const active = player?.device?.is_active === true ? player.device : devices.find((device) => device.is_active === true);
547
- const device = active ?? preferredIdleDevice(devices, { thisComputer: await thisComputerName() });
548
- return Boolean(device) && application.spotifyOnThisMac(device);
549
- }
550
-
551
525
  async function main() {
552
526
  const updater = createApplicationUpdater();
553
527
  const argv = process.argv.slice(2);
@@ -755,6 +729,13 @@ async function main() {
755
729
  );
756
730
  }
757
731
 
732
+ if (options.command === "sources") {
733
+ const [offset = "0", ...extra] = options.rest;
734
+ if (extra.length || !/^\d+$/u.test(offset) || !Number.isSafeInteger(Number(offset))) {
735
+ throw new Error("Usage: moondog sources [offset] [--json].");
736
+ }
737
+ }
738
+
758
739
  if (options.command === "auth") {
759
740
  await runAuthCommand({
760
741
  args: options.rest,
@@ -820,6 +801,36 @@ async function main() {
820
801
  return;
821
802
  }
822
803
 
804
+ if (options.command === "skills") {
805
+ const [action, name, ...extra] = options.rest;
806
+ if (!["list", "show", "archive", "restore"].includes(action) ||
807
+ (action === "list" && (name !== undefined || options.dryRun || options.offline)) ||
808
+ (action !== "list" && (typeof name !== "string" || name.length === 0 || extra.length > 0 ||
809
+ options.dryRun || options.offline))) {
810
+ throw new Error("Usage: moondog skills <list|show <name>|archive <name>|restore <name>> [--json].");
811
+ }
812
+ const memoryStore = await openLocalMemoryStore();
813
+ try {
814
+ let value;
815
+ if (action === "list") {
816
+ value = memoryStore.listLearnedSkills();
817
+ process.stdout.write(`${options.json ? JSON.stringify(value, null, 2) : formatLearnedSkills(value)}\n`);
818
+ } else if (action === "show") {
819
+ value = memoryStore.readLearnedSkill(name, { includeArchived: true });
820
+ process.stdout.write(`${options.json ? JSON.stringify(value, null, 2) : formatLearnedSkill(value)}\n`);
821
+ } else if (action === "archive") {
822
+ value = memoryStore.archiveLearnedSkill(name);
823
+ process.stdout.write(`${options.json ? JSON.stringify(value, null, 2) : `Archived learned practice: ${value.name}.\n`}`);
824
+ } else {
825
+ value = memoryStore.restoreLearnedSkill(name);
826
+ process.stdout.write(`${options.json ? JSON.stringify(value, null, 2) : `Restored learned practice: ${value.name}.\n`}`);
827
+ }
828
+ } finally {
829
+ memoryStore.close();
830
+ }
831
+ return;
832
+ }
833
+
823
834
  if (options.command === "memory" && options.rest[0] === "reflect") {
824
835
  if (options.rest.length !== 1) {
825
836
  throw new Error("Usage: moondog memory reflect [--dry-run] [--json].");
@@ -948,13 +959,24 @@ async function main() {
948
959
  // One-shot commands get none: they would exit in the middle of the first song.
949
960
  // In the desktop app, the window's own player plays them instead.
950
961
  const previewPlayer = options.command ? null : host ? host.musicPreviewPlayer : await createTerminalPreviewPlayer();
951
- // What the listener plays in the Music app on this Mac, read but never opened.
952
- const musicApp = createMusicAppPlayer();
962
+ // What the listener plays in the Music app on this Mac, read but never opened. While the room is
963
+ // open, what it plays goes into the listening history, as Spotify's recent plays do.
964
+ let musicAppListening = null;
965
+ const musicApp = createMusicAppPlayer({ onRead: (answer) => musicAppListening?.observe(answer) });
953
966
  // NetEase Cloud Music plays through ncm-cli in the terminal and the window alike. Its tools
954
967
  // appear once ncm-cli says it is signed in; only listeners who chose it wait for that check.
955
968
  const neteasePlayer = createNeteasePlayer();
956
969
  const playbackService = await resolvePlaybackService();
957
970
  if (playbackService === "netease") await neteasePlayer.check();
971
+ let musicAppWrites = Promise.resolve();
972
+ if (!options.command && musicApp.available) {
973
+ musicAppListening = createMusicAppListening({
974
+ read: () => musicApp.nowPlaying(),
975
+ record: (play) => { musicAppWrites = musicAppWrites.then(() => recordMusicAppPlays([play])).catch(() => null); },
976
+ // A listener who chose Apple Music has the room read the Music app from the start.
977
+ allowed: playbackService === "apple_music",
978
+ });
979
+ }
958
980
  // Moondog makes music on this Mac with Stable Audio 3 once the listener turns it on, in a room
959
981
  // that can play what it makes: Moondog's own install, downloaded when they ask, or their folder.
960
982
  // The terminal and the window each keep one generator, so each makes one track at a time; a
@@ -986,12 +1008,6 @@ async function main() {
986
1008
  // The listener's model menu, shared by the window, the terminal and a model asked for in words.
987
1009
  const modelSettings = createModelSettings({ environment: process.env });
988
1010
  const modelSwitch = createModelSwitch({ list: () => modelSettings.list() });
989
- // The terminal and the window each run this core on one playback.json. A service chosen on the
990
- // other side reaches this side's picker and agents, and stops the Apple Music songs this side plays.
991
- // Moondog's stream is not a service: its made tracks play on.
992
- const unwatchPlayback = watchPlaybackPreference(playbackSelection, {
993
- onChange: (service) => { if (service !== "apple_music" && previewPlayer?.holdsCatalogSongs?.() !== false) previewPlayer?.stop?.(); },
994
- });
995
1011
  // The main application and every conversation the window opens beside it are built from
996
1012
  // this one list, so they cannot drift apart. Each passes in what may change after launch:
997
1013
  // its domain services, the Spotify connection, the language and the music service.
@@ -1000,6 +1016,7 @@ async function main() {
1000
1016
  const applicationOptions = ({ domainServices, domainServicesError, spotifyConnection, locale, playbackService }) => ({
1001
1017
  domainServices, domainServicesError, spotifyConnection, locale, playbackService, playbackSelection, languageSelection, modelSwitch,
1002
1018
  webResearch, memoryStore, musicCatalog, musicPreviewPlayer: previewPlayer, neteasePlayer, localGenerator, atmosphereStream, musicSimilarity, artistIdentityResolver,
1019
+ appleCatalogPlaylistReader: readCatalogPlaylist,
1003
1020
  spotifyTopArtists, musicApp, libraryStore,
1004
1021
  // A playlist that shapes the taste reloads the profile services at once, so the evidence counts in this session.
1005
1022
  playlistTaste: async (found) => { const receipt = await addPlaylistToTaste(found); replaceDomainServices(await loadDomainServices()); return receipt; },
@@ -1007,6 +1024,15 @@ async function main() {
1007
1024
  const application = new MoondogApplication(applicationOptions({
1008
1025
  ...domainState, spotifyConnection, locale: await resolveListenerLocale(), playbackService,
1009
1026
  }));
1027
+ // The terminal and the window share playback.json. Switching away in the other
1028
+ // client also stops this client's Apple lookups and songs. Made tracks keep playing.
1029
+ const unwatchPlayback = watchPlaybackPreference(playbackSelection, {
1030
+ onChange: (service) => {
1031
+ if (service === "apple_music") return;
1032
+ application.cancelPendingMusicPreviews();
1033
+ if (previewPlayer?.holdsCatalogSongs?.() !== false) previewPlayer?.stop?.();
1034
+ },
1035
+ });
1010
1036
  // The conversations the window runs beside the main one, each with its own application and agent.
1011
1037
  const conversations = new Set();
1012
1038
  // An import replaces the domain services under the main application and every open
@@ -1048,6 +1074,7 @@ async function main() {
1048
1074
  const value = await application.runLocalCommand(
1049
1075
  options.command,
1050
1076
  runtimeStatus,
1077
+ options.command === "sources" ? { offset: Number(options.rest[0] ?? 0) } : undefined,
1051
1078
  );
1052
1079
  process.stdout.write(
1053
1080
  `${options.json ? JSON.stringify(value, null, 2) : formatLocalResult(options.command, value)}\n`,
@@ -1111,24 +1138,20 @@ async function main() {
1111
1138
  );
1112
1139
  }
1113
1140
  lyrics = await createLyricService().catch(() => null);
1141
+ musicAppListening?.watch();
1114
1142
  // Each step stands alone, so a Spotify outage does not hold back a due rebuild.
1115
1143
  listeningUpkeep = startListeningUpkeep({
1116
1144
  run: async ({ signal }) => {
1117
1145
  const spotify = application.spotifyReady() ? application.spotifyConnection : null;
1118
- const granted = (scope) => spotify !== null && !spotify.missingScopes?.().includes(scope);
1119
- if (granted("user-read-recently-played")) {
1146
+ if (spotify && !spotify.missingScopes?.().includes("user-read-recently-played")) {
1120
1147
  const synced = await syncRecentSpotifyListening({ signal }).catch(() => null);
1121
1148
  // Open domain services read new plays as they land; only a first history needs opening.
1122
1149
  if (synced?.inserted_events > 0 && !application.domainServices) replaceDomainServices(await loadDomainServices());
1123
1150
  }
1124
- if (granted("user-top-read")) {
1125
- const top = await spotify.service.topItems({ type: "artists", timeRange: "short_term", limit: 10 }, { signal })
1126
- .catch(() => null);
1127
- if (top) {
1128
- spotifyTopArtists.read_at = new Date().toISOString();
1129
- spotifyTopArtists.artists = top.items.flatMap((artist) => typeof artist.name === "string" ? [artist.name.slice(0, 256)] : []);
1130
- }
1131
- }
1151
+ await application.refreshSpotifyTopArtists({ signal }).catch(() => null);
1152
+ signal.throwIfAborted();
1153
+ // Completed conversations become durable memory a batch at a time, before the longer rebuild.
1154
+ await runMemoryReflectionIfDue({ application }).catch(() => null);
1132
1155
  signal.throwIfAborted();
1133
1156
  await application.refreshListenerProfile({ signal });
1134
1157
  },
@@ -1185,18 +1208,18 @@ async function main() {
1185
1208
  checkUpdates: options => updater.startupCheck(options),
1186
1209
  runUpdate: (args, options) => runUpdateCommand({ args, updater, deferInstall: true, ...options }),
1187
1210
  prepareImport: prepareTuiHistoryImport,
1188
- prepareRecentImport: async ({ onProgress } = {}) => {
1189
- const recentPage = await runSpotifySurface({ args: ["recent", "--limit", "50"], stdout: { write() {} } });
1211
+ prepareRecentImport: async ({ onProgress, signal } = {}) => {
1212
+ const recentPage = await runSpotifySurface({ args: ["recent", "--limit", "50"], stdout: { write() {} }, signal });
1190
1213
  let librarySnapshot = null;
1191
1214
  let libraryUnavailable = null;
1192
1215
  try {
1193
- librarySnapshot = await runSpotifySurface({ args: ["library"], stdout: { write() {} }, onProgress });
1216
+ librarySnapshot = await runSpotifySurface({ args: ["library"], stdout: { write() {} }, onProgress, signal });
1194
1217
  } catch (error) {
1195
1218
  // An older recent-plays-only sign-in can still import recent plays.
1196
1219
  if (error?.code !== "spotify_scope_insufficient") throw error;
1197
1220
  libraryUnavailable = "missing_permission";
1198
1221
  }
1199
- return prepareTuiHistoryImport(undefined, { recentPage, librarySnapshot, libraryUnavailable });
1222
+ return prepareTuiHistoryImport(undefined, { recentPage, librarySnapshot, libraryUnavailable, onProgress, signal });
1200
1223
  },
1201
1224
  openImportHelp,
1202
1225
  // Local generation: what the room shows and the switch the listener turns, in Settings or with /generation.
@@ -1300,9 +1323,6 @@ async function main() {
1300
1323
  return json ? `\`\`\`json\n${output.trim()}\n\`\`\`` : output.trim();
1301
1324
  },
1302
1325
  runSpotify: async (args, { signal, stderr } = {}) => {
1303
- // /spotify play, and a move onto this Mac that plays there, start Spotify here: the other players go
1304
- // quiet first. A command its own checks will refuse, or a move to another device, quiets nothing.
1305
- if (await spotifyStartsHere(application, args, { signal })) await application.quietOtherPlayers("spotify", { signal });
1306
1326
  let output = "";
1307
1327
  const capture = {
1308
1328
  write(value) {
@@ -1312,6 +1332,7 @@ async function main() {
1312
1332
  await runSpotifySurface({
1313
1333
  args,
1314
1334
  signal,
1335
+ onPlaybackStarted: application.spotifyPlaybackStarted,
1315
1336
  stdout: capture,
1316
1337
  stderr: stderr ?? (args[0] === "login" ? host?.terminalStreams?.output ?? process.stderr : capture),
1317
1338
  resolutionCache: await spotifyResolutionCacheIfConfigured(),
@@ -1320,8 +1341,9 @@ async function main() {
1320
1341
  replaceDomainServices(await loadDomainServices());
1321
1342
  }
1322
1343
  const connection = await loadSpotifyConnection();
1323
- application.setSpotifyConnection(connection);
1324
- for (const conversation of conversations) conversation.application.setSpotifyConnection(connection);
1344
+ const sameAuthorization = !["login", "logout", "configure"].includes(args[0]);
1345
+ application.setSpotifyConnection(connection, { sameAuthorization });
1346
+ for (const conversation of conversations) conversation.application.setSpotifyConnection(connection, { sameAuthorization });
1325
1347
  return output.trim();
1326
1348
  },
1327
1349
  });
@@ -1343,6 +1365,8 @@ async function main() {
1343
1365
  unwatchStreamMusicApp?.();
1344
1366
  atmosphereStream?.stop("closed");
1345
1367
  listeningUpkeep?.stop();
1368
+ musicAppListening?.stop();
1369
+ await musicAppWrites;
1346
1370
  lyrics?.close();
1347
1371
  // Conversations close first: their domain services are forks of the main application's.
1348
1372
  for (const conversation of conversations) conversation.close();
@@ -2,6 +2,7 @@ import { lstat, readFile, readdir } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
 
4
4
  import { resolveMoondogStateDirectory } from "./state-directory.mjs";
5
+ import { readAppleImportSaveTime } from "../importers/apple-music-library/save-time.mjs";
5
6
 
6
7
  export function defaultAppleMusicImportsRootFor(environment = process.env) {
7
8
  return path.join(resolveMoondogStateDirectory(environment), "apple-music-library", "imports");
@@ -19,6 +20,7 @@ export function resolveAppleMusicImportsRoot(environment = process.env) {
19
20
  const uuidDirectoryPattern =
20
21
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
21
22
  const maximumManifestBytes = 256 * 1024;
23
+ const isSourceDigest = value => typeof value === "string" && /^[0-9a-f]{64}$/u.test(value);
22
24
 
23
25
  function missingStatus() {
24
26
  return {
@@ -77,7 +79,7 @@ function sanitizeManifest(manifest) {
77
79
  return {
78
80
  subject_id: manifest.subject_id.toLowerCase(),
79
81
  captured_at: new Date(capturedAt).toISOString(),
80
- tracks: requireCount(manifest.counts, "source_tracks"),
82
+ tracks: requireCount(manifest.counts, manifest.warning_counts?.non_music_media_excluded ? "track_refs" : "source_tracks"),
81
83
  playlists: requireCount(manifest.counts, "source_playlists"),
82
84
  playlist_item_references: requireCount(
83
85
  manifest.counts,
@@ -103,7 +105,7 @@ function sanitizeManifest(manifest) {
103
105
  };
104
106
  }
105
107
 
106
- async function readPrivateManifest(batchDirectory) {
108
+ async function readPrivateManifest(batchDirectory, includeIdentity) {
107
109
  const directoryMetadata = await lstat(batchDirectory);
108
110
  if (!directoryMetadata.isDirectory() || directoryMetadata.isSymbolicLink()) {
109
111
  throw new Error("batch_directory_invalid");
@@ -119,45 +121,58 @@ async function readPrivateManifest(batchDirectory) {
119
121
  throw new Error("manifest_file_invalid");
120
122
  }
121
123
 
122
- return sanitizeManifest(JSON.parse(await readFile(manifestPath, "utf8")));
124
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
125
+ if (manifest.import_batch_id !== undefined && manifest.import_batch_id !== path.basename(batchDirectory)) {
126
+ throw new Error("manifest_identity_invalid");
127
+ }
128
+ const summary = sanitizeManifest(manifest);
129
+ if (includeIdentity) {
130
+ if (!manifest.import_batch_id ||
131
+ !isSourceDigest(manifest.source.sha256) || !isSourceDigest(manifest.source.library_fingerprint_sha256)) {
132
+ throw new Error("manifest_identity_invalid");
133
+ }
134
+ return {
135
+ ...summary,
136
+ batchId: manifest.import_batch_id,
137
+ sourceHash: manifest.source.sha256,
138
+ libraryFingerprint: manifest.source.library_fingerprint_sha256,
139
+ trackCount: requireCount(manifest.counts, "track_refs"),
140
+ };
141
+ }
142
+ return summary;
123
143
  }
124
144
 
125
- export async function readAppleMusicSourceStatus(
126
- importsRoot = resolveAppleMusicImportsRoot(),
127
- operations = { lstat, readdir },
128
- ) {
145
+ async function scanAppleMusicManifests(importsRoot, operations, { includeSaveTimes = false, includeIdentity = false } = {}) {
146
+ const valid = [];
147
+ let invalidBatches = 0;
129
148
  let rootMetadata;
130
149
  try {
131
150
  rootMetadata = await operations.lstat(importsRoot);
132
151
  } catch (error) {
133
- if (error?.code === "ENOENT") return missingStatus();
134
- return { ...missingStatus(), state: "invalid", error: "source_unreadable" };
152
+ return { valid, invalidBatches, error: error?.code === "ENOENT" ? null : "source_unreadable" };
135
153
  }
136
154
 
137
155
  if (!rootMetadata.isDirectory() || rootMetadata.isSymbolicLink()) {
138
- return { ...missingStatus(), state: "invalid", error: "source_root_invalid" };
156
+ return { valid, invalidBatches, error: "source_root_invalid" };
139
157
  }
140
158
 
141
159
  let entries;
142
160
  try {
143
161
  entries = await operations.readdir(importsRoot, { withFileTypes: true });
144
162
  } catch (error) {
145
- if (error?.code === "ENOENT") return missingStatus();
146
- return { ...missingStatus(), state: "invalid", error: "source_unreadable" };
163
+ return { valid, invalidBatches, error: error?.code === "ENOENT" ? null : "source_unreadable" };
147
164
  }
148
165
  const candidateNames = entries
149
166
  .filter((entry) => uuidDirectoryPattern.test(entry.name))
150
167
  .map((entry) => entry.name)
151
168
  .sort();
152
169
 
153
- const valid = [];
154
- let invalidBatches = 0;
155
-
156
170
  for (const candidateName of candidateNames) {
157
171
  try {
158
- valid.push(
159
- await readPrivateManifest(path.join(importsRoot, candidateName)),
160
- );
172
+ const directory = path.join(importsRoot, candidateName);
173
+ const manifest = await readPrivateManifest(directory, includeIdentity);
174
+ if (includeSaveTimes) manifest.first_imported_at = await readAppleImportSaveTime(directory);
175
+ valid.push(manifest);
161
176
  } catch {
162
177
  invalidBatches += 1;
163
178
  }
@@ -166,6 +181,37 @@ export async function readAppleMusicSourceStatus(
166
181
  valid.sort((left, right) =>
167
182
  left.captured_at.localeCompare(right.captured_at),
168
183
  );
184
+ return { valid, invalidBatches };
185
+ }
186
+
187
+ export function listAppleLibraryComparisonSources(importsRoot) {
188
+ return scanAppleMusicManifests(importsRoot, { lstat, readdir }, { includeIdentity: true, includeSaveTimes: true });
189
+ }
190
+
191
+ export async function listAppleLibraryImportHistory({ importsRoot = resolveAppleMusicImportsRoot(), subjectId } = {}) {
192
+ if (subjectId != null && (typeof subjectId !== "string" || !uuidDirectoryPattern.test(subjectId))) {
193
+ throw new TypeError("An Apple library subject must be a UUID.");
194
+ }
195
+ const { valid, invalidBatches, error } = await scanAppleMusicManifests(importsRoot, { lstat, readdir }, { includeSaveTimes: true });
196
+ const selected = subjectId == null ? valid : valid.filter(manifest => manifest.subject_id === subjectId.toLowerCase());
197
+ if (error || (!selected.length && invalidBatches)) {
198
+ throw Object.assign(new Error("Apple library import history could not be read."), { code: "apple_library_history_unavailable" });
199
+ }
200
+ if (subjectId == null && new Set(valid.map(manifest => manifest.subject_id)).size > 1) {
201
+ throw Object.assign(new Error("Choose a local listening subject to read Apple library imports."), { code: "apple_library_multiple_subjects" });
202
+ }
203
+ return selected.map(manifest => ({
204
+ kind: "collection", sourceKey: "apple_music_library_xml", sourceFormat: "apple-music-library",
205
+ observedAt: manifest.captured_at, importedAt: manifest.first_imported_at, trackCount: manifest.aggregate_track_snapshots,
206
+ })).sort((left, right) => (right.importedAt ?? right.observedAt).localeCompare(left.importedAt ?? left.observedAt));
207
+ }
208
+
209
+ export async function readAppleMusicSourceStatus(
210
+ importsRoot = resolveAppleMusicImportsRoot(),
211
+ operations = { lstat, readdir },
212
+ ) {
213
+ const { valid, invalidBatches, error } = await scanAppleMusicManifests(importsRoot, operations);
214
+ if (error) return { ...missingStatus(), state: "invalid", error };
169
215
  const latest = valid.at(-1) ?? null;
170
216
 
171
217
  if (new Set(valid.map((manifest) => manifest.subject_id)).size > 1) {