@doitian/dsh-music 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/dj.js CHANGED
@@ -17,10 +17,11 @@
17
17
  * Without it the request reaches such a provider looking like an anonymous
18
18
  * client that ignores its conventions.
19
19
  * 2. **Heuristic tier** — always available, no model required: NetEase's own
20
- * signals (similar songs, daily recommendations, anonymous new-song feed,
21
- * charts, keyword search) scored by artist affinity, novelty, and the
22
- * listener's like/dislike/skip feedback, then interleaved so consecutive
23
- * tracks do not share an artist.
20
+ * signals (similar songs, personal FM, rested likes, daily
21
+ * recommendations, anonymous new-song feed, charts, keyword search)
22
+ * scored by mood match, artist affinity, and the listener's
23
+ * like/dislike/skip feedback, then interleaved so consecutive tracks do
24
+ * not share an artist.
24
25
  *
25
26
  * The DJ never blocks playback: every entry point resolves to a plan or to
26
27
  * `null`, and the caller keeps whatever is already queued.
@@ -28,7 +29,10 @@
28
29
  * @module dsh-music/dj
29
30
  */
30
31
 
31
- import { randomUUID } from 'node:crypto';
32
+ import { createHash, randomUUID } from 'node:crypto';
33
+
34
+ import { Pacer, TtlCache, sampleInOrder } from './cache.js';
35
+ import { isHeard } from './session.js';
32
36
 
33
37
  /**
34
38
  * Render a model-tier failure so its stable code survives.
@@ -52,11 +56,95 @@ function describeFailure(error) {
52
56
  }
53
57
 
54
58
  /** Candidate pool handed to the model; keeps the prompt inside a small budget. */
55
- const MAX_POOL = 45;
59
+ const MAX_POOL = 70;
56
60
 
57
- /** Only the first `MAX_SEEDS` history entries seed similarity expansion. */
61
+ /** How many tracks seed similarity expansion. */
58
62
  const MAX_SEEDS = 4;
59
63
 
64
+ /** How far back in the history a seed may come from, so seeds stay current. */
65
+ const SEED_HISTORY = 20;
66
+
67
+ /** Seeds taken from what was played; the rest come from likes. */
68
+ const HISTORY_SEEDS = 2;
69
+
70
+ /** The newest likes whose artists inform the taste picture. */
71
+ const LIKED_TASTE = 200;
72
+
73
+ /** A liked track's artist outweighs a play of it: a like is a deliberate act. */
74
+ const LIKED_ARTIST_WEIGHT = 2;
75
+
76
+ /** Track details per lookup; one oversized id list is a request NetEase may refuse. */
77
+ const DETAIL_BATCH = 50;
78
+
79
+ /** A liked track played more recently than this is not offered back yet. */
80
+ const LIKED_REST_MS = 3 * 24 * 60 * 60 * 1000;
81
+
82
+ /**
83
+ * The order the pool is assembled in: a track two sources share is claimed by
84
+ * the earlier one, and the model reads the catalogue in this order.
85
+ */
86
+ const ORIGINS = ['prompt', 'liked', 'fm', 'similar', 'daily', 'new', 'chart'];
87
+
88
+ /**
89
+ * Tracks each source may contribute per plan. Every source gets a share, so
90
+ * no single one can crowd discovery out of the pool; without a brief they sum
91
+ * to 48, and a brief adds up to 23 that match it.
92
+ */
93
+ const QUOTA = { promptPlaylists: 15, promptSongs: 8, similar: 14, liked: 6, daily: 8, new: 6, chart: 8 };
94
+
95
+ /**
96
+ * Signed in, the account's own signals — the daily list, likes, FM — know the
97
+ * listener; the charts and the new-song feed only know the market. They keep a
98
+ * few slots for discovery and give the rest to the personal sources.
99
+ */
100
+ const SIGNED_IN_QUOTA = { ...QUOTA, liked: 9, daily: 12, new: 3, chart: 4 };
101
+
102
+ const HOUR = 60 * 60 * 1000;
103
+
104
+ /**
105
+ * How long each source is kept. Matched to how often it actually changes:
106
+ * similarity effectively never, a chart daily or weekly, the daily
107
+ * recommendations once a day. Personal FM is never cached, because every call
108
+ * answers something new.
109
+ */
110
+ const TTL = {
111
+ similar: 24 * HOUR,
112
+ track: 24 * HOUR,
113
+ playlist: 12 * HOUR,
114
+ chart: 6 * HOUR,
115
+ search: 6 * HOUR,
116
+ daily: 3 * HOUR,
117
+ new: HOUR,
118
+ /** A brief's rewrite into search terms: what it means does not drift. */
119
+ terms: 7 * 24 * HOUR,
120
+ /** A brief that could not be rewritten is searched as written, and retried after this. */
121
+ termsRetry: HOUR / 2,
122
+ };
123
+
124
+ /** 飙升榜, 新歌榜, 原创榜, 热歌榜: the general charts, updated daily or weekly. */
125
+ const CHARTS = [19723756, 3779629, 2884035, 3778678];
126
+
127
+ /** How many of a brief's playlists are drawn from. */
128
+ const BRIEF_PLAYLISTS = 3;
129
+
130
+ /** How many search terms a brief is rewritten into. */
131
+ const BRIEF_TERMS = 3;
132
+
133
+ /** A playlist shorter than this is too thin to stand for a mood. */
134
+ const MIN_PLAYLIST_TRACKS = 10;
135
+
136
+ /** Personal FM calls per plan; NetEase answers three tracks per call. */
137
+ const FM_CALLS = 2;
138
+
139
+ /**
140
+ * A track skipped this often leaves the pool for good, like a dislike. One
141
+ * skip is only a penalty: it may have been the wrong moment, not the wrong song.
142
+ */
143
+ const SKIPS_TO_EXCLUDE = 2;
144
+
145
+ /** An artist is reported to the model as often skipped from this many skips. */
146
+ const SKIPS_TO_REPORT_ARTIST = 2;
147
+
60
148
  /** Prefix for the minted curation identity, so logs and health read clearly. */
