@doitian/dsh-music 0.1.9 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  NetEase Cloud Music ([music.163.com](https://music.163.com)) playback and an AI DJ for DeepSeek Harness.
4
4
 
5
- A **Music** entry in the DSH sidebar opens a player: queue, synced lyrics, QR sign-in, NetEase likes, and an AI DJ that keeps the queue stocked. The agent can drive the same player through seven tools.
5
+ A **Music** entry in the DSH sidebar opens a player: queue, song details and synced lyrics, QR sign-in, NetEase likes, and an AI DJ that keeps the queue stocked. The agent can drive the same player through seven tools.
6
6
 
7
7
  Developing the plugin, or curious how it works? See [docs/DESIGN.md](https://github.com/doitian/dsh-music/blob/main/docs/DESIGN.md).
8
8
 
@@ -42,7 +42,9 @@ Music plays in the Harness window, so keep it open. Playback continues while you
42
42
 
43
43
  ## Using the player
44
44
 
45
- On a wide window the player has two columns: what is playing on the left — cover, the song's controls, transport and lyrics — and what comes next on the right — the AI DJ card and the queue. On a narrow one they stack.
45
+ On a wide window the player has two columns: what is playing on the left — cover, the song's controls, transport, and the song's details or lyrics — and what comes next on the right — the AI DJ card and the queue. On a narrow one they stack.
46
+
47
+ **Details and lyrics.** Under the transport controls, **Details** shows what NetEase knows about the song: its album (edition, release date, label), genre, tags, language and tempo, awards, and the films or shows it was featured in. Below them, the DJ's model writes a short introduction to the song and its singer from what NetEase holds. It loads after everything else, so the song starts at once. Click the introduction to see NetEase's own text instead: a review, and introductions to each singer and to the album. Click one of those paragraphs to read all of it. Without a model, NetEase's text shows directly. Switch to **Lyrics** for the synced lines. The player remembers which one you chose.
46
48
 
47
49
  **Quality.** Pick a level under the transport controls: `standard`, `higher`, `exhigh` (320 kbps, the default), `lossless`, `hires`, or the spatial tiers `jymaster`, `dolby`, `sky`, `jyeffect`. If a track doesn't offer the level, playback steps down until something plays, and the caption shows what was actually served.
48
50
 
@@ -53,6 +55,7 @@ On a wide window the player has two columns: what is playing on the left — cov
53
55
  | ♡ (beside the title, or on a queue row) | Like on your NetEase account. Click again to unlike. |
54
56
  | ✕ (beside the title) | Dislike: the track leaves the queue, and the next one plays. Local only; the DJ stops picking it. |
55
57
  | ✕ (queue row) | Remove the track. An unrated track is also recorded as disliked. |
58
+ | Clear (queue header) | Empty the queue except the song playing. Nothing is rated. |
56
59
 
57
60
  **Skips.** Pressing next before 30 s (or before a quarter of a long track) counts as a skip. One skip lowers a track's rank; two remove it from the DJ's picks, and skipped plays count against the artist. A dislike is not also counted as a skip.
58
61
 
@@ -60,6 +63,8 @@ On a wide window the player has two columns: what is playing on the left — cov
60
63
 
61
64
  Turn it on with the switch in the player's AI DJ card, or with `music_dj`. When fewer than 3 tracks remain, the DJ appends a batch of 5. It only stocks the queue; it never starts or stops playback.
62
65
 
66
+ The queue is saved, so after a restart it's back where you left it, paused, and you can press play before the DJ plans anything.
67
+
63
68
  **How it learns your taste:** from your NetEase likes, and from songs you hear through. A song the DJ picked counts only once you've listened past the skip window, so its own picks can't teach it what you like.
64
69
 
65
70
  **Where it looks:** songs similar to what you've heard and liked, personal FM and liked songs you haven't heard in three days (when signed in), the daily recommendations, new songs, and the four main charts. Signed in, the charts and new songs get fewer slots and your own sources more. Each source is cached for hours and sampled, so batches vary; requests to NetEase are spaced out rather than sent in a burst.
@@ -68,6 +73,8 @@ Turn it on with the switch in the player's AI DJ card, or with `music_dj`. When
68
73
 
69
74
  **Mood brief.** Type a mood in the AI DJ card, such as `雨天 爵士` or `90s cantopop`. The DJ searches NetEase playlists for it. With a model available, the brief is first rewritten into Chinese search terms, once per brief.
70
75
 
76
+ After you change the mood or set a boost, the DJ's next batch replaces its own picks that haven't played yet, so the new direction starts right away. The song playing and songs you queued yourself stay.
77
+
71
78
  **Who chooses:**
72
79
 
73
80
  - **Model tier:** a model picks from the candidates by your taste and the mood, and writes a one-line vibe. It calls the model directly; it is not an agent and starts no conversation.
package/lib/client.js CHANGED
@@ -256,15 +256,23 @@ window.__ModuleLoader__.load({
256
256
  * so an attempt can legitimately fail and has to be repeatable. Both
257
257
  * outcomes are reported at once, so the host — and the panel's hint —
258
258
  * learns the real state instead of waiting for the next scheduled report.
259
+ * `blocked` says which: only the autoplay policy's `NotAllowedError` is a
260
+ * reason to ask for a click, not an attempt still under way or one
261
+ * interrupted by a new source.
259
262
  */
260
263
  function attemptPlay() {
261
264
  if (playing || disposed) return;
262
265
  playing = true;
263
- const done = () => {
264
- playing = false;
265
- void report({});
266
- };
267
- audio.play().then(done, done);
266
+ audio.play().then(
267
+ () => {
268
+ playing = false;
269
+ void report({ blocked: false });
270
+ },
271
+ (error) => {
272
+ playing = false;
273
+ void report(error?.name === 'NotAllowedError' ? { blocked: true } : {});
274
+ },
275
+ );
268
276
  }
269
277
 
270
278
  /**
package/lib/dj.js CHANGED
@@ -218,6 +218,42 @@ export function curationRequest({ target, messages, sessionId }) {
218
218
  return { ...target, messages, sessionId };
219
219
  }
220
220
 
221
+ /** Each NetEase text an introduction is written from is cut to this many characters. */
222
+ const INTRO_SOURCE_CHARS = 1_200;
223
+
224
+ /** What the model is told about a song: its facts, then NetEase's own prose. */
225
+ export function introMaterial(info) {
226
+ const cut = (text) => (text.length > INTRO_SOURCE_CHARS ? `${text.slice(0, INTRO_SOURCE_CHARS)}…` : text);
227
+ const album = info.album ?? {};
228
+ const artists = info.artists ?? [];
229
+ const released = album.publishTime ? new Date(album.publishTime).getUTCFullYear() : null;
230
+ return [
231
+ `Song: ${info.name}${info.alias?.length ? ` (${info.alias.join(' / ')})` : ''}`,
232
+ `Artists: ${artists.map((artist) => artist.name).join(', ') || '(unknown)'}`,
233
+ album.name ? `Album: ${album.name}${[album.subType || album.type, released, album.company].filter(Boolean).map((note) => `, ${note}`).join('')}` : '',
234
+ info.genres?.length ? `Genre: ${info.genres.join(', ')}` : '',
235
+ info.tags?.length ? `Tags: ${info.tags.join(', ')}` : '',
236
+ info.language ? `Language: ${info.language}` : '',
237
+ info.featuredIn?.length ? `Featured in: ${info.featuredIn.join('; ')}` : '',
238
+ info.awards?.length ? `Awards: ${info.awards.join('; ')}` : '',
239
+ info.review?.text ? `\nA listener's review:\n${cut(info.review.text)}` : '',
240
+ ...artists.filter((artist) => artist.intro).map((artist) => `\nAbout ${artist.name}:\n${cut(artist.intro)}`),
241
+ album.intro ? `\nAbout the album:\n${cut(album.intro)}` : '',
242
+ ]
243
+ .filter(Boolean)
244
+ .join('\n');
245
+ }
246
+
247
+ /** A model's prose without the markdown it was asked not to use. */
248
+ function plainProse(text) {
249
+ return String(text ?? '')
250
+ .replace(/^```\w*\s*|```\s*$/g, '')
251
+ .replace(/^#{1,6}\s+.*$/gm, '')
252
+ .replace(/\*\*|__/g, '')
253
+ .replace(/\n{3,}/g, '\n\n')
254
+ .trim();
255
+ }
256
+
221
257
  /**
222
258
  * @typedef {object} Plan
223
259
  * @property {object[]} tracks chosen tracks, in play order.
@@ -284,6 +320,14 @@ export class AiDj {
284
320
  this.modelError = null;
285
321
  /** Guards against overlapping plans when a track ends mid-plan. */
286
322
  this.busy = false;
323
+ /**
324
+ * Ids of the DJ's upcoming picks chosen before the listener last steered —
325
+ * a new mood brief, or a boost either way. The first plan to land after
326
+ * the steer replaces whichever of them are still unplayed.
327
+ */
328
+ this.stale = new Set();
329
+ /** Counts steers, so a plan begun before one knows its own picks are stale. */
330
+ this.steers = 0;
287
331
  /** The sources' answers, each kept for as long as it plausibly stays the same. */
288
332
  this.cache = new TtlCache({ now });
289
333
  /** Every source request goes through this, so a plan never arrives as a burst. */
@@ -569,6 +613,31 @@ export class AiDj {
569
613
  return {};
570
614
  }
571
615
 
616
+ /** The listener changed direction: every upcoming DJ pick is now stale. */
617
+ #steer() {
618
+ this.steers += 1;
619
+ for (const track of this.player.remaining()) {
620
+ if (track.queuedBy === 'dj') this.stale.add(track.id);
621
+ }
622
+ }
623
+
624
+ /** Queue positions of the stale picks still unplayed, last first so each can be removed in turn. */
625
+ #staleUpcoming() {
626
+ const at = [];
627
+ for (let index = this.player.queue.length - 1; index > this.player.index; index -= 1) {
628
+ const track = this.player.queue[index];
629
+ if (track.queuedBy === 'dj' && this.stale.has(track.id)) at.push(index);
630
+ }
631
+ return at;
632
+ }
633
+
634
+ /** Set the mood brief; a different one is a steer. */
635
+ setPrompt(prompt) {
636
+ const next = String(prompt);
637
+ if (next.trim() !== (this.store.settings.djPrompt ?? '').trim()) this.#steer();
638
+ this.store.updateSettings({ djPrompt: next });
639
+ }
640
+
572
641
  /**
573
642
  * Make a fresh boost felt now rather than a batch or two later.
574
643
  *
@@ -584,6 +653,8 @@ export class AiDj {
584
653
  async applyBoost(track, direction) {
585
654
  const effect = { queued: 0, removed: 0 };
586
655
  if (!this.player.dj.enabled || !track?.id) return effect;
656
+ // Before "more" queues its neighbours: they are picked the new way.
657
+ if (direction === 'more' || direction === 'less') this.#steer();
587
658
  const similar = await this.#neighboursOf(track);
588
659
  if (direction === 'more') {
589
660
  const digest = this.store.tasteDigest();
@@ -864,6 +935,48 @@ export class AiDj {
864
935
  return unique;
865
936
  }
866
937
 
938
+ /**
939
+ * An introduction to a song and its artists for the player's details pane,
940
+ * written by the model from what NetEase holds about them, on the same route
941
+ * and under the same identity as curation.
942
+ *
943
+ * @param {object} info the song's details, as `Netease#songInfo` returns them.
944
+ * @param {{lang?: 'en'|'zh'}} [options] the language the panel is showing.
945
+ * @returns {Promise<{text: string, route: string} | null>} `null` when no model route is available.
946
+ * @throws {Error} when the model failed or wrote nothing.
947
+ */
948
+ async introduce(info, { lang = 'en' } = {}) {
949
+ const llm = this.resolveLlm?.();
950
+ if (!llm?.stream) return null;
951
+ const target = await this.#resolveTarget(llm);
952
+ if (!target?.provider || !target?.model) return null;
953
+ const request = curationRequest({
954
+ target,
955
+ sessionId: this.sessionId,
956
+ messages: [
957
+ {
958
+ role: 'user',
959
+ content: [
960
+ {
961
+ type: 'text',
962
+ text:
963
+ 'Introduce the song below to a listener who is playing it now: what the song is, and who sings it. ' +
964
+ 'Rely on the material given; it is from NetEase Cloud Music. Add nothing you are not sure is true, ' +
965
+ 'and when the material is thin, write less rather than guess. ' +
966
+ 'Two or three short paragraphs separated by a blank line, under ' +
967
+ (lang === 'zh' ? '300 characters in all, in Simplified Chinese. ' : '180 words in all, in English. ') +
968
+ 'Plain text only: no title, no headings, no lists, no markdown.',
969
+ },
970
+ { type: 'text', text: introMaterial(info) },
971
+ ],
972
+ },
973
+ ],
974
+ });
975
+ const text = plainProse(await this.#collect(llm.stream(request)));
976
+ if (!text) throw new Error('the model wrote no introduction');
977
+ return { text, route: `${target.provider}/${target.model}` };
978
+ }
979
+
867
980
  // --------------------------------------------------------------- model tier
868
981
 
869
982
  /**
@@ -1217,6 +1330,7 @@ export class AiDj {
1217
1330
  this.player.dj.busy = true;
1218
1331
  this.player.bump();
1219
1332
  try {
1333
+ const steers = this.steers;
1220
1334
  const planned = await this.plan({ prompt: settings.djPrompt ?? '', count: count ?? settings.djBatchSize ?? 5 });
1221
1335
  // The queue can change while the plan is in flight; report only what lands.
1222
1336
  const queued = new Set(this.player.queue.map((track) => track.id));
@@ -1225,6 +1339,19 @@ export class AiDj {
1225
1339
  this.player.dj = { ...this.player.dj, busy: false, error: plan.note ?? 'no tracks found', lastPlanAt: Date.now() };
1226
1340
  return plan;
1227
1341
  }
1342
+ // The first plan after a steer replaces the picks it made stale, so the
1343
+ // new direction plays next. One begun before the latest steer was picked
1344
+ // the old way, so it lands, but is itself stale for the next plan.
1345
+ let replaced = 0;
1346
+ if (steers === this.steers) {
1347
+ for (const index of this.#staleUpcoming()) {
1348
+ this.player.remove(index);
1349
+ replaced += 1;
1350
+ }
1351
+ this.stale.clear();
1352
+ } else {
1353
+ for (const track of plan.tracks) this.stale.add(track.id);
1354
+ }
1228
1355
  // The DJ only stocks the queue; it never changes the transport state.
1229
1356
  // `play: false` preserves whatever the listener chose, so a top-up while
1230
1357
  // paused does not start playback, while a queue refilled after the last
@@ -1245,7 +1372,9 @@ export class AiDj {
1245
1372
  },
1246
1373
  };
1247
1374
  this.player.bump();
1248
- this.logger?.info?.(`[music] DJ added ${plan.tracks.length} track(s) via ${plan.source}`);
1375
+ this.logger?.info?.(
1376
+ `[music] DJ added ${plan.tracks.length} track(s) via ${plan.source}${replaced ? `, replacing ${replaced} stale` : ''}`,
1377
+ );
1249
1378
  return plan;
1250
1379
  } catch (error) {
1251
1380
  this.player.dj = { ...this.player.dj, busy: false, error: error.message };
@@ -1263,12 +1392,14 @@ export class AiDj {
1263
1392
  * @returns {Promise<Plan>}
1264
1393
  */
1265
1394
  async start({ prompt, count = 8 } = {}) {
1266
- this.store.updateSettings({ djEnabled: true, ...(prompt === undefined ? {} : { djPrompt: prompt }) });
1395
+ if (prompt !== undefined) this.setPrompt(prompt);
1396
+ this.store.updateSettings({ djEnabled: true });
1267
1397
  this.player.dj.enabled = true;
1268
1398
  // The batch replaces the queue, so nothing precedes its first track.
1269
1399
  const plan = await this.plan({ prompt: prompt ?? this.store.settings.djPrompt ?? '', count, follows: null });
1270
1400
  if (plan.tracks.length > 0) {
1271
1401
  this.player.setQueue(plan.tracks, { startIndex: 0, play: true, source: plan.source, queuedBy: 'dj' });
1402
+ this.stale.clear();
1272
1403
  this.player.dj.lastPlanAt = Date.now();
1273
1404
  this.player.dj.lastPlan = {
1274
1405
  source: plan.source,
@@ -1289,7 +1420,8 @@ export class AiDj {
1289
1420
  /** Turn continuous mode on or off without touching the queue. */
1290
1421
  setEnabled(enabled, { prompt } = {}) {
1291
1422
  const next = Boolean(enabled);
1292
- this.store.updateSettings({ djEnabled: next, ...(prompt === undefined ? {} : { djPrompt: prompt }) });
1423
+ if (prompt !== undefined) this.setPrompt(prompt);
1424
+ this.store.updateSettings({ djEnabled: next });
1293
1425
  this.player.dj.enabled = next;
1294
1426
  this.player.bump();
1295
1427
  return next;
package/lib/index.js CHANGED
@@ -128,6 +128,7 @@ export function apply(ctx, config = {}) {
128
128
  const player = new Player({ logger });
129
129
  // Restore the persisted DJ preference so continuous mode survives a restart.
130
130
  player.dj.enabled = Boolean(store.settings.djEnabled);
131
+ player.restore(store.savedQueue);
131
132
 
132
133
  const qr = new QrLogin({ api, store, logger });
133
134
 
@@ -229,13 +230,23 @@ export function apply(ctx, config = {}) {
229
230
  // The one place a play is recorded: whenever the current track changes, by
230
231
  // whatever path. Recording it again where the queue is set counted every
231
232
  // played track twice, and an appended one as a play of the current track.
232
- let lastRecorded = null;
233
+ // A restored current track was recorded by the run that played it.
234
+ let lastRecorded = player.current()?.id ?? null;
233
235
  player.subscribe(() => {
234
236
  const current = player.current();
235
237
  if (!current || current.id === lastRecorded) return;
236
238
  lastRecorded = current.id;
237
239
  store.recordPlay(current, { tentative: current.queuedBy === 'dj' });
238
240
  });
241
+
242
+ // Saved only when the queue or cursor moves, not on every position report.
243
+ let savedQueueKey = null;
244
+ player.subscribe(() => {
245
+ const key = `${player.index}:${player.queue.map((track) => track.id).join(',')}`;
246
+ if (key === savedQueueKey) return;
247
+ savedQueueKey = key;
248
+ store.saveQueue(player.queue, player.index);
249
+ });
239
250
  player.onHeard = (track) => store.confirmPlay(track.id);
240
251
 
241
252
  // Plays reach the account's listening history the way the web player's do.
package/lib/netease.js CHANGED
@@ -219,6 +219,55 @@ function normalizeTracks(list) {
219
219
  return (list ?? []).map(normalizeTrack).filter(Boolean);
220
220
  }
221
221
 
222
+ /** Encyclopedia prose without its citation marks (`[38]`) or ragged blank lines. */
223
+ export function cleanText(text) {
224
+ return String(text ?? '')
225
+ .replace(/\s*\[\d+(?:-\d+)?\]/g, '')
226
+ .replace(/\n{3,}/g, '\n\n')
227
+ .trim();
228
+ }
229
+
230
+ /**
231
+ * The song facts in a music-wiki ("音乐百科") answer. The wiki is a page of UI
232
+ * blocks; the facts are the creatives of its basic block, keyed by
233
+ * `creativeType`, with their values in resource titles or text links.
234
+ */
235
+ export function parseSongWiki(data) {
236
+ const facts = { genres: [], tags: [], language: '', bpm: null, awards: [], featuredIn: [], review: null };
237
+ const basic = (data?.data?.blocks ?? []).find((block) => block?.code === 'SONG_PLAY_ABOUT_SONG_BASIC');
238
+ for (const creative of basic?.creatives ?? []) {
239
+ const titles = (creative.resources ?? []).map((resource) => resource?.uiElement?.mainTitle?.title).filter(Boolean);
240
+ const text = creative.uiElement?.textLinks?.[0]?.text ?? '';
241
+ switch (creative.creativeType) {
242
+ case 'songTag':
243
+ facts.genres = titles;
244
+ break;
245
+ case 'songBizTag':
246
+ facts.tags = titles;
247
+ break;
248
+ case 'language':
249
+ facts.language = text;
250
+ break;
251
+ case 'bpm':
252
+ facts.bpm = Number(text) || null;
253
+ break;
254
+ case 'songAward':
255
+ facts.awards = titles;
256
+ break;
257
+ case 'entertainment':
258
+ facts.featuredIn = titles;
259
+ break;
260
+ case 'songComment': {
261
+ const resource = creative.resources?.[0]?.uiElement;
262
+ const body = cleanText(resource?.descriptions?.[0]?.description);
263
+ if (body) facts.review = { text: body, by: String(resource?.mainTitle?.title ?? '').replace(/^乐评来自\s*/, '') };
264
+ break;
265
+ }
266
+ }
267
+ }
268
+ return facts;
269
+ }
270
+
222
271
  /** `[1,2]` — NetEase wants bracketed ids in query strings. */
223
272
  function idList(ids) {
224
273
  return encodeURIComponent(JSON.stringify([...ids].map(Number)));
@@ -493,6 +542,55 @@ export class Netease {
493
542
  };
494
543
  }
495
544
 
545
+ /**
546
+ * What the panel's details pane says about a song: its album, its music-wiki
547
+ * entry (genre, tags, language, BPM, awards, where it was featured, a review)
548
+ * and an introduction to each of its first three artists.
549
+ *
550
+ * Only the song itself is required; each other part is fetched on its own
551
+ * and left empty when it fails, so one missing wiki entry never costs the
552
+ * album and the artists.
553
+ */
554
+ async songInfo(id) {
555
+ const detail = await this.call('/api/song/detail', { query: { ids: JSON.stringify([Number(id)]) } });
556
+ const song = detail?.songs?.[0];
557
+ if (!song) throw new NeteaseError(`song ${id} not found`, { code: detail?.code, endpoint: 'song/detail' });
558
+ const albumRef = song.al ?? song.album ?? {};
559
+ const artistRefs = (song.ar ?? song.artists ?? []).filter((artist) => artist?.id).slice(0, 3);
560
+
561
+ const [album, wiki, artists] = await Promise.all([
562
+ albumRef.id ? this.call(`/api/v1/album/${albumRef.id}`).then((data) => data?.album ?? null, () => null) : null,
563
+ this.call('/api/song/play/about/block/page', { method: 'POST', body: { songId: Number(id) } }).catch(() => null),
564
+ Promise.all(
565
+ artistRefs.map((artist) =>
566
+ this.call('/api/artist/introduction', { query: { id: artist.id } }).then(
567
+ (data) => ({ id: artist.id, name: artist.name, intro: cleanText(data?.briefDesc) }),
568
+ () => ({ id: artist.id, name: artist.name, intro: '' }),
569
+ ),
570
+ ),
571
+ ),
572
+ ]);
573
+
574
+ return {
575
+ id: Number(id),
576
+ name: song.name ?? '',
577
+ alias: [...(song.alia ?? song.alias ?? []), ...(song.tns ?? song.transNames ?? [])].filter(Boolean),
578
+ publishTime: song.publishTime || null,
579
+ album: {
580
+ id: albumRef.id ?? null,
581
+ name: album?.name ?? albumRef.name ?? '',
582
+ type: album?.type ?? albumRef.type ?? '',
583
+ subType: album?.subType ?? albumRef.subType ?? '',
584
+ company: album?.company || albumRef.company || '',
585
+ publishTime: album?.publishTime || albumRef.publishTime || null,
586
+ size: album?.size ?? albumRef.size ?? 0,
587
+ intro: cleanText(album?.description || album?.briefDesc),
588
+ },
589
+ artists,
590
+ ...parseSongWiki(wiki),
591
+ };
592
+ }
593
+
496
594
  /** Playlist header plus its first `limit` tracks. */
497
595
  async playlistDetail(id, { limit = 500 } = {}) {
498
596
  const data = await this.call('/api/v6/playlist/detail', {