@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
@@ -1,15 +1,38 @@
1
1
  // What the listener plays right now, wherever it plays: Moondog's own player (the songs it played or
2
2
  // queued, the tracks it made, its stream), the Music app on this Mac, Spotify on its active device,
3
3
  // or NetEase through ncm-cli, with the playlist, album or queue it plays from.
4
- // Two players rarely play at once. When they do, one that plays wins over a paused one, then
5
- // Moondog's own player, which pauses the others when it starts, then the listener's chosen service,
6
- // then this order.
4
+ // A playing source comes first. In silence, prefer the song just requested over an older paused one.
5
+ // For equal states, prefer Moondog's own player, then the listener's chosen service.
6
+ import { appleMusicSongId } from "../integrations/apple-music/song-id.mjs";
7
+ import { foldedWords } from "./track-title.mjs";
8
+
7
9
  export const LISTENING_ORDER = Object.freeze(["moondog", "apple_music", "spotify", "netease"]);
8
10
 
11
+ // Only a complete request to replay this recording. A condition, negation or request for another
12
+ // version leaves the choice with the host. These words alone never identify the recording.
13
+ const currentSong = "(?:it|(?:this|that|the same)(?: (?:one|song|track|recording))?)";
14
+ const again = "(?:again|one more time|once more)";
15
+ const replayRequests = [
16
+ new RegExp(`^(?:please )?(?:(?:can|could|would) you (?:please )?)?(?:play ${currentSong} ${again}|(?:replay|repeat|restart) ${currentSong}|(?:let me|i want to|i d like to|can i) hear ${currentSong} ${again})(?: please)?$`, "u"),
17
+ /^(?:请|請)?(?:再(?:放|播|播放|听|聽)(?:一遍|一次)?[这這那]首(?:歌|曲)?(?:一遍|一次)?|(?:把)?[这這那]首(?:歌|曲)?再(?:放|播|播放|听|聽)(?:一遍|一次)?)吧?$/u,
18
+ /^(?:この曲|その曲|これ|それ)をもう一(?:度|回)(?:かけて|流して|再生して)(?:ください)?$/u,
19
+ /^(?:이|그) (?:곡|노래)(?:을|를)? (?:다시|한 번 더) (?:틀어|들려) ?(?:줘|주세요)$/u,
20
+ /^(?:vuelve a (?:poner|reproducir) (?:esta|esa) cancion|(?:ponla|ponlo|pon (?:esta|esa) cancion) (?:otra vez|de nuevo))(?: por favor)?$/u,
21
+ /^(?:toque|toca) (?:essa|esta) (?:musica|faixa) (?:de novo|outra vez)(?: por favor)?$/u,
22
+ /^(?:rejoue (?:ce morceau|cette chanson)|remets (?:ce morceau|cette chanson|la))$/u,
23
+ /^(?:spiel|spiele) (?:das|das lied|diesen song|dieses lied) (?:nochmal|noch einmal)(?: bitte)?$/u,
24
+ /^(?:rimetti|risuona) (?:questa|quella) canzone(?: per favore)?$/u,
25
+ ];
26
+ export function requestsCurrentReplay(text) {
27
+ const words = foldedWords(text);
28
+ return replayRequests.some(pattern => pattern.test(words));
29
+ }
30
+
9
31
  export function activeListening(sources, chosen) {
10
32
  const order = [...new Set(["moondog", chosen, ...LISTENING_ORDER])];
11
- const heard = sources.filter((source) => source.song && (source.state === "playing" || source.state === "paused"));
12
- return heard.sort((a, b) => (a.state === "playing" ? 0 : 1) - (b.state === "playing" ? 0 : 1) ||
33
+ const states = ["playing", "loading", "paused"];
34
+ const visible = sources.filter(source => source.song && states.includes(source.state));
35
+ return visible.sort((a, b) => states.indexOf(a.state) - states.indexOf(b.state) ||
13
36
  order.indexOf(a.service) - order.indexOf(b.service))[0] ?? null;
14
37
  }
15
38
 
@@ -66,6 +89,7 @@ async function spotify(application, { signal }) {
66
89
  : null;
67
90
  return {
68
91
  state: player.is_playing === true ? "playing" : "paused",
92
+ recording: player.item.track_ref_id,
69
93
  player: player.device?.name ? `Spotify on ${player.device.name}` : "Spotify",
70
94
  ...(player.device ? { device: { name: player.device.name ?? null, type: player.device.type ?? null } } : {}),
71
95
  song: songOf(player.item),
@@ -78,41 +102,51 @@ async function spotify(application, { signal }) {
78
102
  }
79
103
 
80
104
  // Moondog's own player: Apple Music songs in the window or the terminal, and the tracks Moondog made.
81
- const madeBy = (track) => ({ title: track.title, artists: track.generated ? ["Moondog"] : track.artist_credit ? [track.artist_credit] : [],
82
- ...(track.generated && track.id ? { made_track_id: track.id } : {}) });
83
- function moondogPlayer(application) {
105
+ const madeBy = (track, forLibrary) => ({ title: track.title, artists: track.generated ? ["Moondog"] : track.artist_credit ? [track.artist_credit] : [],
106
+ ...(track.generated && track.id ? { made_track_id: track.id } : {}),
107
+ ...(forLibrary && !track.generated && track.catalog_id ? { refs: { apple_music_id: track.catalog_id } } : {}) });
108
+ function moondogPlayer(application, forLibrary) {
84
109
  const now = application.musicPreviewPlayer.nowPlaying();
85
110
  if (!now?.song?.title) return { state: "stopped" };
86
111
  const kind = !now.song.generated ? "moondog_queue" : application.streamView?.() ? "moondog_stream" : "moondog_made";
112
+ // Keep the whole remaining queue with the same observation as the current song.
113
+ const next = forLibrary === "queue" ? application.musicPreviewPlayer.remaining?.()?.slice(1) ?? now.next : now.next;
87
114
  return {
88
115
  state: now.state,
116
+ recording: now.song.generated ? (now.song.id && `moondog:generated:${now.song.id}`) :
117
+ (now.song.catalog_id && `apple_music:${now.song.catalog_id}`),
89
118
  player: "Moondog's own player",
90
- song: madeBy(now.song),
119
+ song: madeBy(now.song, forLibrary),
91
120
  from: { kind, name: null, tracks_total: now.count, position: now.position },
92
- next: now.next.map(madeBy),
121
+ next: next.map(track => madeBy(track, forLibrary)),
93
122
  };
94
123
  }
95
124
 
96
- async function netease(application) {
125
+ async function netease(application, forLibrary) {
97
126
  const now = await application.neteaseNowPlaying();
98
127
  if (now.state === "stopped" || !now.song) return { state: "stopped" };
128
+ const project = (track) => {
129
+ const id = track.original_id ?? track.id;
130
+ return { ...songOf(track), ...(forLibrary && id ? { refs: { netease_id: String(id) } } : {}) };
131
+ };
99
132
  return {
100
133
  state: now.state,
134
+ recording: now.song.id && `netease:${now.song.id}`,
101
135
  player: "NetEase Music through ncm-cli on this Mac",
102
- song: songOf(now.song),
136
+ song: project(now.song),
103
137
  position_ms: now.position_ms ?? 0,
104
138
  from: { kind: "moondog_queue", name: null },
105
- next: (now.next ?? []).map(songOf),
139
+ next: (now.next ?? []).map(project),
106
140
  };
107
141
  }
108
142
 
109
- /** Every player Moondog can read, the one the listener hears first: { active, sources }. */
110
- export async function readListeningNow(application, { signal } = {}) {
143
+ /** Every player Moondog can read, with the playing or pending selection first. */
144
+ export async function readListeningNow(application, { signal, onPlayingRecording, forLibrary } = {}) {
111
145
  const readers = [
112
- typeof application.musicPreviewPlayer?.nowPlaying === "function" ? ["moondog", () => moondogPlayer(application)] : null,
146
+ typeof application.musicPreviewPlayer?.nowPlaying === "function" ? ["moondog", () => moondogPlayer(application, forLibrary)] : null,
113
147
  application.musicApp?.available ? ["apple_music", () => musicApp(application)] : null,
114
148
  application.spotifyReady() ? ["spotify", () => spotify(application, { signal })] : null,
115
- application.neteaseReady() ? ["netease", () => netease(application)] : null,
149
+ application.neteaseReady() ? ["netease", () => netease(application, forLibrary)] : null,
116
150
  ].filter(Boolean);
117
151
  const sources = await Promise.all(readers.map(async ([service, read]) => {
118
152
  try {
@@ -123,18 +157,21 @@ export async function readListeningNow(application, { signal } = {}) {
123
157
  }
124
158
  }));
125
159
  const active = activeListening(sources, application.playbackService);
126
- return { active: active?.service ?? null, sources: active ? [active, ...sources.filter((source) => source !== active)] : sources };
160
+ if (active?.state === "playing" && active.recording) onPlayingRecording?.(active.service, active.recording);
161
+ const ordered = active ? [active, ...sources.filter((source) => source !== active)] : sources;
162
+ return { active: active?.service ?? null, sources: ordered.map(({ recording, ...source }) => source) };
127
163
  }
128
164
 
129
165
  // What Moondog's own player plays: the queue it was sent last, and where in it the player's own
130
166
  // events put it. The window and the terminal players keep one each, so the agent can read the songs
131
167
  // it played or queued, and the tracks it made, as it reads the Music app or Spotify.
132
168
 
133
- const entry = (track) => ({
134
- title: String(track?.title ?? "").trim(),
135
- artist_credit: String(track?.artist_credit ?? "").trim(),
136
- ...(track?.generated === true ? { generated: true, ...(typeof track.id === "string" && track.id ? { id: track.id } : {}) } : {}),
137
- });
169
+ const entry = (track) => {
170
+ const song = { title: String(track?.title ?? "").trim(), artist_credit: String(track?.artist_credit ?? "").trim() };
171
+ if (track?.generated === true) return { ...song, generated: true, ...(typeof track.id === "string" && track.id ? { id: track.id } : {}) };
172
+ const id = appleMusicSongId(track);
173
+ return id ? { ...song, catalog_id: id } : song;
174
+ };
138
175
 
139
176
  export function createPlayerNow() {
140
177
  // null, or { tracks, index, state } where state is "loading", "playing" or "paused".
@@ -145,10 +182,15 @@ export function createPlayerNow() {
145
182
  const list = (Array.isArray(tracks) ? tracks : []).map(entry).filter((track) => track.title);
146
183
  queue = list.length ? { tracks: list, index: 0, state: "loading" } : null;
147
184
  },
148
- /** A made track queued behind the last one, as Moondog's stream does. */
149
- appended(track) {
185
+ /** A new track, at the position the player confirmed or at the end of the queue. */
186
+ appended(track, position) {
150
187
  const added = entry(track);
151
- if (queue && added.title) queue.tracks.push(added);
188
+ if (!queue || !added.title) return;
189
+ if (Number.isSafeInteger(position) && position >= 1 && position <= queue.tracks.length) {
190
+ // A later Library append can be here already when the window confirms an earlier batch.
191
+ queue.tracks.splice(position - 1, 0, added);
192
+ if (position - 1 <= queue.index) queue.index++;
193
+ } else queue.tracks.push(added);
152
194
  },
153
195
  /** One of the player's events: { type, position } moves it along; stopped empties it. */
154
196
  observe(event) {
@@ -175,8 +217,7 @@ export function createPlayerNow() {
175
217
  read() {
176
218
  if (!queue) return null;
177
219
  return {
178
- // A song still loading is the one the listener is about to hear.
179
- state: queue.state === "paused" ? "paused" : "playing",
220
+ state: queue.state,
180
221
  song: { ...queue.tracks[queue.index] },
181
222
  position: queue.index + 1,
182
223
  count: queue.tracks.length,
@@ -1,16 +1,17 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { readImportSourceHistory } from "./import-source-history.mjs";
2
3
  import { exploreProfileCatalog, profileExplorationInput } from "../profile/profile-exploration.mjs";
3
4
  import { createListenerProfileInput, savedListenerChoices } from "../profile/listener-profile-build.mjs";
4
5
  import { lyricSeedsFromProfile } from "./lyric-profile.mjs";
5
- import { cachedAvoidGate, listeningVersion } from "./listener-avoids.mjs";
6
+ import { allowedDiscoveryTracks, cachedAvoidGate, listeningVersion } from "./listener-avoids.mjs";
6
7
  import { recordListenerChoice } from "../profile/listener-corrections.mjs";
7
8
  import { listenedNames } from "../profile/taste-compiler.mjs";
9
+ import { isHeardMixSlot } from "../profile/moondog-suggestions.mjs";
8
10
 
9
11
  import { isUuid } from "./uuid-v5.mjs";
10
12
  import { createListeningHistoryProfileProjection } from "../profile/spotify-archive-taste.mjs";
11
13
  import {
12
14
  assertExternalPlanDiversity,
13
- exactTitleArtistMatch,
14
15
  safeExternalSource,
15
16
  safeExternalTrack,
16
17
  } from "./apple-projection-domain-services.mjs";
@@ -502,6 +503,10 @@ export class ListeningProfileDomainServices {
502
503
  return this.#store.listeningCoverage?.({ subjectId: this.#subjectId }) ?? null;
503
504
  }
504
505
 
506
+ importSourceHistory(options) {
507
+ return readImportSourceHistory({ ...options, listeningHistoryStore: this.#store, subjectId: this.#subjectId });
508
+ }
509
+
505
510
  recentAttention() {
506
511
  return this.#store.recentAttention?.({ subjectId: this.#subjectId }) ?? null;
507
512
  }
@@ -511,8 +516,12 @@ export class ListeningProfileDomainServices {
511
516
  }
512
517
 
513
518
  // Moondog's suggestions ledger and the declared mix (src/profile/moondog-suggestions.mjs).
514
- recordMoondogSuggestions(entries) {
515
- return this.#store.recordMoondogSuggestions?.({ entries }) ?? null;
519
+ recordMoondogSuggestions(entries, options = {}) {
520
+ return this.#store.recordMoondogSuggestions?.({ ...options, entries }) ?? null;
521
+ }
522
+
523
+ recordSuggestionOutcome(outcome) {
524
+ return this.#store?.recordSuggestionOutcome?.(outcome) ?? null;
516
525
  }
517
526
 
518
527
  moondogSuggestionHistory(tracks) {
@@ -588,13 +597,21 @@ export class ListeningProfileDomainServices {
588
597
  const gate = cachedAvoidGate(this.#avoids, listeningVersion(this.#store), () =>
589
598
  this.#store.activeAvoidances?.({ subjectId: this.#subjectId }) ??
590
599
  this.#store.profileSummary({ subjectId: this.#subjectId })?.listener_assertions?.avoids ?? []);
591
- return tracks.filter((track) => !gate.avoidsTrack(track));
600
+ return allowedDiscoveryTracks(gate, tracks, this.#store, this.#subjectId);
592
601
  }
593
602
 
594
603
  recordListenerChoice(choice) {
595
604
  return recordListenerChoice(this.#store, { ...choice, subjectId: this.#subjectId });
596
605
  }
597
606
 
607
+ tasteReviewChoices() {
608
+ return this.#store.listListenerCorrections?.({ subjectId: this.#subjectId, limit: null }) ?? null;
609
+ }
610
+
611
+ retractTasteReviewChoice(correctionId) {
612
+ return this.#store.retractListenerCorrection({ subjectId: this.#subjectId, correctionId });
613
+ }
614
+
598
615
  // The choices in force, cheap enough to read when there is no saved reading.
599
616
  listenerChoices() {
600
617
  if (typeof this.#store.countActiveListenerCorrections !== "function") return null;
@@ -603,7 +620,7 @@ export class ListeningProfileDomainServices {
603
620
  }
604
621
 
605
622
  isKnownDiscoveryTrack(track) {
606
- return (this.#store.listenedTracks?.({ subjectId: this.#subjectId }) ?? []).some(heard => exactTitleArtistMatch(track, heard));
623
+ return isHeardMixSlot(this.listeningMix([track])?.[0]);
607
624
  }
608
625
 
609
626
  // Every Avoid in force, imported bans included, as the play paths read them.
@@ -630,14 +647,12 @@ export class ListeningProfileDomainServices {
630
647
  throw new TypeError("External catalog candidates are duplicated");
631
648
  }
632
649
  // Familiarity is useful evidence, not an automatic discovery exclusion.
633
- const listened = typeof this.#store.listenedTracks === "function"
634
- ? this.#store.listenedTracks({ subjectId: this.#subjectId })
635
- : [];
636
650
  const accepted = [];
637
651
  let excludedHistoryMatches = 0;
638
652
  const allowed = this.filterDiscoveryTracks(prepared);
639
- for (const track of allowed) {
640
- const heard = listened.some((heard) => exactTitleArtistMatch(track, heard));
653
+ const slots = this.listeningMix(allowed);
654
+ for (const [index, track] of allowed.entries()) {
655
+ const heard = isHeardMixSlot(slots?.[index]);
641
656
  if (excludeKnown && heard) {
642
657
  excludedHistoryMatches += 1;
643
658
  continue;
@@ -703,13 +718,13 @@ export class ListeningProfileDomainServices {
703
718
  return this.#store.listenerProfileStorage({ subjectId: this.#subjectId });
704
719
  }
705
720
 
706
- getProfileBuildContext() {
721
+ getProfileBuildContext(readingThrough = null) {
707
722
  const version = listeningVersion(this.#store);
708
- if (this.#profileBuildInput?.version !== version) {
723
+ if (this.#profileBuildInput?.version !== version || (readingThrough && !this.#profileBuildInput.input.historyDigests[readingThrough])) {
709
724
  this.#profileBuildInput = { version, input: createListenerProfileInput({
710
725
  subjectId: this.#subjectId,
711
726
  evidenceRevision: this.#store.profileEvidenceRevision({ subjectId: this.#subjectId }),
712
- listening: this.#store.profileCatalog({ subjectId: this.#subjectId }),
727
+ listening: this.#store.profileCatalog({ subjectId: this.#subjectId, readingThrough }),
713
728
  }) };
714
729
  }
715
730
  return { store: this.getListenerProfileStore(), input: this.#profileBuildInput.input };
@@ -1027,10 +1042,9 @@ export class ListeningProfileDomainServices {
1027
1042
  ) {
1028
1043
  throw new TypeError("A playlist plan cannot contain duplicate tracks");
1029
1044
  }
1030
- const external = selected.map(({ track }) => track)
1031
- .filter((track) => track.candidate_scope === "external_catalog");
1032
- if (this.filterDiscoveryTracks(external).length !== external.length) {
1033
- throw new Error("An external discovery is currently marked Avoid. Choose another track.");
1045
+ const selectedTracks = selected.map(({ track }) => track);
1046
+ if (this.filterDiscoveryTracks(selectedTracks).length !== selectedTracks.length) {
1047
+ throw new Error("A selected song is currently marked Avoid. Choose another track.");
1034
1048
  }
1035
1049
  const tracks = selected.map(({ track, selectionReason }, index) => ({
1036
1050
  position: index + 1,
@@ -0,0 +1,119 @@
1
+ // Only explicit directions for the current listen belong here, not a title, a dated fact, a habit or
2
+ // a taste said "now". Keep the original offsets for exact quotes.
3
+ const QUOTED = /"[^"\n]+"|“[^”\n]+”|‘[^’\n]+’|(?<![\p{L}\p{N}])'[^'\n]+'(?![\p{L}\p{N}])|《[^》\n]+》|「[^」\n]+」|『[^』\n]+』|«[^»\n]+»/gu;
4
+ const BREAK = /[.!?;。!?;\n]+|[,,::]+|\b(?:but|however|pero|mais|aber|and\s+(?=(?:I|remember|always|usually|never|please|no|skip|avoid|play|for now)\b))\b|(?:但是|不过|不過|可是|但|而且)/giu;
5
+ const SOFT_BREAK = /^(?:[,,::]+|and\s+)$/iu;
6
+ const TIME = [
7
+ /\b(?:for (?:right )?now|this (?:time(?: around)?|once)|(?:(?:for|during) )?(?:this|the current) (?:listening |work )?(?:session|conversation|mix|set)|for the rest of (?:this|the) session)\b/giu,
8
+ /\b(?:(?:for )?(?:right now|tonight|this (?:morning|afternoon|evening))|while I(?:['’]m| am)? (?:work(?:ing)?|study(?:ing)?|driv(?:e|ing)))\b/giu,
9
+ /(?:这次|這次|这回|這回|这轮|這輪|本次)(?:对话|對話)?|(?:今晚|今早|暂时|暫時|今回(?:だけ)?|今だけ|이번만|이번에는)/gu,
10
+ /\b(?:por (?:ahora|hoy|agora|hoje)|esta (?:vez|sesión)|(?:pour|pendant) cette (?:fois|séance)|pour le moment|cette fois|für (?:heute|diese sitzung)|diesmal|per (?:ora|oggi)|questa volta)\b/giu,
11
+ ];
12
+ const NOW = /\b(?:now|today)\b|今天|现在|現在/giu;
13
+ const TASTE = /^i(?: do not| don['’]t)? (?:like|love)\b|^我喜[欢歡]/iu;
14
+ const LASTING = /\b(?:always|usually|generally|normally|forever|permanently|in general|as a rule|from (?:now|here) on|all[- ]time favou?rite|ever|never|any ?more|no longer|nunca|jamais|nie (?:wieder|mehr))\b|\bmai più|(?:一向|一直|平时|平時|总是|總是|永远|永遠|以后都|以後都|以后不|以後不|再也不|いつも|もう二度と|다시는|앞으로)/iu;
15
+ const FILLER = /^(?:(?:just|only|for|during|please|solo|seulement|nur)\s*|[只就仅僅限先是的はだけ\s()()-])*$/iu;
16
+ const POLITE = /^(?:(?:please|just|only|maybe|something|also|let['’]s|could you|can you|could we|can we)\s+)*/iu;
17
+ const DIRECTION = [
18
+ /^(?:(?:do not|don['’]t)\s+)?(?:play|put on|give me|go with|queue|keep|leave|skip|avoid|exclude|try|make|recommend|suggest|no|not|without|more|less|some|prefer)\s+(?!(?:by|from)\b)\S/iu,
19
+ /^i(?: (?:(?:do not|don['’]t) )?(?:want|prefer|like|love|need|feel like)|(?:['’]d| would) (?:like|prefer|love|rather))\s+(?!(?:by|from)\b)\S/iu,
20
+ /^(?:instrumentals?|vocals?|quieter|louder|quiet music|soft music|music for|background music)\b|^i(?:['’]m| am) (?:working|studying|driving|in the mood)\b/iu,
21
+ /^(?:别|別|不(?:要|听|聽|想听|想聽|放|播)|跳过|跳過|先|只|请|請|听|聽|放|播|来|來|想|要|给我|給我|我(?:想|要|在|喜欢|喜歡|不想|只|更想)|安静|安靜|纯音乐|純音樂)/u,
22
+ /^(?:sin|evita|pon|prefiero|sans|évite|mets|ohne|spiele|bitte|sem|toque|senza|metti)\s+\S|(?:なし|抜き|かけて|流して|避けて|いらない|없이|빼고|틀어)/iu,
23
+ ];
24
+ const NAMED_TITLE = /\b(?:this time|right now|tonight|today)\b(?=\s+by\b)|\b(?:called|named|titled) (?:this time|right now|tonight|today)\b/giu;
25
+ const DATED_EVENT = /\b(?:found|heard|bought|discovered|released|met|learned)\s+(?:[\p{L}'’-]+\s+){0,3}(?:today|tonight|this morning)\b|(?:今天|今晚)(?:刚|剛)?(?:发行|發行|听到|聽到|买|買)的/giu;
26
+ const NEXT_DIRECTION = /^(?:no|without|just|only|more|less|skip|avoid|play)\b|^(?:不要|不放|别|別|只|先)/iu;
27
+
28
+ function clausesFor(message) {
29
+ const maskTitle = (title) => "x".repeat(title.length);
30
+ const masked = message.replace(QUOTED, maskTitle).replace(NAMED_TITLE, maskTitle).replace(DATED_EVENT, maskTitle);
31
+ const clauses = [];
32
+ let start = 0;
33
+ let group = 0;
34
+ function add(end) {
35
+ const clause = masked.slice(start, end).trim();
36
+ if (!clause) return;
37
+ const words = [];
38
+ const strip = (text, limit) => text.replace(limit, word => (words.push(word), "")).trim();
39
+ const fixed = TIME.reduce(strip, clause);
40
+ const rest = strip(fixed, NOW);
41
+ const lasting = LASTING.test(clause);
42
+ const request = rest.replace(POLITE, "");
43
+ const timed = !lasting && (fixed !== clause || (rest !== fixed && !TASTE.test(request)));
44
+ const direction = !lasting && DIRECTION.some((pattern) => pattern.test(request));
45
+ clauses.push({ start, end, group, lasting, direction, words, scoped: timed && (direction || /^not$/iu.test(rest)),
46
+ qualifier: timed && FILLER.test(rest), continuation: direction && NEXT_DIRECTION.test(rest) });
47
+ }
48
+ for (const match of masked.matchAll(BREAK)) {
49
+ add(match.index);
50
+ if (!SOFT_BREAK.test(match[0])) group++;
51
+ start = match.index + match[0].length;
52
+ }
53
+ add(message.length);
54
+ // A fronted or trailing qualifier can sit across a comma: "For this session, no vocals."
55
+ for (const [i, clause] of clauses.entries()) {
56
+ if (clause.qualifier) {
57
+ const neighbour = [clauses[i + 1], clauses[i - 1]].find((part) => part?.group === clause.group && part.direction);
58
+ if (neighbour) clause.scoped = neighbour.scoped = true;
59
+ }
60
+ const previous = clauses[i - 1];
61
+ if (clause.continuation && previous?.group === clause.group && previous.scoped) clause.scoped = true;
62
+ if (clause.scoped && previous?.group === clause.group && previous.continuation) previous.scoped = true;
63
+ }
64
+ return clauses;
65
+ }
66
+
67
+ function occurrences(message, quote) {
68
+ const ranges = [];
69
+ const words = typeof quote === "string" ? quote.trim() : "";
70
+ if (!words) return ranges;
71
+ for (let start = message.indexOf(words); start >= 0; start = message.indexOf(words, start + words.length)) {
72
+ ranges.push({ start, end: start + words.length });
73
+ }
74
+ return ranges;
75
+ }
76
+
77
+ const overlaps = (a, b) => a.start < b.end && b.start < a.end;
78
+
79
+ /** The time words that keep a quote out of lasting writes, or null. */
80
+ export function sessionOnlyWords(message, quote) {
81
+ const ranges = occurrences(message, quote);
82
+ const scoped = clausesFor(message).filter((clause) => clause.scoped);
83
+ return ranges.length && ranges.every((range) => scoped.some((clause) => overlaps(range, clause)))
84
+ ? scoped.flatMap(clause => clause.words) : null;
85
+ }
86
+
87
+ /** Keep only the listener's unscoped words in the copy available to memory and reflection. */
88
+ export function listenerWordsForMemory(message, markedQuotes = []) {
89
+ const clauses = clausesFor(message);
90
+ const marks = markedQuotes.flatMap((quote) => {
91
+ const matches = occurrences(message, quote);
92
+ if (matches.length < 2) return matches;
93
+ // A short mark may name the same artist twice: a temporary skip and a lasting Like.
94
+ const scoped = matches.filter((mark) => clauses.some((clause) => clause.scoped && overlaps(mark, clause)));
95
+ if (scoped.length) return scoped;
96
+ const unqualified = matches.filter((mark) => !clauses.some((clause) => clause.lasting && overlaps(mark, clause)));
97
+ return unqualified.length ? unqualified : matches;
98
+ });
99
+ const removed = new Set(clauses.filter((clause) => clause.scoped));
100
+ for (const mark of marks) {
101
+ const hits = clauses.filter((clause) => overlaps(mark, clause));
102
+ const broad = hits.length > 1;
103
+ if (broad && (hits.some((clause) => clause.scoped) ||
104
+ marks.some((narrow) => narrow !== mark && narrow.start >= mark.start && narrow.end <= mark.end &&
105
+ (narrow.start > mark.start || narrow.end < mark.end)))) continue;
106
+ for (const clause of hits) if (!broad || !clause.lasting) removed.add(clause);
107
+ }
108
+ if (!removed.size) return message;
109
+ const kept = [];
110
+ for (let i = 0; i < clauses.length;) {
111
+ const first = i++;
112
+ if (removed.has(clauses[first])) continue;
113
+ while (i < clauses.length && !removed.has(clauses[i])) i++;
114
+ const last = clauses[i - 1];
115
+ const punctuation = message.slice(last.end).match(/^([.!?。!?]+)/u)?.[1] ?? "";
116
+ kept.push(message.slice(clauses[first].start, last.end).trim() + punctuation);
117
+ }
118
+ return kept.join(" ");
119
+ }