@audiofool/moondog 0.4.0-beta.3 → 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 (93) hide show
  1. package/README.md +19 -8
  2. package/package.json +1 -1
  3. package/scripts/moondog.mjs +95 -103
  4. package/src/core/apple-library-source-status.mjs +64 -18
  5. package/src/core/apple-projection-domain-services.mjs +63 -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 +28 -18
  16. package/src/core/listening-scope.mjs +119 -0
  17. package/src/core/moondog-application.mjs +1003 -267
  18. package/src/core/play-follower.mjs +73 -37
  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 +89 -26
  34. package/src/i18n/screen/ja.mjs +88 -25
  35. package/src/i18n/screen/pt.mjs +89 -26
  36. package/src/i18n/screen/zh.mjs +88 -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/song-id.mjs +13 -0
  44. package/src/integrations/apple-music/terminal-preview-player.mjs +154 -44
  45. package/src/integrations/listenbrainz/history-file.mjs +63 -35
  46. package/src/integrations/netease/ncm-cli-player.mjs +355 -68
  47. package/src/integrations/netease/queue-occurrence.mjs +138 -0
  48. package/src/integrations/playlist-links.mjs +93 -30
  49. package/src/integrations/public-playlists.mjs +21 -15
  50. package/src/integrations/spotify/account-data-history.mjs +9 -10
  51. package/src/integrations/spotify/account-data-profile.mjs +1 -0
  52. package/src/integrations/spotify/extended-streaming-history.mjs +57 -52
  53. package/src/integrations/spotify/history-archive.mjs +8 -18
  54. package/src/integrations/spotify/library-snapshot.mjs +2 -1
  55. package/src/integrations/spotify/service.mjs +29 -11
  56. package/src/integrations/spotify/web-api-client.mjs +2 -2
  57. package/src/integrations/stable-audio/local-generator.mjs +13 -5
  58. package/src/integrations/youtube-music/takeout.mjs +12 -8
  59. package/src/memory/local-memory-store.mjs +479 -27
  60. package/src/memory/reflection-worker.mjs +1 -0
  61. package/src/profile/apple-library-import.mjs +56 -2
  62. package/src/profile/history-import.mjs +58 -27
  63. package/src/profile/listener-corrections.mjs +2 -4
  64. package/src/profile/listener-profile-build.mjs +128 -45
  65. package/src/profile/listener-profile-store.mjs +25 -4
  66. package/src/profile/listener-profile-verification.mjs +11 -5
  67. package/src/profile/listener-profile-worker.mjs +24 -8
  68. package/src/profile/listening-history-store.mjs +944 -367
  69. package/src/profile/listening-profile-projection.mjs +123 -156
  70. package/src/profile/local-file-import.mjs +172 -0
  71. package/src/profile/moondog-suggestions.mjs +40 -11
  72. package/src/profile/profile-exploration.mjs +36 -6
  73. package/src/profile/recorded-measures.mjs +5 -0
  74. package/src/profile/spotify-archive-taste.mjs +41 -65
  75. package/src/runtime/pi/agent-runtime.mjs +360 -215
  76. package/src/runtime/pi/custom-endpoints.mjs +30 -8
  77. package/src/runtime/pi/memory-agent-runtime.mjs +43 -3
  78. package/src/runtime/pi/playback-rules.mjs +100 -0
  79. package/src/runtime/pi/profile-build-runtime.mjs +81 -24
  80. package/src/surfaces/cli/brand-components.mjs +9 -6
  81. package/src/surfaces/cli/command-completions.mjs +8 -1
  82. package/src/surfaces/cli/format-output.mjs +207 -34
  83. package/src/surfaces/cli/history-import-view.mjs +130 -21
  84. package/src/surfaces/cli/listenbrainz-command.mjs +7 -2
  85. package/src/surfaces/cli/listener-profile-command.mjs +67 -10
  86. package/src/surfaces/cli/listening-menu.mjs +3 -0
  87. package/src/surfaces/cli/profile-command.mjs +1 -0
  88. package/src/surfaces/cli/spotify-command.mjs +17 -25
  89. package/src/surfaces/cli/taste-period.mjs +22 -0
  90. package/src/surfaces/cli/taste-profile-model.mjs +52 -32
  91. package/src/surfaces/cli/tui.mjs +557 -170
  92. package/src/surfaces/html/tasteprint.mjs +181 -93
  93. package/src/surfaces/import-source-history.mjs +80 -0