61
149
  const SESSION_ID_PREFIX = 'music-dj-';
62
150
 
@@ -132,6 +220,8 @@ export class AiDj {
132
220
  * @param {string} [options.sessionId] configured curation identity, overriding the minted one.
133
221
  * @param {{warn: Function, info: Function, debug: Function}} [options.logger]
134
222
  * @param {object} [options.model] `{ provider, model }` enabling the model tier.
223
+ * @param {() => number} [options.now] the source cache's clock, injectable for tests.
224
+ * @param {Pacer} [options.pacer] spaces out the NetEase requests a plan sends.
135
225
  */
136
226
  constructor({
137
227
  api,
@@ -142,6 +232,8 @@ export class AiDj {
142
232
  sessionId,
143
233
  logger,
144
234
  model = {},
235
+ now = Date.now,
236
+ pacer = new Pacer(),
145
237
  } = {}) {
146
238
  this.api = api;
147
239
  this.player = player;
@@ -172,6 +264,10 @@ export class AiDj {
172
264
  this.modelError = null;
173
265
  /** Guards against overlapping plans when a track ends mid-plan. */
174
266
  this.busy = false;
267
+ /** The sources' answers, each kept for as long as it plausibly stays the same. */
268
+ this.cache = new TtlCache({ now });
269
+ /** Every source request goes through this, so a plan never arrives as a burst. */
270
+ this.pacer = pacer;
175
271
  }
176
272
 
177
273
  /** Record a model-tier decline and carry on with the heuristic tier. */
@@ -285,58 +381,358 @@ export class AiDj {
285
381
 
286
382
  // ------------------------------------------------------------- candidates
287
383
 
384
+ /**
385
+ * The tracks similarity expands from: what is playing and what was recently
386
+ * heard through, and random likes — each filling in when the other is thin.
387
+ *
388
+ * A rejected track never seeds. The ✕ records a dislike and then moves on, so
389
+ * seeding from the raw history would make the very next plan fetch more of
390
+ * exactly what was just turned down.
391
+ */
392
+ #seeds(digest) {
393
+ const usable = (id) => id && this.store.taste(id) !== 'disliked' && !digest.skipCounts.has(id);
394
+ const heard = [
395
+ this.player.current()?.id,
396
+ ...this.store.state.history.slice(0, SEED_HISTORY).filter(isHeard).map((entry) => entry.id),
397
+ ].filter(usable);
398
+ const liked = sampleInOrder(this.store.feedback.likes.filter(usable), MAX_SEEDS);
399
+ const seeds = [];
400
+ const take = (ids, limit) => {
401
+ for (const id of ids) {
402
+ if (seeds.length >= limit) return;
403
+ if (!seeds.includes(id)) seeds.push(id);
404
+ }
405
+ };
406
+ // Half from what is playing and was heard, half from likes: seeding only
407
+ // from plays lets the DJ's own picks decide what it picks next.
408
+ take(heard, HISTORY_SEEDS);
409
+ take(liked, MAX_SEEDS);
410
+ take(heard, MAX_SEEDS);
411
+ return seeds;
412
+ }
413
+
414
+ /**
415
+ * A random handful of liked tracks that have rested long enough to be worth
416
+ * hearing again. A personal DJ that never returns to what the listener loves
417
+ * is only a discovery feed.
418
+ */
419
+ #likedSample(excluded) {
420
+ const restedSince = Date.now() - LIKED_REST_MS;
421
+ const heardRecently = new Set(
422
+ this.store.state.history.filter((entry) => (entry.at ?? 0) > restedSince).map((entry) => entry.id),
423
+ );
424
+ const ids = this.store.feedback.likes.filter((id) => !excluded.has(id) && !heardRecently.has(id));
425
+ return sampleInOrder(ids, this.#quota().liked);
426
+ }
427
+
288
428
  /**
289
429
  * Gather a de-duplicated candidate pool from every available signal.
290
430
  *
291
431
  * Every source is independent and failure-tolerant: a source that throws or
292
432
  * needs a session the listener lacks contributes nothing.
293
433
  */
294
- async #candidates({ prompt = '', count = 30 } = {}) {
434
+ async #candidates({ prompt = '' } = {}) {
295
435
  const digest = this.store.tasteDigest();
296
- const excluded = new Set([...digest.dislikedIds, ...digest.recentIds]);
436
+ // Queued tracks are excluded too: a batch is appended, and a pick the queue
437
+ // already holds is dropped there, so the batch would silently come up short.
438
+ const excluded = new Set([
439
+ ...digest.dislikedIds,
440
+ ...digest.recentIds,
441
+ ...this.player.queue.map((track) => track.id),
442
+ ...[...digest.skipCounts].filter(([, skips]) => skips >= SKIPS_TO_EXCLUDE).map(([id]) => id),
443
+ ]);
444
+ const brief = prompt.trim();
445
+ const seeds = this.#seeds(digest);
446
+ // Every source is fetched at once and fails alone; the pool is then
447
+ // assembled in priority order, so a track two sources share is claimed by
448
+ // the one that ranks it higher, however the requests happened to finish.
449
+ const settled = (promise) => promise.catch(() => []);
450
+ const briefing = brief ? this.#briefTracks(brief, excluded).catch(() => ({ tracks: [], terms: [brief] })) : null;
451
+ const sources = {
452
+ prompt: brief ? settled(briefing.then((result) => result.tracks)) : [],
453
+ liked: settled(this.#tracksByIds(this.#likedSample(excluded))),
454
+ fm: settled(this.#fmTracks()),
455
+ similar: settled(this.#similarTracks(seeds, excluded)),
456
+ daily: settled(this.#feedTracks(`daily:${this.#account()}`, TTL.daily, () => this.api.recommendSongs(30), this.#quota().daily, excluded)),
457
+ new: settled(this.#feedTracks('new', TTL.new, () => this.api.personalizedNewsongs(30), this.#quota().new, excluded)),
458
+ chart: settled(this.#chartTracks(excluded)),
459
+ };
460
+
461
+ // The newest likes, for the taste picture; cached per track, so only new
462
+ // likes cost a lookup after the first plan.
463
+ const likedTaste = this.#tracksByIds(this.store.feedback.likes.slice(0, LIKED_TASTE)).catch(() => []);
464
+
297
465
  const pool = [];
298
466
  const seen = new Set();
299
- const add = (tracks, origin) => {
300
- for (const track of tracks ?? []) {
467
+ for (const origin of ORIGINS) {
468
+ for (const track of await sources[origin]) {
301
469
  if (!track?.id || seen.has(track.id) || excluded.has(track.id)) continue;
302
470
  seen.add(track.id);
303
471
  pool.push({ ...track, origin });
304
472
  }
473
+ }
474
+ const trimmed = pool.slice(0, MAX_POOL);
475
+ // Covers cost a request only when some track came without one.
476
+ const covered = trimmed.some((track) => !track.picUrl)
477
+ ? await this.pacer.run(() => this.api.withCovers(trimmed)).catch(() => trimmed)
478
+ : trimmed;
479
+ return {
480
+ pool: covered,
481
+ digest: this.#withLikes(digest, await likedTaste),
482
+ terms: briefing ? (await briefing).terms : [],
305
483
  };
484
+ }
306
485
 
307
- const current = this.player.current();
308
- const seeds = [current?.id, ...this.store.recentIds(MAX_SEEDS)].filter(Boolean).slice(0, MAX_SEEDS);
486
+ /**
487
+ * Who the personal sources belong to. The cookie, not the account record,
488
+ * because the record is fetched after a sign-in and would briefly read the
489
+ * same for two different people. Only a digest of it is ever kept.
490
+ */
491
+ #account() {
492
+ const cookie = this.api.jar?.get?.('MUSIC_U');
493
+ if (cookie) return createHash('sha256').update(cookie).digest('hex').slice(0, 12);
494
+ return this.api.authenticated ? 'session' : 'anonymous';
495
+ }
309
496
 
310
- const tasks = [];
311
- // Similarity expansion from what is playing and what was played recently.
312
- for (const seed of seeds) {
313
- tasks.push(
314
- this.api.simiSongs(seed, { limit: 12 }).then((tracks) => add(tracks, 'similar')).catch(() => {}),
315
- );
497
+ /** Track details by id, each cached on its own so a sample costs only the misses. */
498
+ async #tracksByIds(ids) {
499
+ if (ids.length === 0 || !this.api.songDetail) return [];
500
+ const missing = ids.filter((id) => this.cache.peek(`track:${id}`) === undefined);
501
+ for (let offset = 0; offset < missing.length; offset += DETAIL_BATCH) {
502
+ const batch = missing.slice(offset, offset + DETAIL_BATCH);
503
+ for (const track of await this.pacer.run(() => this.api.songDetail(batch))) {
504
+ if (track?.id) this.cache.set(`track:${track.id}`, track, TTL.track);
505
+ }
316
506
  }
317
- // A mood brief is a search term; the raw text searches well enough.
318
- if (prompt.trim()) {
319
- tasks.push(
320
- this.api.searchSongs(prompt.trim(), { limit: 15 }).then((r) => add(r.tracks, 'prompt')).catch(() => {}),
321
- );
507
+ return ids.map((id) => this.cache.peek(`track:${id}`)).filter(Boolean);
508
+ }
509
+
510
+ /** The pool's quotas: personal sources take over once there is an account. */
511
+ #quota() {
512
+ return this.api.authenticated ? SIGNED_IN_QUOTA : QUOTA;
513
+ }
514
+
515
+ /**
516
+ * Fold the account's likes into the taste picture.
517
+ *
518
+ * The history only knows what played through this plugin, and much of that
519
+ * the DJ chose itself; the likes are what the listener chose, anywhere. So
520
+ * a liked track's artists count toward the favourites — twice what a play
521
+ * counts — and the model is shown liked songs by name, not only the few that
522
+ * happen to be in the history.
523
+ */
524
+ #withLikes(digest, liked) {
525
+ if (liked.length === 0) return digest;
526
+ const scores = this.store.heardArtists();
527
+ for (const track of liked) {
528
+ for (const artist of track.artists ?? []) scores.set(artist, (scores.get(artist) ?? 0) + LIKED_ARTIST_WEIGHT);
322
529
  }
323
- // Editorial and anonymous feeds keep the pool from collapsing to one genre.
324
- tasks.push(this.api.recommendSongs(20).then((tracks) => add(tracks, 'daily')).catch(() => {}));
325
- tasks.push(this.api.personalizedNewsongs(15).then((tracks) => add(tracks, 'new')).catch(() => {}));
326
- tasks.push(
327
- this.api
328
- .playlistDetail('3778678', { limit: 40 })
329
- .then((playlist) => add(playlist.tracks, 'chart'))
330
- .catch(() => {}),
530
+ return {
531
+ ...digest,
532
+ topArtists: [...scores].sort((a, b) => b[1] - a[1]).slice(0, 8).map(([artist]) => artist),
533
+ liked: sampleInOrder(liked, 15).map((track) => `${track.name} — ${(track.artists ?? []).join('/')}`),
534
+ };
535
+ }
536
+
537
+ /** A cached list, sampled down to its quota of eligible tracks. */
538
+ async #feedTracks(key, ttlMs, load, quota, excluded) {
539
+ const tracks = await this.cache.get(key, ttlMs, () => this.pacer.run(load));
540
+ return sampleInOrder((tracks ?? []).filter((track) => track?.id && !excluded.has(track.id)), quota);
541
+ }
542
+
543
+ /** Personal FM answers a different three on every call, so it is never cached. */
544
+ async #fmTracks() {
545
+ if (!this.api.authenticated || !this.api.personalFm) return [];
546
+ const calls = Array.from({ length: FM_CALLS }, () => this.pacer.run(() => this.api.personalFm()).catch(() => []));
547
+ return (await Promise.all(calls)).flat();
548
+ }
549
+
550
+ /**
551
+ * Similar tracks for each seed. Every eligible track of the first seed — the
552
+ * one playing — is kept, and the other seeds share what is left of the quota.
553
+ */
554
+ async #similarTracks(seeds, excluded) {
555
+ const lists = await Promise.all(
556
+ seeds.map((seed) =>
557
+ this.cache
558
+ .get(`similar:${seed}`, TTL.similar, () => this.pacer.run(() => this.api.simiSongs(seed, { limit: 20 })))
559
+ .catch(() => []),
560
+ ),
561
+ );
562
+ const eligible = (tracks) => (tracks ?? []).filter((track) => track?.id && !excluded.has(track.id));
563
+ const [first = [], ...rest] = lists.map(eligible);
564
+ const lead = first.slice(0, this.#quota().similar);
565
+ return [...lead, ...sampleInOrder(rest.flat(), this.#quota().similar - lead.length)];
566
+ }
567
+
568
+ /**
569
+ * One playlist's track ids and whatever full tracks came with them, cached.
570
+ *
571
+ * For a playlist the account does not own NetEase returns full tracks only
572
+ * for the first 20, but every id. Sampling from the ids is what reaches the
573
+ * rest of a 100-track playlist, rather than serving its first 20 forever.
574
+ */
575
+ async #playlist(id, ttlMs) {
576
+ const playlist = await this.cache.get(`playlist:${id}`, ttlMs, () =>
577
+ this.pacer.run(() => this.api.playlistDetail(id, { limit: 1000 })),
578
+ );
579
+ const tracks = playlist?.tracks ?? [];
580
+ return {
581
+ ids: playlist?.trackIds?.length ? playlist.trackIds : tracks.map((track) => track.id),
582
+ known: new Map(tracks.map((track) => [track.id, track])),
583
+ };
584
+ }
585
+
586
+ /** Sample eligible ids from playlists, resolving only those that came without details. */
587
+ async #samplePlaylists(playlists, quota, excluded) {
588
+ const known = new Map();
589
+ const ids = [];
590
+ for (const playlist of playlists) {
591
+ for (const [id, track] of playlist.known) known.set(id, track);
592
+ for (const id of playlist.ids) if (!excluded.has(id) && !ids.includes(id)) ids.push(id);
593
+ }
594
+ const chosen = sampleInOrder(ids, quota);
595
+ const resolved = await this.#tracksByIds(chosen.filter((id) => !known.has(id))).catch(() => []);
596
+ for (const track of resolved) known.set(track.id, track);
597
+ return chosen.map((id) => known.get(id)).filter(Boolean);
598
+ }
599
+
600
+ /**
601
+ * A sample across the four general charts. One chart alone served the same
602
+ * forty hits every plan; the genre charts are left out because a classical
603
+ * or rap chart is as likely to be off-taste as on it.
604
+ */
605
+ async #chartTracks(excluded) {
606
+ const charts = await Promise.all(CHARTS.map((id) => this.#playlist(id, TTL.chart).catch(() => null)));
607
+ return this.#samplePlaylists(charts.filter(Boolean), this.#quota().chart, excluded);
608
+ }
609
+
610
+ /**
611
+ * Tracks for a mood brief. Song search only matches titles and lyrics, so a
612
+ * mood mostly finds tracks literally named after it; listeners name and tag
613
+ * playlists by mood, so the brief's best-loved playlists carry most of it.
614
+ *
615
+ * @returns {Promise<{tracks: object[], terms: string[]}>}
616
+ */
617
+ async #briefTracks(brief, excluded) {
618
+ const terms = await this.#briefTerms(brief);
619
+ const songs = this.#feedTracks(
620
+ `songs:${terms[0]}`,
621
+ TTL.search,
622
+ () => this.api.searchSongs(terms[0], { limit: 30 }).then((result) => result.tracks),
623
+ this.#quota().promptSongs,
624
+ excluded,
625
+ ).catch(() => []);
626
+ const playlists = (async () => {
627
+ if (!this.api.searchPlaylists) return [];
628
+ // Every term gets its share, so one broad term cannot take every slot.
629
+ const perTerm = Math.ceil(BRIEF_PLAYLISTS / terms.length);
630
+ const found = await Promise.all(
631
+ terms.map((term) =>
632
+ this.cache
633
+ .get(`playlists:${term}`, TTL.search, () => this.pacer.run(() => this.api.searchPlaylists(term, { limit: 10 })))
634
+ .catch(() => []),
635
+ ),
636
+ );
637
+ // Among the most relevant few, the most played: relevance alone surfaces
638
+ // a 14-track playlist nobody listens to as readily as a curated one.
639
+ const chosen = new Map();
640
+ for (const results of found) {
641
+ const best = results
642
+ .slice(0, 6)
643
+ .filter((playlist) => playlist.trackCount >= MIN_PLAYLIST_TRACKS && !chosen.has(playlist.id))
644
+ .sort((a, b) => b.playCount - a.playCount)
645
+ .slice(0, perTerm);
646
+ for (const playlist of best) chosen.set(playlist.id, playlist);
647
+ }
648
+ const ids = [...chosen.keys()].slice(0, BRIEF_PLAYLISTS);
649
+ const loaded = await Promise.all(ids.map((id) => this.#playlist(id, TTL.playlist).catch(() => null)));
650
+ return this.#samplePlaylists(loaded.filter(Boolean), this.#quota().promptPlaylists, excluded);
651
+ })().catch(() => []);
652
+ // Playlist tracks first: they are the stronger match for a mood.
653
+ return { tracks: [...(await playlists), ...(await songs)], terms };
654
+ }
655
+
656
+ /**
657
+ * The search terms a brief is looked up by: the model's rewrite when there is
658
+ * one, the brief as written otherwise.
659
+ *
660
+ * NetEase playlists are named in Chinese, so an English brief matches badly —
661
+ * "90s cantopop" finds 90s hip-hop. One model call turns the brief into the
662
+ * terms a listener would name such a playlist, and it is made once per brief,
663
+ * not per plan: a brief means the same thing next week. A brief that could
664
+ * not be rewritten is searched as written, and retried after a while rather
665
+ * than on every plan.
666
+ *
667
+ * @returns {Promise<string[]>}
668
+ */
669
+ #briefTerms(brief) {
670
+ const key = `terms:${brief}`;
671
+ const cached = this.cache.peek(key);
672
+ if (cached !== undefined) return cached;
673
+ const pending = this.#rewriteBrief(brief).then(
674
+ (terms) => {
675
+ if (!terms) {
676
+ this.cache.set(key, Promise.resolve([brief]), TTL.termsRetry);
677
+ return [brief];
678
+ }
679
+ this.cache.set(key, Promise.resolve(terms), TTL.terms);
680
+ this.logger?.info?.(`[music] DJ brief "${brief}" will be searched as: ${terms.join('; ')}`);
681
+ return terms;
682
+ },
683
+ (error) => {
684
+ this.logger?.warn?.(`[music] DJ brief could not be rewritten, searching it as written: ${describeFailure(error)}`);
685
+ this.cache.set(key, Promise.resolve([brief]), TTL.termsRetry);
686
+ return [brief];
687
+ },
331
688
  );
332
- await Promise.all(tasks);
689
+ this.cache.set(key, pending, TTL.termsRetry);
690
+ return pending;
691
+ }
333
692
 
334
- // Keep the prompt cheap when the pool overflowed: prefer prompt/similar
335
- // matches, then the feeds.
336
- const priority = { prompt: 0, similar: 1, daily: 2, new: 3, chart: 4 };
337
- pool.sort((a, b) => (priority[a.origin] ?? 9) - (priority[b.origin] ?? 9));
338
- const trimmed = pool.slice(0, Math.max(count, MAX_POOL));
339
- return { pool: await this.api.withCovers(trimmed).catch(() => trimmed), digest };
693
+ /**
694
+ * Ask the model for a brief's search terms, on the same route and under the
695
+ * same identity as curation.
696
+ *
697
+ * @returns {Promise<string[] | null>} `null` when no model route is available.
698
+ * @throws {Error} when the model answered with nothing usable.
699
+ */
700
+ async #rewriteBrief(brief) {
701
+ const llm = this.resolveLlm?.();
702
+ if (!llm?.stream) return null;
703
+ const target = await this.#resolveTarget(llm);
704
+ if (!target?.provider || !target?.model) return null;
705
+ const request = curationRequest({
706
+ target,
707
+ sessionId: this.sessionId,
708
+ messages: [
709
+ {
710
+ role: 'user',
711
+ content: [
712
+ {
713
+ type: 'text',
714
+ text:
715
+ "Rewrite a listener's music brief into short search keywords for NetEase Cloud Music playlist search. " +
716
+ `Give up to ${BRIEF_TERMS} keywords, each 2 to 8 words, the way listeners name playlists there: ` +
717
+ 'in Chinese, by genre, mood, era, language or scene; keep an artist or genre name in its usual form. ' +
718
+ 'Each keyword should find the brief on its own. ' +
719
+ 'Reply with JSON only, no prose, no code fence: {"terms":["<keyword>"]}',
720
+ },
721
+ { type: 'text', text: `Brief: ${brief}` },
722
+ ],
723
+ },
724
+ ],
725
+ });
726
+ const text = await this.#collect(llm.stream(request));
727
+ const json = /\{[\s\S]*\}/.exec(text ?? '');
728
+ if (!json) throw new Error('the rewrite contained no JSON object');
729
+ const terms = (JSON.parse(json[0]).terms ?? [])
730
+ .filter((term) => typeof term === 'string')
731
+ .map((term) => term.trim())
732
+ .filter((term) => term.length > 0 && term.length <= 40);
733
+ const unique = [...new Set(terms)].slice(0, BRIEF_TERMS);
734
+ if (unique.length === 0) throw new Error('the model returned no search terms');
735
+ return unique;
340
736
  }
341
737
 
342
738
  // --------------------------------------------------------------- model tier
@@ -386,10 +782,10 @@ export class AiDj {
386
782
  * Decide which provider route to call.
387
783
  *
388
784
  * An explicit pin always wins. Otherwise the deployment's own model selection
389
- * is inherited — `agent-default-model`, which is the same choice the composer
390
- * picker writes and therefore the model the agent loop runs on — so the
391
- * session model and the DJ's model are two separable decisions that agree
392
- * by default. Only when neither exists does discovery run.
785
+ * is inherited — `agent-default-model`, the same choice the composer picker
786
+ * writes and new conversations start on — so the session model and the DJ's
787
+ * model are two separable decisions that agree by default. Only the choice
788
+ * is inherited; the call itself stays a leaf call. Only when neither exists does discovery run.
393
789
  *
394
790
  * Discovery is a convenience, not a recommendation: the catalogue's first
395
791
  * entry is arbitrary, so pinning both fields is the only way to know which
@@ -438,17 +834,30 @@ export class AiDj {
438
834
  * One place builds the prompt, so a leaf call and any future caller reason
439
835
  * about exactly the same brief.
440
836
  */
441
- #brief({ pool, digest, prompt, count }) {
837
+ #brief({ pool, digest, prompt, count, follows }) {
838
+ const label = (track) => `${track.name} — ${(track.artists ?? []).join('/')}`;
442
839
  const catalogue = pool
443
- .map((track, index) => `${index}. ${track.name} — ${(track.artists ?? []).join('/')}${track.album ? ` (${track.album})` : ''}`)
840
+ .map((track, index) =>
841
+ `${index}. ${label(track)}${track.album ? ` (${track.album})` : ''}${track.origin === 'liked' ? ' [liked]' : ''}`)
444
842
  .join('\n');
843
+ const current = this.player.current();
844
+ const upNext = follows ? this.player.remaining().slice(-5) : [];
845
+ const skippedArtists = [...digest.skippedArtists]
846
+ .filter(([, skips]) => skips >= SKIPS_TO_REPORT_ARTIST)
847
+ .sort((a, b) => b[1] - a[1])
848
+ .slice(0, 8)
849
+ .map(([artist, skips]) => `${artist} (${skips})`);
445
850
  return [
446
851
  `Mood or request: ${prompt?.trim() || '(none — continue the current listening session)'}`,
447
- `Currently playing: ${this.player.current() ? `${this.player.current().name} — ${this.player.current().artists.join('/')}` : '(nothing)'}`,
852
+ `Currently playing: ${current ? label(current) : '(nothing)'}`,
853
+ upNext.length ? `Already queued after it: ${upNext.map(label).join('; ')}` : '',
854
+ follows && follows !== current ? `Your picks play after: ${label(follows)}` : '',
448
855
  digest.recentlyPlayed.length ? `Recently played: ${digest.recentlyPlayed.join('; ')}` : '',
449
856
  digest.topArtists.length ? `Favourite artists: ${digest.topArtists.join(', ')}` : '',
450
857
  digest.liked.length ? `Liked: ${digest.liked.join('; ')}` : '',
451
858
  digest.disliked.length ? `Disliked (never pick): ${digest.disliked.join('; ')}` : '',
859
+ digest.skipped.length ? `Skipped early (steer away from these): ${digest.skipped.join('; ')}` : '',
860
+ skippedArtists.length ? `Often skipped artists (skips): ${skippedArtists.join(', ')}` : '',
452
861
  '',
453
862
  `CANDIDATES (choose only by index):\n${catalogue}`,
454
863
  '',
@@ -470,7 +879,8 @@ export class AiDj {
470
879
  'You are the music programmer for a personal NetEase Cloud Music player. ' +
471
880
  'Choose the next tracks from the CANDIDATES list only, by index. ' +
472
881
  'Favour artists the listener likes and the requested mood; keep variety — never place two tracks by the same artist back to back; ' +
473
- 'avoid anything listed as recently played or disliked. ' +
882
+ 'avoid anything listed as recently played or disliked, and pick less of what the listener skips. ' +
883
+ 'Candidates marked [liked] are the listener\'s own likes, not heard for a while: mix one in when it fits, but do not fill the set with them. ' +
474
884
  'Reply with JSON only, no prose, no code fence: ' +
475
885
  '{"vibe":"<one short line describing the set>","picks":[{"index":<candidate index>,"why":"<max 8 words>"}]}',
476
886
  },
@@ -488,7 +898,7 @@ export class AiDj {
488
898
  *
489
899
  * @throws {Error} when the answer carries no JSON object or no usable index.
490
900
  */
491
- #parseAnswer(text, pool) {
901
+ #parseAnswer(text, pool, count) {
492
902
  const json = /\{[\s\S]*\}/.exec(text ?? '');
493
903
  if (!json) throw new Error('response contained no JSON object');
494
904
  const parsed = JSON.parse(json[0]);
@@ -503,7 +913,8 @@ export class AiDj {
503
913
  seen.add(index);
504
914
  ordered.push(index);
505
915
  }
506
- return { picks: ordered, vibe: typeof parsed.vibe === 'string' ? parsed.vibe : '' };
916
+ // A model asked for five that answers with twenty would otherwise flood the queue.
917
+ return { picks: ordered.slice(0, count), vibe: typeof parsed.vibe === 'string' ? parsed.vibe : '' };
507
918
  }
508
919
 
509
920
  /** Record a model-tier success: clear the stale reason and log what ran. */
@@ -528,7 +939,7 @@ export class AiDj {
528
939
  * @returns {Promise<{picks: number[], vibe: string} | null>}
529
940
  * `null` when the tier is unavailable or answered with nothing usable.
530
941
  */
531
- async #askModel({ pool, digest, prompt, count }) {
942
+ async #askModel({ pool, digest, prompt, count, follows }) {
532
943
  const llm = this.resolveLlm?.();
533
944
  if (!llm?.stream) {
534
945
  return this.#decline('no LLM service is mounted (ctx.get("llm") returned nothing)');
@@ -545,7 +956,7 @@ export class AiDj {
545
956
  }
546
957
  this.resolvedFrom = target.source;
547
958
 
548
- const brief = this.#brief({ pool, digest, prompt, count });
959
+ const brief = this.#brief({ pool, digest, prompt, count, follows });
549
960
  try {
550
961
  const request = curationRequest({
551
962
  target,
@@ -553,7 +964,7 @@ export class AiDj {
553
964
  sessionId: this.sessionId,
554
965
  });
555
966
  const text = await this.#collect(llm.stream(request));
556
- return this.#accept(this.#parseAnswer(text, pool), target);
967
+ return this.#accept(this.#parseAnswer(text, pool, count), target);
557
968
  } catch (error) {
558
969
  return this.#decline(describeFailure(error));
559
970
  }
@@ -564,41 +975,48 @@ export class AiDj {
564
975
  /**
565
976
  * Score and interleave candidates without a model.
566
977
  *
567
- * Scoring is deliberately simple and explainable: artist affinity dominates,
568
- * familiarity is penalised, explicit dislikes are excluded earlier, and a
569
- * small jitter keeps repeat requests from returning an identical order.
978
+ * Scoring is deliberately simple and explainable: a mood-brief match and
979
+ * artist affinity dominate, skips count against a track and its artists,
980
+ * recently played and disliked tracks were already excluded from the pool,
981
+ * and a small jitter keeps repeat requests from returning an identical order.
570
982
  */
571
- #rank({ pool, digest, count }) {
983
+ #rank({ pool, digest, count, follows }) {
572
984
  const favourites = new Set(digest.topArtists);
573
985
  const currentArtists = new Set(this.player.current()?.artists ?? []);
574
- const playedArtists = new Map();
575
- for (const entry of this.store.state.history.slice(0, 60)) {
576
- for (const artist of entry.artists ?? []) playedArtists.set(artist, (playedArtists.get(artist) ?? 0) + 1);
577
- }
578
- const recentlyPlayed = new Set(digest.recentIds);
986
+ const playedArtists = this.store.heardArtists(60);
579
987
 
580
988
  const scored = pool.map((track) => {
581
989
  let score = Math.random() * 0.8;
990
+ // The brief is the listener's explicit ask; without this weight a chart
991
+ // hit by a favourite artist outranks every track that matches it.
992
+ // FM is personalised, similarity is not; a like is a known good song,
993
+ // weighted lightly so the set stays a discovery rather than a replay.
994
+ if (track.origin === 'prompt') score += 3.0;
995
+ else if (track.origin === 'fm') score += 1.0;
996
+ else if (track.origin === 'similar') score += 0.6;
997
+ else if (track.origin === 'liked') score += 0.5;
582
998
  for (const artist of track.artists ?? []) {
583
999
  if (favourites.has(artist)) score += 2.2;
584
1000
  if (currentArtists.has(artist)) score += 1.4;
585
1001
  score += Math.min((playedArtists.get(artist) ?? 0) * 0.15, 1.0);
1002
+ score -= Math.min((digest.skippedArtists.get(artist) ?? 0) * 0.6, 2.4);
586
1003
  }
587
- if (!recentlyPlayed.has(track.id)) score += 1.0;
1004
+ if (digest.skipCounts.has(track.id)) score -= 1.5;
588
1005
  if (track.vip) score -= 0.4; // still playable when signed in, but riskier
589
1006
  return { track, score };
590
1007
  });
591
1008
  scored.sort((a, b) => b.score - a.score);
592
1009
 
593
- // Interleave so one artist cannot own consecutive slots.
1010
+ // Interleave so one artist cannot own consecutive slots, starting from the
1011
+ // track the batch will actually follow.
594
1012
  const picked = [];
595
- let lastArtist = this.player.current()?.artists?.[0] ?? null;
1013
+ let lastArtists = new Set(follows?.artists ?? []);
596
1014
  while (picked.length < count && scored.length > 0) {
597
- let chosen = scored.findIndex((entry) => entry.track.artists?.[0] !== lastArtist);
1015
+ let chosen = scored.findIndex((entry) => !(entry.track.artists ?? []).some((artist) => lastArtists.has(artist)));
598
1016
  if (chosen === -1) chosen = 0;
599
1017
  const [entry] = scored.splice(chosen, 1);
600
1018
  picked.push(entry.track);
601
- lastArtist = entry.track.artists?.[0] ?? null;
1019
+ lastArtists = new Set(entry.track.artists ?? []);
602
1020
  }
603
1021
  return picked;
604
1022
  }
@@ -610,15 +1028,19 @@ export class AiDj {
610
1028
  * @param {object} [options]
611
1029
  * @param {string} [options.prompt] mood/request brief.
612
1030
  * @param {number} [options.count] how many tracks to choose.
1031
+ * @param {object|null} [options.follows] the track the batch will play after;
1032
+ * the queue's last track by default, since a batch is appended.
613
1033
  * @returns {Promise<Plan>}
614
1034
  */
615
- async plan({ prompt = '', count = 5 } = {}) {
1035
+ async plan({ prompt = '', count = 5, follows = this.player.queue.at(-1) ?? null } = {}) {
616
1036
  const size = Math.min(Math.max(Number(count) || 5, 1), 25);
617
- const { pool, digest } = await this.#candidates({ prompt, count: size });
1037
+ const { pool, digest, terms } = await this.#candidates({ prompt });
1038
+ /** What the brief was searched as, so a rewrite is observable. */
1039
+ const searchedAs = terms;
618
1040
  if (pool.length === 0) {
619
- return { tracks: [], source: 'heuristic', note: 'no candidates were available', poolSize: 0 };
1041
+ return { tracks: [], source: 'heuristic', note: 'no candidates were available', poolSize: 0, searchedAs };
620
1042
  }
621
- const answer = await this.#askModel({ pool, digest, prompt, count: size });
1043
+ const answer = await this.#askModel({ pool, digest, prompt, count: size, follows });
622
1044
  if (answer) {
623
1045
  return {
624
1046
  tracks: answer.picks.map((index) => pool[index]),
@@ -627,24 +1049,29 @@ export class AiDj {
627
1049
  /** Which provider route curated, so the choice is observable. */
628
1050
  route: `${answer.target.provider}/${answer.target.model}`,
629
1051
  poolSize: pool.length,
1052
+ searchedAs,
630
1053
  };
631
1054
  }
632
1055
  return {
633
- tracks: this.#rank({ pool, digest, count: size }),
1056
+ tracks: this.#rank({ pool, digest, count: size, follows }),
634
1057
  source: 'heuristic',
635
1058
  note: this.modelError
636
1059
  ? `model tier unavailable (${this.modelError}); used similarity, charts and taste feedback`
637
1060
  : 'no model configured; used similarity, charts and taste feedback',
638
1061
  poolSize: pool.length,
1062
+ searchedAs,
639
1063
  };
640
1064
  }
641
1065
 
642
1066
  /**
643
1067
  * Extend the queue when it runs low. Safe to call on every track change: the
644
1068
  * busy flag and the threshold check make it a no-op most of the time.
1069
+ * @param {object} [options]
1070
+ * @param {boolean} [options.force] plan even when disabled or the queue is deep.
1071
+ * @param {number} [options.count] batch size, overriding the player's setting.
645
1072
  * @returns {Promise<Plan | null>}
646
1073
  */
647
- async topUp({ force = false } = {}) {
1074
+ async topUp({ force = false, count } = {}) {
648
1075
  const settings = this.store.settings;
649
1076
  if (!this.player.dj.enabled && !force) return null;
650
1077
  if (this.busy) return null;
@@ -655,7 +1082,10 @@ export class AiDj {
655
1082
  this.player.dj.busy = true;
656
1083
  this.player.bump();
657
1084
  try {
658
- const plan = await this.plan({ prompt: settings.djPrompt ?? '', count: settings.djBatchSize ?? 5 });
1085
+ const planned = await this.plan({ prompt: settings.djPrompt ?? '', count: count ?? settings.djBatchSize ?? 5 });
1086
+ // The queue can change while the plan is in flight; report only what lands.
1087
+ const queued = new Set(this.player.queue.map((track) => track.id));
1088
+ const plan = { ...planned, tracks: planned.tracks.filter((track) => !queued.has(track.id)) };
659
1089
  if (plan.tracks.length === 0) {
660
1090
  this.player.dj = { ...this.player.dj, busy: false, error: plan.note ?? 'no tracks found', lastPlanAt: Date.now() };
661
1091
  return plan;
@@ -664,7 +1094,7 @@ export class AiDj {
664
1094
  // `play: false` preserves whatever the listener chose, so a top-up while
665
1095
  // paused does not start playback, while a queue refilled after the last
666
1096
  // track ended still resumes because `playing` was already true.
667
- this.player.append(plan.tracks, { source: plan.source, play: false });
1097
+ this.player.append(plan.tracks, { source: plan.source, play: false, queuedBy: 'dj' });
668
1098
  this.player.dj = {
669
1099
  ...this.player.dj,
670
1100
  busy: false,
@@ -676,6 +1106,7 @@ export class AiDj {
676
1106
  route: plan.route ?? null,
677
1107
  added: plan.tracks.length,
678
1108
  names: plan.tracks.map((track) => `${track.name} — ${(track.artists ?? []).join('/')}`),
1109
+ searchedAs: plan.searchedAs ?? [],
679
1110
  },
680
1111
  };
681
1112
  this.player.bump();
@@ -699,9 +1130,10 @@ export class AiDj {
699
1130
  async start({ prompt, count = 8 } = {}) {
700
1131
  this.store.updateSettings({ djEnabled: true, ...(prompt === undefined ? {} : { djPrompt: prompt }) });
701
1132
  this.player.dj.enabled = true;
702
- const plan = await this.plan({ prompt: prompt ?? this.store.settings.djPrompt ?? '', count });
1133
+ // The batch replaces the queue, so nothing precedes its first track.
1134
+ const plan = await this.plan({ prompt: prompt ?? this.store.settings.djPrompt ?? '', count, follows: null });
703
1135
  if (plan.tracks.length > 0) {
704
- this.player.setQueue(plan.tracks, { startIndex: 0, play: true, source: plan.source });
1136
+ this.player.setQueue(plan.tracks, { startIndex: 0, play: true, source: plan.source, queuedBy: 'dj' });
705
1137
  this.player.dj.lastPlanAt = Date.now();
706
1138
  this.player.dj.lastPlan = {
707
1139
  source: plan.source,
@@ -709,6 +1141,7 @@ export class AiDj {
709
1141
  route: plan.route ?? null,
710
1142
  added: plan.tracks.length,
711
1143
  names: plan.tracks.map((track) => `${track.name} — ${(track.artists ?? []).join('/')}`),
1144
+ searchedAs: plan.searchedAs ?? [],
712
1145
  };
713
1146
  this.player.dj.error = null;
714
1147
  } else {