@@ -1,5 +1,4 @@
1
1
  import { createHash } from "node:crypto";
2
- import { createReadStream } from "node:fs";
3
2
  import { lstat } from "node:fs/promises";
4
3
  import path from "node:path";
5
4
  import { openZipArchive } from "../../importers/zip-reader.mjs";
@@ -29,8 +28,8 @@ export const SPOTIFY_EXTENDED_HISTORY_LIMITS = Object.freeze({
29
28
  maximumRecords: 500_000,
30
29
  });
31
30
 
32
- const historyMemberPattern =
33
- /^Spotify Extended Streaming History\/Streaming_History_(?:Audio|Video)_([0-9]{4})(?:_([0-9]+))?\.json$/u;
31
+ const historyDirectory = "Spotify Extended Streaming History/";
32
+ const historyMemberPattern = /^Streaming_History_(Audio|Video)_([0-9]{4})(?:-([0-9]{4}))?(?:_([0-9]+))?\.json$/u;
34
33
  const trackUriPattern = /^spotify:track:([A-Za-z0-9]{22})$/u;
35
34
  const sha256Pattern = /^[a-f0-9]{64}$/u;
36
35
  const unsafeTextPattern =
@@ -112,12 +111,21 @@ function normalizedMusicRows(records, capturedAt) {
112
111
  }
113
112
  const capturedMilliseconds = Date.parse(capturedAt);
114
113
  const rows = [];
114
+ const excluded = { non_music: 0, unidentified: 0 };
115
115
  for (let index = 0; index < records.length; index += 1) {
116
116
  const record = records[index];
117
117
  if (!record || typeof record !== "object" || Array.isArray(record)) {
118
118
  fail(`Spotify Extended History record ${index + 1} is invalid.`);
119
119
  }
120
- if (record.spotify_track_uri === null) continue;
120
+ if (record.spotify_track_uri === null) {
121
+ const named = [record.episode_name, record.episode_show_name, record.audiobook_title, record.audiobook_chapter_title]
122
+ .some(value => typeof value === "string" && value.trim());
123
+ const identified = [record.spotify_episode_uri, record.audiobook_uri, record.audiobook_chapter_uri]
124
+ .some(value => typeof value === "string" && /^spotify:(?:episode|audiobook|chapter):[A-Za-z0-9]{22}$/u.test(value));
125
+ if (named || identified) excluded.non_music += 1;
126
+ else excluded.unidentified += 1;
127
+ continue;
128
+ }
121
129
  const uri = cleanText(
122
130
  record.spotify_track_uri,
123
131
  64,
@@ -206,7 +214,27 @@ function normalizedMusicRows(records, capturedAt) {
206
214
  tuple,
207
215
  });
208
216
  }
209
- return rows.sort((left, right) => lexicalCompare(left.tuple, right.tuple));
217
+ return { rows: rows.sort((left, right) => lexicalCompare(left.tuple, right.tuple)), excluded };
218
+ }
219
+
220
+ function historyMemberParts(name) {
221
+ const match = typeof name === "string" && historyMemberPattern.exec(name);
222
+ if (!match) return null;
223
+ const [, kind, first, last, segment] = match;
224
+ if (last !== undefined && last < first) return null;
225
+ return { kind, first: Number(first), last: last === undefined ? null : Number(last), segment: Number(segment ?? -1) };
226
+ }
227
+
228
+ export function spotifyExtendedHistoryArchiveMember(name) {
229
+ if (typeof name !== "string" || !name.startsWith(historyDirectory)) return null;
230
+ const basename = name.slice(historyDirectory.length);
231
+ const parts = historyMemberParts(basename);
232
+ return parts && { name, basename, ...parts };
233
+ }
234
+
235
+ export function isPreviouslySkippedSpotifyHistoryMember(name) {
236
+ const parts = historyMemberParts(name);
237
+ return parts !== null && (parts.kind === "Video" || parts.last !== null);
210
238
  }
211
239
 
212
240
  function normalizedMemberNames(memberNames) {
@@ -217,19 +245,13 @@ function normalizedMemberNames(memberNames) {
217
245
  ) {
218
246
  fail("Spotify Extended History member names are invalid.");
219
247
  }
220
- const normalized = memberNames.map((value) => {
221
- if (
222
- typeof value !== "string" ||
223
- !/^Streaming_History_(?:Audio|Video)_[0-9]{4}(?:_[0-9]+)?\.json$/u.test(value)
224
- ) {
225
- fail("Spotify Extended History member names are invalid.");
226
- }
227
- return value;
228
- });
229
- if (new Set(normalized).size !== normalized.length) {
248
+ if (memberNames.some((name) => !historyMemberParts(name))) {
249
+ fail("Spotify Extended History member names are invalid.");
250
+ }
251
+ if (new Set(memberNames).size !== memberNames.length) {
230
252
  fail("Spotify Extended History contains duplicate member names.");
231
253
  }
232
- return [...normalized].sort(lexicalCompare);
254
+ return [...memberNames].sort(lexicalCompare);
233
255
  }
234
256
 
235
257
  export function projectSpotifyExtendedStreamingHistory({
@@ -257,7 +279,7 @@ export function projectSpotifyExtendedStreamingHistory({
257
279
  fail("Spotify Extended History archive size is invalid.");
258
280
  }
259
281
  const normalizedMembers = normalizedMemberNames(memberNames);
260
- const rows = normalizedMusicRows(records, normalizedCapturedAt);
282
+ const { rows, excluded } = normalizedMusicRows(records, normalizedCapturedAt);
261
283
  const importBatchId = uuidV5(
262
284
  `${normalizedSubjectId}\0${archiveSha256}`,
263
285
  SPOTIFY_EXTENDED_HISTORY_BATCH_NAMESPACE,
@@ -377,6 +399,7 @@ export function projectSpotifyExtendedStreamingHistory({
377
399
  latestOccurredAt === null ? null : Date.parse(latestOccurredAt),
378
400
  track_refs: [...trackRefs.values()],
379
401
  listening_events: listeningEvents,
402
+ excluded_records: excluded,
380
403
  reconciliation_candidates: reconciliationCandidates,
381
404
  import_batch: {
382
405
  import_batch_id: importBatchId,
@@ -394,12 +417,6 @@ export function projectSpotifyExtendedStreamingHistory({
394
417
  };
395
418
  }
396
419
 
397
- async function sha256File(filePath) {
398
- const hash = createHash("sha256");
399
- for await (const chunk of createReadStream(filePath)) hash.update(chunk);
400
- return hash.digest("hex");
401
- }
402
-
403
420
  async function openArchive(archivePath) {
404
421
  try {
405
422
  return await openZipArchive(archivePath);
@@ -422,26 +439,11 @@ async function zipText(archive, maximumBytes, member) {
422
439
  }
423
440
  }
424
441
 
425
- function selectedHistoryMembers(listing) {
426
- const selected = listing
427
- .split(/\r?\n/u)
428
- .filter(Boolean)
429
- .map((name) => {
430
- const match = historyMemberPattern.exec(name);
431
- return match
432
- ? {
433
- name,
434
- year: Number(match[1]),
435
- segment: match[2] === undefined ? 0 : Number(match[2]) + 1,
436
- }
437
- : null;
438
- })
439
- .filter(Boolean)
440
- .sort((left, right) =>
441
- left.year === right.year
442
- ? left.segment - right.segment
443
- : left.year - right.year,
444
- );
442
+ function selectedHistoryMembers(names) {
443
+ const selected = names.map(spotifyExtendedHistoryArchiveMember).filter(Boolean)
444
+ .sort((left, right) => left.first - right.first ||
445
+ (left.last ?? left.first) - (right.last ?? right.first) ||
446
+ left.segment - right.segment || lexicalCompare(left.name, right.name));
445
447
  if (selected.length < 1) {
446
448
  fail("The ZIP does not contain Spotify Extended History audio/video files.");
447
449
  }
@@ -458,6 +460,7 @@ export async function readSpotifyExtendedStreamingHistoryArchive({
458
460
  archivePath,
459
461
  subjectId,
460
462
  capturedAt = new Date().toISOString(),
463
+ onProgress,
461
464
  } = {}) {
462
465
  if (typeof archivePath !== "string" || !archivePath.trim()) {
463
466
  fail("A Spotify Extended History ZIP path is required.");
@@ -487,12 +490,12 @@ export async function readSpotifyExtendedStreamingHistoryArchive({
487
490
  // One open archive serves the listing and every member, and is closed even when a check fails.
488
491
  const archive = await openArchive(resolvedPath);
489
492
  let members;
493
+ let archiveSha256;
490
494
  const records = [];
491
495
  try {
492
- const listing = archive.names.join("\n");
493
- members = selectedHistoryMembers(listing);
496
+ members = selectedHistoryMembers(archive.names);
494
497
  let totalJsonBytes = 0;
495
- for (const member of members) {
498
+ for (const [index, member] of members.entries()) {
496
499
  const jsonText = await zipText(archive, SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumMemberBytes, member.name);
497
500
  totalJsonBytes += Buffer.byteLength(jsonText, "utf8");
498
501
  if (
@@ -505,19 +508,21 @@ export async function readSpotifyExtendedStreamingHistoryArchive({
505
508
  parsed = JSON.parse(jsonText.replace(/^\uFEFF/u, ""));
506
509
  } catch {
507
510
  fail(
508
- `Spotify Extended History audio/video file for ${member.year} is invalid JSON.`,
511
+ `Spotify Extended History file ${member.basename} is invalid JSON.`,
509
512
  );
510
513
  }
511
514
  if (!Array.isArray(parsed)) {
512
515
  fail(
513
- `Spotify Extended History audio/video file for ${member.year} is not an array.`,
516
+ `Spotify Extended History file ${member.basename} is not an array.`,
514
517
  );
515
518
  }
516
- records.push(...parsed);
517
- if (records.length > SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumRecords) {
519
+ if (records.length + parsed.length > SPOTIFY_EXTENDED_HISTORY_LIMITS.maximumRecords) {
518
520
  fail("Spotify Extended History contains too many records.");
519
521
  }
522
+ for (const record of parsed) records.push(record);
523
+ onProgress?.({ stage: "files", count: index + 1, total: members.length });
520
524
  }
525
+ archiveSha256 = await archive.digest(file);
521
526
  } finally {
522
527
  archive.close();
523
528
  }
@@ -525,9 +530,9 @@ export async function readSpotifyExtendedStreamingHistoryArchive({
525
530
  return projectSpotifyExtendedStreamingHistory({
526
531
  subjectId,
527
532
  records,
528
- archiveSha256: await sha256File(resolvedPath),
533
+ archiveSha256,
529
534
  archiveSizeBytes: file.size,
530
- memberNames: members.map(({ name }) => path.posix.basename(name)),
535
+ memberNames: members.map(({ basename }) => basename),
531
536
  capturedAt,
532
537
  });
533
538
  }
@@ -2,7 +2,10 @@ import path from "node:path";
2
2
  import { listZipMembers } from "../../importers/zip-reader.mjs";
3
3
 
4
4
  import { readSpotifyAccountDataHistoryArchive } from "./account-data-history.mjs";
5
- import { readSpotifyExtendedStreamingHistoryArchive } from "./extended-streaming-history.mjs";
5
+ import { readSpotifyExtendedStreamingHistoryArchive, spotifyExtendedHistoryArchiveMember } from "./extended-streaming-history.mjs";
6
+
7
+ const accountMember = /^Spotify Account Data\/StreamingHistory_music_[0-9]+\.json$/u;
8
+ export const isSpotifyHistoryMember = name => accountMember.test(name) || Boolean(spotifyExtendedHistoryArchiveMember(name));
6
9
 
7
10
  function fail(message, code = "spotify_history_archive_invalid") {
8
11
  const error = new Error(message);
@@ -10,34 +13,21 @@ function fail(message, code = "spotify_history_archive_invalid") {
10
13
  throw error;
11
14
  }
12
15
 
13
- export async function readSpotifyHistoryArchive(options = {}) {
16
+ export async function readSpotifyHistoryArchive(options = {}, members) {
14
17
  if (typeof options.archivePath !== "string" || !options.archivePath.trim()) {
15
18
  fail("A Spotify history ZIP path is required.");
16
19
  }
17
20
  const archivePath = path.resolve(options.archivePath);
18
- let listing;
19
21
  try {
20
- listing = (await listZipMembers(archivePath)).join("\n");
22
+ members ??= await listZipMembers(archivePath);
21
23
  } catch {
22
24
  fail(
23
25
  "The Spotify history ZIP could not be read safely.",
24
26
  "spotify_history_archive_unreadable",
25
27
  );
26
28
  }
27
- const hasAccountData = listing
28
- .split(/\r?\n/u)
29
- .some((name) =>
30
- /^Spotify Account Data\/StreamingHistory_music_[0-9]+\.json$/u.test(
31
- name,
32
- ),
33
- );
34
- const hasExtendedHistory = listing
35
- .split(/\r?\n/u)
36
- .some((name) =>
37
- /^Spotify Extended Streaming History\/Streaming_History_(?:Audio|Video)_[0-9]{4}(?:_[0-9]+)?\.json$/u.test(
38
- name,
39
- ),
40
- );
29
+ const hasAccountData = members.some(name => accountMember.test(name));
30
+ const hasExtendedHistory = members.some(spotifyExtendedHistoryArchiveMember);
41
31
  if (hasAccountData === hasExtendedHistory) {
42
32
  fail("The ZIP does not contain one unambiguous Spotify history format.");
43
33
  }
@@ -183,7 +183,8 @@ export function projectSpotifyLibrarySnapshot({ subjectId, snapshot, capturedAt
183
183
  for (const item of playlist.tracks) {
184
184
  add({ kind: "playlist_track_added", logicalKey: `playlist-track\0${playlistRef}\0${item.id}\0${item.position}`,
185
185
  strength: "curated", entity: addTrack(item), member: "playlists", observedAt: item.added_at,
186
- attributes: { playlist_ref_id: playlistRef, playlist_name: playlist.name, playlist_position: item.position } });
186
+ attributes: { playlist_ref_id: playlistRef, playlist_name: playlist.name, playlist_position: item.position,
187
+ ...(item.added_at && item.added_at <= capturedAt ? { playlist_added_at: item.added_at } : {}) } });
187
188
  }
188
189
  }
189
190
  for (const [timeRange, period] of Object.entries(TOP_PERIODS)) {
@@ -927,16 +927,28 @@ export function createSpotifyService(options = {}) {
927
927
  if (!playlist) fail("spotify_playlist_unavailable", "Spotify did not describe this playlist.");
928
928
  const tracks = [];
929
929
  const pageSize = SPOTIFY_SERVICE_LIMITS.playlistItemsPageMax;
930
+ let lastPage = false;
931
+ let consistent = true;
932
+ let pages = 0;
930
933
  for (let offset = 0; offset < 2000; offset += pageSize) {
931
934
  const page = await client.getPlaylistItems({ playlistId: id, limit: pageSize, offset }, { signal });
935
+ pages++;
936
+ if ((page.total != null && page.total !== playlist.tracks_total) || (page.offset != null && page.offset !== offset)) consistent = false;
932
937
  // A local file on the owner's computer has no catalog song to play or name; it stays out.
933
938
  tracks.push(...page.items.filter((entry) => entry.is_local !== true).map((entry) => entry.item)
934
939
  .filter((item) => item?.type === "track" && item.name && item.artists?.length && /^spotify:track:/u.test(item.uri ?? "")));
935
- if (!page.has_more || !page.items.length) break;
940
+ lastPage = page.has_more === false;
941
+ if (lastPage || !page.items.length) break;
942
+ }
943
+ // Separate pages may describe different versions even when the total stays the same.
944
+ if (pages > 1 && playlist.snapshot_id && consistent) {
945
+ const latest = await client.getPlaylist({ playlistId: id }, { signal }).catch((error) => (signal?.aborted ? Promise.reject(error) : null));
946
+ consistent = latest?.snapshot_id === playlist.snapshot_id;
936
947
  }
937
948
  const account = await client.getAccount({ signal }).catch((error) => (signal?.aborted ? Promise.reject(error) : null));
938
949
  return { name: playlist.name, uri: playlist.uri, tracks_total: playlist.tracks_total ?? null,
939
- owned: account?.account_id && playlist.owner_id ? account.account_id === playlist.owner_id : null, tracks };
950
+ owned: account?.account_id && playlist.owner_id ? account.account_id === playlist.owner_id : null, tracks,
951
+ complete: lastPage && consistent && tracks.length === playlist.tracks_total };
940
952
  },
941
953
 
942
954
  // One device decision for a whole queue request. An idle device cannot take a
@@ -1272,7 +1284,7 @@ export function createSpotifyService(options = {}) {
1272
1284
  };
1273
1285
  },
1274
1286
 
1275
- async resume(value, { signal, ...preparation } = {}) {
1287
+ async resume(value, { signal, onPlaybackStarted, ...preparation } = {}) {
1276
1288
  signal?.throwIfAborted();
1277
1289
  const input = inputObject(value);
1278
1290
  const contextUri = optionalContextUri(input.contextUri);
@@ -1293,7 +1305,7 @@ export function createSpotifyService(options = {}) {
1293
1305
  if ((offsetPosition !== undefined || offsetUri !== undefined) && contextUri && !/^spotify:(?:album|playlist):/u.test(contextUri)) {
1294
1306
  fail("invalid_spotify_offset", "Spotify can start partway only into an album or a playlist.");
1295
1307
  }
1296
- return preparedResume({
1308
+ const receipt = await preparedResume({
1297
1309
  deviceId: optionalDeviceId(input.deviceId),
1298
1310
  contextUri,
1299
1311
  uris,
@@ -1301,6 +1313,8 @@ export function createSpotifyService(options = {}) {
1301
1313
  offsetUri,
1302
1314
  positionMs: optionalPosition(input.positionMs, "invalid_position"),
1303
1315
  }, { signal, ...preparation });
1316
+ if (!receipt.already) await onPlaybackStarted?.(receipt.device, { signal });
1317
+ return receipt;
1304
1318
  },
1305
1319
 
1306
1320
  async pause(value, { signal } = {}) {
@@ -1384,7 +1398,7 @@ export function createSpotifyService(options = {}) {
1384
1398
  return actionReceipt("playback.repeat.set");
1385
1399
  },
1386
1400
 
1387
- async transfer(value, { signal, onDeviceSelected } = {}) {
1401
+ async transfer(value, { signal, onDeviceSelected, onPlaybackStarted } = {}) {
1388
1402
  signal?.throwIfAborted();
1389
1403
  const input = inputObject(value);
1390
1404
  if (input.play !== undefined && typeof input.play !== "boolean") {
@@ -1414,28 +1428,32 @@ export function createSpotifyService(options = {}) {
1414
1428
  signal?.throwIfAborted();
1415
1429
  const playing = player?.state === "available" && player.is_playing === true;
1416
1430
  const play = input.play ?? playing;
1431
+ // A false transfer flag preserves an ongoing song. Only a known or requested start
1432
+ // may use a play command as a fallback or quiet the other players on its destination.
1433
+ const willPlay = play || playing;
1417
1434
  if (player?.device?.id === device.id && player.device.is_active !== false && (!play || playing)) {
1418
1435
  return { ...actionReceipt("playback.transfer"), already: true, device: display };
1419
1436
  }
1437
+ let method;
1420
1438
  try {
1421
1439
  await client.transfer({ deviceId: device.id, play }, { signal });
1422
- return { ...actionReceipt("playback.transfer"), device: display };
1423
1440
  } catch (error) {
1424
1441
  // Spotify sometimes refuses a transfer that it accepts as a play request aimed at
1425
1442
  // the device. Start the same song there, at the same moment, once.
1426
1443
  const item = player?.item?.uri;
1427
- if (![403, 404, 502].includes(error?.status) || error.outcomeUnknown || !item || signal?.aborted) throw refusedMove(error, display, player);
1444
+ if (!willPlay || ![403, 404, 502].includes(error?.status) || error.outcomeUnknown || !item || signal?.aborted) throw refusedMove(error, display, player);
1428
1445
  try {
1429
1446
  await client.resume({ deviceId: device.id, uris: [item], ...(Number.isInteger(player.progress_ms) ? { positionMs: player.progress_ms } : {}) }, { signal });
1430
1447
  } catch (fallback) {
1431
1448
  throw refusedMove(fallback, display, player);
1432
1449
  }
1433
- if (!play) await client.pause({ deviceId: device.id }, { signal }).catch(() => {});
1434
- return { ...actionReceipt("playback.transfer"), device: display, method: "play_on_device" };
1450
+ method = "play_on_device";
1435
1451
  }
1452
+ if (willPlay) await onPlaybackStarted?.(display, { signal });
1453
+ return { ...actionReceipt("playback.transfer"), device: display, ...(method ? { method } : {}) };
1436
1454
  },
1437
1455
 
1438
- async addToQueue(value, { signal } = {}) {
1456
+ async addToQueue(value, { signal, beforeDispatch } = {}) {
1439
1457
  signal?.throwIfAborted();
1440
1458
  const input = inputObject(value);
1441
1459
  const uri = requiredItemUri(input.uri);
@@ -1443,7 +1461,7 @@ export function createSpotifyService(options = {}) {
1443
1461
  signal?.throwIfAborted();
1444
1462
  // Let a dispatched write settle so cancellation can report accepted effects.
1445
1463
  // Never dispatch the next write after the prompt has been cancelled.
1446
- await client.addToQueue({ uri, deviceId }, { signal });
1464
+ await client.addToQueue({ uri, deviceId }, { signal, beforeDispatch });
1447
1465
  return actionReceipt("playback.queue.add");
1448
1466
  },
1449
1467
 
@@ -1042,10 +1042,10 @@ export function createSpotifyWebApiClient({
1042
1042
  });
1043
1043
  },
1044
1044
 
1045
- async addToQueue({ uri, deviceId }, { signal } = {}) {
1045
+ async addToQueue({ uri, deviceId }, { signal, beforeDispatch } = {}) {
1046
1046
  await request(
1047
1047
  `/me/player/queue${queryString({ uri, device_id: deviceId })}`,
1048
- { method: "POST", responseMode: "none", signal },
1048
+ { method: "POST", responseMode: "none", signal, beforeDispatch },
1049
1049
  );
1050
1050
  },
1051
1051
  });
@@ -57,6 +57,13 @@ export function resolveGeneratedTracksDirectory(environment = process.env) {
57
57
  return path.join(resolveMoondogStateDirectory(environment), "generated");
58
58
  }
59
59
 
60
+ /** An existing recording is available for export even on a host without a player or generation model. */
61
+ export async function retainedTrackFile(id, environment = process.env) {
62
+ if (!isGeneratedTrackId(id)) return null;
63
+ const file = path.join(resolveGeneratedTracksDirectory(environment), id, "track.wav");
64
+ return await isFile(file, { minimumBytes: 45 }) ? file : null;
65
+ }
66
+
60
67
  // A typed folder: absolute, or under the home folder with ~/.
61
68
  function literalFolder(value) {
62
69
  const text = typeof value === "string" ? value.trim() : "";
@@ -535,11 +542,7 @@ export function createLocalGenerator({
535
542
  },
536
543
  sweep,
537
544
  /** The WAV of one generated track, or null when there is none. */
538
- async trackFile(id) {
539
- if (!isGeneratedTrackId(id)) return null;
540
- const file = path.join(tracksDirectory(), id, "track.wav");
541
- return (await isFile(file, { minimumBytes: 45 })) ? file : null;
542
- },
545
+ trackFile: (id) => retainedTrackFile(id, environment),
543
546
  async receipt(id) {
544
547
  if (!isGeneratedTrackId(id)) return null;
545
548
  try {
@@ -837,6 +840,11 @@ export function createAtmosphereStream({ generator, player, now = Date.now, keep
837
840
  const items = Array.isArray(event.tracks) ? event.tracks : track ? [track] : [];
838
841
  if (items.some((item) => !item?.generated || (item.id && !ours(item.id)))) { end("other_music"); return; }
839
842
  }
843
+ // The terminal can stop an expired track while it loads, before launching the audio player.
844
+ if (event?.type === "loading" && track?.id && track.id === current.next && expired(current)) {
845
+ endInTime();
846
+ return;
847
+ }
840
848
  const isCurrent = track?.id && track.id === current.current.id;
841
849
  if (event?.type === "playing" && track?.id && track.id === current.next) {
842
850
  // The window may already have moved on to it when the time limit had passed. The generator
@@ -8,6 +8,7 @@ const maximumBytes = 256 * 1024 * 1024;
8
8
  const memberBytes = 64 * 1024 * 1024;
9
9
  const maximumRecords = 100_000;
10
10
  const videoId = /^[A-Za-z0-9_-]{11}$/u;
11
+ export const isYouTubeMusicMember = name => /(?:^|\/)(?:watch-history\.json|music[- ]library[- ]songs\.csv|library[- ]songs\.csv)$/iu.test(name);
11
12
 
12
13
  // Quoted commas, escaped quotes, UTF-8 BOMs and embedded line breaks occur in song names.
13
14
  export function parseMusicCsv(text) {
@@ -45,7 +46,8 @@ function readRows(text, name, capturedAt) {
45
46
  const [header = [], ...records] = parseMusicCsv(text);
46
47
  const field = (row, key) => row[header.indexOf(key)]?.trim();
47
48
  if (!["Video ID", "Song Title", "Artist Name"].every((key) => header.includes(key))) {
48
- throw new Error("This CSV is not supported. Choose music-library-songs.csv with Video ID, Song Title and Artist Name columns. General YouTube playlist CSVs are not music library exports.");
49
+ throw Object.assign(new Error("This CSV is not supported. Choose music-library-songs.csv with Video ID, Song Title and Artist Name columns. General YouTube playlist CSVs are not music library exports."),
50
+ { code: "youtube_music_library_csv_columns" });
49
51
  }
50
52
  for (const row of records) {
51
53
  const id = field(row, "Video ID");
@@ -95,8 +97,8 @@ async function boundedFile(filePath) {
95
97
  } finally { await file.close(); }
96
98
  }
97
99
 
98
- export async function readYouTubeMusicTakeout({ filePath, subjectId, capturedAt }) {
99
- const bytes = await boundedFile(filePath);
100
+ export async function readYouTubeMusicTakeout({ filePath, subjectId, capturedAt, onProgress }, jsonSource) {
101
+ const bytes = jsonSource?.bytes ?? await boundedFile(filePath);
100
102
  const sources = [];
101
103
  if (/\.zip$/iu.test(filePath)) {
102
104
  // Read from one private snapshot: manifest digest and preview describe exactly the same bytes.
@@ -107,7 +109,7 @@ export async function readYouTubeMusicTakeout({ filePath, subjectId, capturedAt
107
109
  throw new Error("Could not read this Takeout ZIP. Finish the download and use an unencrypted ZIP, or extract music-library-songs.csv and watch-history.json and import each file.");
108
110
  }
109
111
  try {
110
- const selected = zip.names.filter((name) => /(?:^|\/)(?:watch-history\.json|music[- ]library[- ]songs\.csv|library[- ]songs\.csv)$/iu.test(name));
112
+ const selected = zip.names.filter(isYouTubeMusicMember);
111
113
  if (!selected.length) throw new Error("No supported YouTube Music files in this ZIP. Include music library songs and history in Google Takeout; set history format to JSON, not HTML.");
112
114
  if (selected.length > 100 || new Set(selected).size !== selected.length) throw new Error("Takeout contains too many or duplicate music files.");
113
115
  let total = 0;
@@ -117,18 +119,20 @@ export async function readYouTubeMusicTakeout({ filePath, subjectId, capturedAt
117
119
  total += content.length;
118
120
  if (total > maximumBytes) throw new Error("Unpacked music data exceeds 256 MB. Import the extracted files separately.");
119
121
  sources.push({ name: `${musicHash(name).slice(0, 12)}-${path.basename(name)}`, content });
122
+ onProgress?.({ stage: "files", count: sources.length, total: selected.length });
120
123
  }
121
124
  } finally { zip.close(); }
122
125
  } else {
123
126
  if (bytes.length > memberBytes) throw new Error("Choose a music CSV or history JSON smaller than 64 MB.");
124
- sources.push({ name: path.basename(filePath), content: bytes });
127
+ sources.push({ name: path.basename(filePath), content: bytes, text: jsonSource?.text });
125
128
  }
126
129
  let skipped = 0;
127
130
  const rows = [];
128
131
  for (const source of sources) {
129
- const parsed = readRows(new TextDecoder("utf-8", { fatal: true }).decode(source.content), source.name, capturedAt);
130
- rows.push(...parsed.rows); skipped += parsed.skipped;
131
- if (rows.length > maximumRecords) throw new Error("Import up to 100,000 music records at a time. Import the extracted files separately.");
132
+ const parsed = readRows(source.text ?? new TextDecoder("utf-8", { fatal: true }).decode(source.content), source.name, capturedAt);
133
+ if (rows.length + parsed.rows.length > maximumRecords) throw new Error("Import up to 100,000 music records at a time. Import the extracted files separately.");
134
+ for (const row of parsed.rows) rows.push(row);
135
+ skipped += parsed.skipped;
132
136
  }
133
137
  const prepared = prepareMusicBundle({ provider: "youtube_music", subjectId, capturedAt, rows,
134
138
  digest: musicHash(bytes), size: bytes.length, members: sources.map((source) => source.name), skipped,