@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/README.md CHANGED
@@ -1,279 +1,75 @@
1
1
  # @doitian/dsh-music
2
2
 
3
- NetEase Cloud Music ([music.163.com](https://music.163.com)) playback and an AI DJ, inside DeepSeek Harness.
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 appears in the DSH sidebar. It opens a player — your queue, synced lyrics, an `<audio>` element that streams through the host, QR sign-in, NetEase likes, and a continuous AI DJ. The same player is also exposed to the agent through seven tools, so it can search, queue, and curate from a conversation.
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.
6
6
 
7
- ```
8
- ┌──────────────────────────────────────────────────────────────────┐
9
- │ 音乐 music.163.com [AI DJ] [mood] [account] │
10
- │ │
11
- │ ♪ 海屿你 — 马也_Crabbit │
12
- │ 上一首 · 播放 · 下一首 · 列表 · 喜欢 · 静音 · 音量 │
13
- │ │
14
- │ 歌词 Lyrics │
15
- │ [00:12.40] ... │
16
- │ 播放队列 Queue (12) │
17
- └──────────────────────────────────────────────────────────────────┘
18
- ```
7
+ Developing the plugin, or curious how it works? See [docs/DESIGN.md](https://github.com/doitian/dsh-music/blob/main/docs/DESIGN.md).
19
8
 
20
9
  ## Install
21
10
 
22
- The package is self-contained — **no dependencies, no build step, no peer
23
- packages** — so it installs either from npm or straight from a checkout.
24
-
25
- ### From npm
26
-
27
- The package is published as **`@doitian/dsh-music`**. In the Desktop app, install
28
- it from the GUI, because the `dsh plugin` CLI refuses this profile
29
- (`profile "desktop" is managed exclusively by the Electron application`):
11
+ In the desktop app: **Plugins** → **Add plugin** → `@doitian/dsh-music`, then restart the app. **Music** appears in the sidebar.
30
12
 
31
- **Plugins** page → **Add plugin** → `@doitian/dsh-music`
32
-
33
- For any other profile, from a shell:
13
+ For a profile other than `desktop`, install from a terminal instead:
34
14
 
35
15
  ```powershell
36
16
  dsh plugin --profile <name> add @doitian/dsh-music
37
17
  ```
38
18
 
39
- ### From a checkout
40
-
41
- Point the profile at a working tree instead — this is what developing the plugin
42
- looks like. Add it to the profile's `package.json` directly:
43
-
44
- ```json
45
- {
46
- "dependencies": {
47
- "@doitian/dsh-music": "link:C:/path/to/dsh-music"
48
- },
49
- "dsh": {
50
- "profile": {
51
- "bundles": [
52
- "@deepseek-ai/dsh-base",
53
- "@deepseek-ai/dsh-web-app",
54
- "@doitian/dsh-music"
55
- ]
56
- }
57
- }
58
- }
59
- ```
60
-
61
- A `link:` dependency keeps the profile pointing at the working tree, so edits
62
- need no reinstall. Note that this is what makes a plugin *remount* re-read the
63
- served page while the module stays cached — see
64
- [Reloading a change](#reloading-a-change).
65
-
66
- **Language.** The UI follows the Harness language (Settings → Language): the
67
- sidebar label and error page register a zh/en dictionary with the host's
68
- `locale` service, and the player page follows the shell's `<html lang>` live.
69
- Switching language re-renders both in place — no restart.
19
+ The player follows the Harness language setting (中文 or English).
70
20
 
71
- While a profile is linked, the Desktop app's **Add plugin** flow is the wrong
72
- tool for it: that flow installs the published tarball, which replaces the
73
- `link:` dependency. Re-add the link if it happens.
21
+ ## Sign in
74
22
 
75
- ### Either way
23
+ Optional. Signed out, search, charts, playlists, lyrics and non-VIP playback all work; VIP tracks return no audio.
76
24
 
77
- The bundle's own `cordis.patch.yml` inserts the plugin entry, so no
78
- `cordis.patch.yml` edit is required. Restart the app (or reload the profile) and
79
- **Music** appears in the sidebar.
80
-
81
- ## Sign in (optional)
82
-
83
- Without credentials the plugin works anonymously: search, charts, playlists,
84
- lyrics, and non-VIP playback all function. VIP tracks return no audio URL.
85
-
86
- Sign in from the player (**登录 Sign in** in the header), which renders a QR
87
- code to scan with the NetEase Cloud Music mobile app, or ask the agent to use
88
- `music_login`. The session cookie is stored in `$DSH_HOME/music/session.json`.
89
-
90
- `fee=1` (VIP-only) tracks are gated by NetEase for anonymous sessions; that is
91
- an upstream entitlement rule, not a plugin limit.
25
+ Click **登录 Sign in** in the player and scan the QR code with the NetEase Cloud Music app, or ask the agent to use `music_login`. The cookie is stored in `$DSH_HOME/music/session.json`.
92
26
 
93
27
  ## Agent tools
94
28
 
95
29
  | Tool | Purpose |
96
30
  |---|---|
97
- | `music_search` | Search NetEase for songs; returns ids usable below. |
98
- | `music_play` | Queue and start playback, by ids or by search query. |
99
- | `music_queue` | Show / append / insert / replace / remove / jump / clear the queue. |
100
- | `music_control` | play, pause, toggle, next, previous, seek, volume, mute, mode. |
101
- | `music_dj` | Run or configure the AI DJ, with an optional mood brief. |
102
- | `music_now_playing` | What is playing, what is next, and whether the account is signed in. |
103
- | `music_login` | status / qr / poll / set_cookie / logout. |
31
+ | `music_search` | Search NetEase for songs |
32
+ | `music_play` | Queue and play, by ids or a search query |
33
+ | `music_queue` | Show, append, insert, replace, remove, jump, clear |
34
+ | `music_control` | Play, pause, next, previous, seek, volume, mute, mode |
35
+ | `music_dj` | Run or configure the AI DJ, with an optional mood brief |
36
+ | `music_now_playing` | What is playing and next, and whether you're signed in |
37
+ | `music_login` | Status, QR, poll, set a cookie, log out |
104
38
 
105
- Playback happens in the browser panel, so nothing is audible until the user has
106
- opened the Music page.
39
+ Music plays in the Harness window, so keep it open. Playback continues while you switch to a conversation.
107
40
 
108
- ## Streaming quality
41
+ ## Using the player
109
42
 
110
- The transport row carries a quality picker. Levels, richest first:
43
+ **Quality.** Pick a level in the transport row: `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.
111
44
 
112
- | Level | What it serves |
113
- |---|---|
114
- | `jymaster` / `dolby` / `sky` / `jyeffect` | the object-audio tiers; often answered with the Hi-Res stream, and `sky` is frequently refused outright |
115
- | `hires` | FLAC, ~1677–1785 kbps (51–63 MB per track on a VIP account) |
116
- | `lossless` | FLAC, ~908–1016 kbps (28–36 MB) |
117
- | `exhigh` *(default)* | 320 kbps MP3 (~10 MB) |
118
- | `higher` / `standard` | 192 / 128 kbps MP3 |
119
-
120
- **A refusal walks down the ladder.** Entitlement and availability are per track:
121
- a track with no lossless master, or a level the region does not carry, answers
122
- `code -110` while the same track streams fine one tier lower. The request steps
123
- down until something plays, and the caption reports what was *actually* served —
124
- `▶ FLAC · 1677 kbps`, or `▶ MP3 · 320 kbps (exhigh, 已降级/downgraded)` when the
125
- rich request could not be honoured. It never silently pretends, and it never
126
- leaves you with silence because you asked for more than the track has.
127
-
128
- The choice is saved in `session.json` and beats `config.audioLevel` in the
129
- profile patch, the same precedence the DJ's model route uses. An unknown value in
130
- either place falls back to `exhigh` rather than failing a stream.
131
-
132
- Two implementation details worth knowing:
133
-
134
- - **The level rides in the stream URL** (`/music/stream/<id>?level=lossless`),
135
- and the CDN-URL cache is keyed by level as well as track. The same track at
136
- two qualities is two different files, so reusing one resolution while the
137
- browser range-requests the other would corrupt the byte stream.
138
- - **Switching quality mid-track loads a fresh resource and resumes in place**,
139
- restoring the position from the previous file once metadata arrives, rather
140
- than restarting the song. The resource check runs on every poll, not behind
141
- the transport-revision gate — quality is not a one-shot transport change, and
142
- gating it meant a switch did nothing until something else moved the revision.
143
-
144
- `/music/health` reports both: `audio.preferred` and `audio.last` (what the last
145
- stream actually served, including `downgraded`).
146
-
147
- ## Likes and taste
148
-
149
- A track holds one of three taste levels — **liked**, **unrated**, or
150
- **disliked** — and the player draws whichever it is:
151
-
152
- | Control | Level it sets |
45
+ **Taste.** Each track is liked, unrated or disliked:
46
+
47
+ | Control | Effect |
153
48
  |---|---|
154
- | the **♡ / ♥** in a queue row, or the heart in the transport row | **liked** — the track goes into the account's 我喜欢的音乐 playlist on NetEase. Clicking the filled heart takes the like back. |
155
- | the **✕** in the transport row | **disliked** — local, and fed to the DJ, which stops picking the track. Clicking the filled ✕ clears it. |
156
- | the **✕** on a queue row | **disliked** as well. Taking a track out of the queue is a judgement about the track, not just about the list — without recording it the DJ re-derives the same track from the same similarity and charts within a batch or two. |
157
- | neither | unrated. |
158
-
159
- A like is a **NetEase** like, not a plugin flag, and the two halves of what that
160
- needs are both plain endpoints:
161
-
162
- - `POST /api/song/like` — one of the few *write* endpoints the web API still
163
- serves unencrypted, so no `weapi` client is needed. It takes the direction
164
- rather than toggling: the page always says which level it wants, so a stale
165
- poll cannot turn a click into the wrong one, and disliking a liked track is one
166
- request instead of two racing ones.
167
- - `GET /api/song/like/check` — which of a batch of ids are liked. The answer is
168
- cached per track (5 minutes), so a whole queue's hearts cost one request, and
169
- only tracks with no fresh answer ever cost another.
170
-
171
- Four properties are worth knowing, because they are what makes a heart mean
172
- something:
173
-
174
- - **An unknown track is not an unliked one.** A track nobody has asked about has
175
- no answer, and renders as unrated until NetEase gives one.
176
- - **A refusal is not an answer.** An anonymous session answers `code 301` for
177
- every id, and a delisted track answers `400` with NetEase's own reason
178
- (`下架歌曲无法收藏` for 晴天, for instance). Both leave the heart empty and say
179
- why in the toast; a refused check is retried later instead of being cached as
180
- "not liked", so signing in mid-session fills the hearts without a restart.
181
- - **The account is the record.** `feedback.likes` in `session.json` is a *copy*
182
- of the account's likes, kept for the DJ's taste digest. It is reconciled with
183
- the account at startup — one read of the liked playlist — so a like made on
184
- the phone counts, and a like an earlier build recorded locally (because it had
185
- nowhere to send it) does not linger as a phantom.
186
- - **A dislike is local.** The plain web API has no dislike endpoint, so this is
187
- where the plugin's own taste memory is the only record. Liking and disliking
188
- are the same three levels rather than two flags: one replaces the other, and
189
- disliking a liked track removes it on NetEase as well.
190
- - **Removing a queued track is a dislike, once.** The row's ✕ goes through the
191
- queue endpoint, whose removal *is* the judgement: the row leaves the list and
192
- an unrated track is recorded as disliked in the same request, so the DJ does
193
- not derive it again from the same similarity. The confirm names the removal —
194
- the judgement is the host's side of it. A track that already carries a level
195
- keeps it, because removing is often just queue housekeeping (clearing out what
196
- has already been heard) and rewriting a like into a dislike would be worse
197
- than missing the signal. Removing the track that is playing also advances
198
- playback, which a removal otherwise would not.
49
+ | ♡ (row or transport) | Like on your NetEase account. Click again to unlike. |
50
+ | ✕ (transport) | Dislike: the track leaves the queue, and the next one plays. Local only; the DJ stops picking it. |
51
+ | ✕ (queue row) | Remove the track. An unrated track is also recorded as disliked. |
199
52
 
200
- ## The AI DJ
53
+ **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.
201
54
 
202
- The DJ keeps the queue stocked. When the queue drops below
203
- `djAutoExtendBelow`, it gathers candidates and appends a batch:
204
-
205
- - similar songs for the current and recently played tracks (`simiSong`),
206
- - the daily recommendations and the anonymous new-song feed,
207
- - the official charts,
208
- - keyword search for the mood brief.
209
-
210
- Then one of two tiers chooses:
211
-
212
- - **Model tier** — when `dj.provider` and `dj.model` are configured (or a
213
- single provider is discoverable), the candidate pool plus a taste digest
214
- (recently played, favourite artists, likes, dislikes) goes to
215
- `ctx.llm.stream()`, and the model returns the picks and a one-line vibe. This
216
- is the tier that reasons about a mood.
217
- - **Heuristic tier** — always available: candidates are scored by artist
218
- affinity, novelty against play history, and explicit like/dislike feedback,
219
- then interleaved so consecutive tracks do not share an artist.
220
-
221
- **Every model call carries a session identity.** A leaf call cannot set headers
222
- — `GenerateOptions` has no `headers` field — so `sessionId` is the only identity
223
- a plugin can give a provider, and each adapter maps it onto whatever that
224
- provider calls a per-conversation header: pi-ai emits `x-opencode-session` for
225
- the `opencode-go` route. Without it, a provider that keys on the conversation
226
- sees an anonymous client ignoring its conventions.
227
-
228
- The identity is minted once per install and persisted in `session.json`, so
229
- every plan and every restart stays inside one conversation; `dj.sessionId` pins
230
- it explicitly instead. A request with no identity is refused rather than sent
231
- bare, so the failure is a recorded `dj.modelError` rather than a silent one.
232
-
233
- Two other properties are worth knowing:
234
-
235
- - **The DJ is not an agent, and does not start one.** It is plugin code that
236
- gathers candidates, makes one model call, and stocks the queue. Routing that
237
- call through a DSH agent would buy conversation memory and an audit trail at
238
- the cost of a session lifecycle (rotation, tool masking, disposal).
239
- - **The model tier is stateless.** Each plan sends its own pool and gets its
240
- picks back; there is no accumulated transcript, no context growth and no drift
241
- from a previous mood — which is the property, not a limitation, for this job.
242
-
243
- The model tier is optional and silent on failure; the DJ never blocks playback.
244
- It only ever **stocks the queue** — it never starts or stops playback, so a
245
- top-up while paused stays paused, and one that refills an empty queue after the
246
- last track ended resumes on its own because the desired state was already
247
- "playing".
55
+ ## The AI DJ
248
56
 
249
- ### Choosing the model
57
+ Turn it on in the player 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.
250
58
 
251
- **In the player.** The right column carries a **AI DJ 模型 / DJ model**
252
- panel: a provider picker, a model picker, and three buttons.
59
+ **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.
253
60
 
254
- | Control | What it does |
255
- |---|---|
256
- | **保存 Save** | Applies the pair immediately and persists it in `session.json` |
257
- | **测试 Test** | Runs one throwaway plan (nothing is queued) and reports the route it used, the track it would have picked, and — on failure — exactly why |
258
- | **回退 Revert** | Clears the saved choice so the profile patch applies again |
61
+ **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.
259
62
 
260
- The picker lists every registered provider route and that route's catalogued
261
- models. The catalogue is **advisory**: core resolution accepts unlisted ids, so
262
- **其他… / Other…** reveals a text field for any id the route serves — which is
263
- how you keep using a model the adapter's catalogue does not list.
63
+ **Mood brief.** Type a mood 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.
264
64
 
265
- Selection precedence, highest first:
65
+ **Who chooses:**
266
66
 
267
- 1. **the player's saved choice** (`settings.djProvider` / `settings.djModel`)
268
- 2. **the profile patch** (`config.dj.provider` / `config.dj.model`)
269
- 3. **discovery** — the first route, then its first catalogued model
67
+ - **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.
68
+ - **Heuristic tier:** used when no model is available or a call fails. Candidates are scored by mood match, favourite artists, and your likes, dislikes and skips.
270
69
 
271
- The source is shown next to the heading: *面板 / panel*, *配置 / profile*, or
272
- *自动 / auto*. Saving beats the patch deliberately; otherwise a stale patch pin
273
- would silently override what you just picked. **回退 Revert** is how you hand
274
- control back to the patch.
70
+ ### Choosing the model
275
71
 
276
- **In the profile patch**, as a default for a fresh install:
72
+ By default the DJ uses your session's default model. To use another, pick a provider and model in the player's **AI DJ 模型 / DJ model** panel (**测试 Test** checks it without touching the queue), or set it in your profile's `cordis.patch.yml`:
277
73
 
278
74
  ```yaml
279
75
  - id: music
@@ -284,380 +80,38 @@ control back to the patch.
284
80
  model: deepseek-v4.1-flash
285
81
  ```
286
82
 
287
- Both names must be ones the host actually serves. `provider` is a registered
288
- adapter route — read them from the `llm-pi-ai` entry's `config.providers` (or
289
- ask the agent for `ctx.llm.listProviders()`); `model` is any id that route
290
- accepts.
291
-
292
- **Pin it, or follow the session.** With both fields unset the DJ inherits
293
- `agent-default-model` — the same selection the composer's model picker writes,
294
- so it is the model the agent loop itself runs on — which is why "use my session
295
- model" needs no configuration. Pinning `dj.provider`/`dj.model` curates on
296
- something else instead, and pinning is what makes the two choices independent:
297
-
298
- ```yaml
299
- - id: agent-default-model # the agent loop / session model
300
- config: { provider: opencode-go, model: deepseek-v4.1-flash }
301
- - id: music
302
- config:
303
- dj: # the DJ's own model, when you want a different one
304
- provider: opencode-go
305
- model: minimax-m3
306
- ```
307
-
308
- Three things worth knowing:
309
-
310
- - **`config` is replaced, not merged.** The loader assigns the whole object
311
- (`entry.ts`: `this.options.config = value`), so if you also want, say,
312
- `audioLevel`, keep every option in one block. Schema defaults fill the rest.
313
- - **Discovery is the last resort, and its choice is arbitrary.** Only when
314
- neither a pin nor `agent-default-model` exists does the DJ ask the mounted LLM
315
- service for its routes (`listProviders()`), take the first, then take that
316
- route's first catalogue entry. On this machine `opencode-go`'s catalogue is
317
- `minimax-m3, deepseek-v4-flash, gpt-5.6-luna`, so discovery curates with
318
- **MiniMax-M3** — not a recommendation, just the first row.
319
- - **Partial pins are honoured.** A `provider` alone keeps that route and picks
320
- its first catalogue model; a `model` alone keeps that model on the first
321
- route.
322
-
323
- Confirm it took effect:
324
-
325
- | Where | What to look for |
326
- |---|---|
327
- | `/music/health` | `dj.model` is your pinned pair; `dj.modelSource` is `panel`, `config`, `agent-default` or `discovered`; `dj.resolvedFrom` is what the last plan actually used (`pin`, `agent-default`, `discovered`); `dj.sessionModel` is the deployment's own model; `dj.lastRoute` is the route that curated the last batch; `dj.sessionId` is the identity every call carries; `dj.modelError` is `null` once the tier works |
328
- | Player, DJ status line | **AI DJ** plus the route (heuristic runs read **AI DJ (heuristic)**, and a declined tier prints the reason) |
329
- | **测试 Test** in the player | Answers "does this route work?" in one click, without touching the queue |
330
- | `music_dj` tool result | `AI DJ is on (model via opencode-go/deepseek-v4.1-flash)` |
331
-
332
- **If the tier declines, `dj.modelError` says why** — the tier is non-fatal by
333
- design, so without that field every cause looks the same. It reports
334
- `no LLM service is mounted (ctx.get("llm") returned nothing)` when no adapter
335
- service is present, names a half-configured pin (`opencode-go/?`), or carries
336
- the provider's own failure (a `LlmError` code such as `NO_ADAPTER`,
337
- `MISSING_CREDENTIAL`, `AUTH`, `RATE_LIMIT`). The heuristic tier covers that batch
338
- either way.
339
-
340
- **If a provider says your usage does not follow its conventions**, the first
341
- thing to check is the route's identity, not the request: pi-ai adds
342
- `x-opencode-session` only for its own catalog routes `opencode-go` and
343
- `opencode`. A hand-declared route id that merely points at
344
- `https://opencode.ai/zen/go/v1` gets no wrapper and therefore no header, with
345
- nothing in the logs to say so — keep the catalog route name. For the same
346
- reason, do not set `x-opencode-session` in a profile's `headers`: the adapter
347
- lets a configured value win over the generated one, which would freeze a single
348
- id across every conversation. What remains after that is entitlement rather
349
- than convention — a plan that only permits its own client's traffic cannot be
350
- satisfied by a header, only by delegating transport to that client.
351
-
352
- To see the bytes rather than trust the reasoning, run the bundled probe, point a
353
- route's `baseURL` at it for one plan, and read what actually leaves the process:
354
-
355
- ```powershell
356
- npm run probe:headers # http://127.0.0.1:8787 -> https://opencode.ai
357
- ```
358
-
359
- You should see `x-opencode-session` carrying the DJ's id, and
360
- `user-agent: deepseek-harness/<version> (+…)` — attribution that must never be
361
- replaced by a provider-shaped one. Take the `baseURL` back out afterwards.
362
-
363
- Editing `config` recomposes the running host, but **the plugin module itself is
364
- cached** — restart the harness for the new route to take effect. If the model
365
- tier fails for any reason (no adapter, bad credentials, unparseable reply,
366
- rate limit) the DJ logs a warning and falls back to the heuristic tier for that
367
- batch; it never leaves the queue empty.
368
-
369
- ### Heuristic tier
370
-
371
- Always available, used whenever the model tier is unavailable:
83
+ The player's choice wins over the profile; **回退 Revert** hands control back. If the DJ falls back to heuristics, the health page shows why in `dj.modelError` (see [Troubleshooting](#troubleshooting)).
372
84
 
373
85
  ## Configuration
374
86
 
375
- Defaults live in the package, so the profile patch stays empty. To override,
376
- add `config` to the inserted entry:
377
-
378
- ```yaml
379
- - insert:
380
- - id: music
381
- name: '@doitian/dsh-music'
382
- config:
383
- audioLevel: exhigh # exhigh (320 kbps) | standard | higher | lossless
384
- dataDir: D:\dsh-data\music # default $DSH_HOME/music
385
- requestTimeoutMs: 15000
386
- dj:
387
- provider: opencode-go # enables the model tier
388
- model: deepseek-v4.1-flash
389
- sessionId: music-dj-mine # optional: pin the provider-visible identity
390
- ```
87
+ All fields are optional, under the plugin entry's `config` in your profile's `cordis.patch.yml`. The loader replaces `config` as a whole, so keep every option in one block.
391
88
 
392
89
  | Field | Default | Meaning |
393
90
  |---|---|---|
394
- | `apiPrefix` | `music` | Route prefix. **Changing this also requires editing `BASE` in `lib/client.js`.** |
395
- | `dataDir` | `$DSH_HOME/music` | Where `session.json` (cookie, history, feedback, settings) lives. |
396
- | `audioLevel` | `exhigh` | Initial streaming quality, until the player's picker records a choice. One of the levels above; an unknown value falls back to `exhigh`. |
397
- | `requestTimeoutMs` | `15000` | Per-request deadline for NetEase calls. |
398
- | `dj.provider` / `dj.model` | unset | Model route for the DJ's model tier — see [Choosing the model](#choosing-the-model). Unset, the tier follows `agent-default-model` and only then falls back to discovery; any failure falls back to heuristics. |
399
- | `dj.sessionId` | minted, persisted | The identity every model call carries. Adapters map it onto the provider's per-conversation header. Pin it to control what a provider sees, or leave it unset and let the DJ mint one per install. |
400
-
401
- Player preferences (quality, DJ on/off, mood brief, batch size, extend
402
- threshold) are persisted in `session.json` and edited from the panel.
403
-
404
- ## How it works
405
-
406
- ```
407
- browser (DSH web GUI, http://127.0.0.1:<port>)
408
- ├─ client plugin — mounted for the plugin's whole lifetime
409
- │ └─ audio engine ── <audio src="/music/stream/<id>"> ──▶ host audio proxy
410
- │ (keeps playing while you are in a session)
411
- └─ sidebar "音乐 Music" ── iframe ──▶ /music/panel (player UI, no audio)
412
- │ fetch (same origin)
413
- ▼
414
- /music/api/* (JSON)
415
- /music/stream/<id> (audio bytes)
416
- │
417
- host plugin ───────┘
418
- ├─ lib/netease.js NetEase web API (no weapi encryption)
419
- ├─ lib/session.js cookie store + QR login state machine
420
- ├─ lib/state.js queue, cursor, transport revisions
421
- ├─ lib/dj.js candidate pool + model/heuristic tiers
422
- ├─ lib/likes.js the account's like state, cached
423
- └─ lib/router.js JSON API, HTML, Range-capable audio proxy
424
- ```
425
-
426
- Four design notes:
427
-
428
- - **Audio is proxied, not redirected.** CDN URLs expire after 20 minutes and
429
- need the session cookie at *resolution* time, so the host resolves and streams
430
- the bytes (cache 15 min, `Range` forwarded upstream so seeking works). It also
431
- keeps playback same-origin, avoiding mixed-content and CORS entirely.
432
- - **Playback lives in the shell document, not in the page.** The layout renders
433
- only the **active** `main` slot entry —
434
- `renderSlot('main', {}, { entryKey: activePanelId ?? 'conversation' })` — so
435
- opening a Session unmounts the Music page and discards its document. An
436
- `<audio>` owned by that page would stop the music, which is exactly what
437
- happened before contract 2. The engine is created on the client plugin's own
438
- lifetime, survives every panel switch, and the page is a remote control:
439
- `window.__dshMusicEngine.sync()` applies a command without waiting for the
440
- next poll. A `panelContract` value on `/music/health` keeps a half-updated
441
- browser (new bundle, old host) from playing every track twice.
442
- - **The host owns the desired state; the engine owns the audio element.** They
443
- reconcile through `rev` / `transportRev` counters, so agent tools, the page,
444
- and the DJ all drive one state machine instead of three.
445
- - **The client half is hand-written.** `lib/client.js` is a plain
446
- `window.__ModuleLoader__` bundle using only baseline `react`, so there is no
447
- tsdown/Vite step. It registers the sidebar row (`sidebar.panellist`, a list
448
- slot) and the page (`main`, the layout's keyed slot) with the same id, and
449
- `ctx.slots.inject` waits for those slots to be declared.
450
-
451
- ## Security notes
452
-
453
- - The `/music` route prefix is registered on the bare HTTP server, which owns no
454
- authentication of its own. Anyone who can reach the port can browse the
455
- library, stream audio, and **change the account's likes** — `POST
456
- /music/api/taste` is the panel's own control, so it is a real write to the
457
- NetEase account. The route is loopback-only in the shipped composition. It
458
- exposes no credentials — only search results, the queue, the like state, and
459
- audio bytes.
460
- - The NetEase cookie lives in `$DSH_HOME/music/session.json` in plain text, the
461
- same posture as the rest of the profile's session data. `music_login` with
462
- `set_cookie` accepts a pasted `MUSIC_U`, and the value is never returned by any
463
- endpoint.
464
-
465
- ### Diagnostics
466
-
467
- `GET /music/health` is unauthenticated and answers with the facts worth having
468
- when something looks wrong:
469
-
470
- ```json
471
- {
472
- "ok": true,
473
- "prefix": "/music",
474
- "panelContract": 2,
475
- "authenticated": true,
476
- "account": { "nickname": "…", "vip": true },
477
- "playing": false,
478
- "queued": 0,
479
- "tools": ["music_search", "music_play", "music_queue", "music_control",
480
- "music_dj", "music_now_playing", "music_login"],
481
- "dj": { "enabled": false, "model": null, "lastRoute": null,
482
- "modelError": null, "lastPlanAt": null, "error": null },
483
- "likes": { "cached": 12, "pending": 0, "error": null },
484
- "dataDir": "C:\\Users\\…\\.dsh\\music",
485
- "session": { "authenticated": true, "nickname": "…", "vip": true },
486
- "uptimeMs": 123456
487
- }
488
- ```
489
-
490
- `tools` is the point: the HTTP route is registered before the tools, so a tool
491
- that failed to register would otherwise leave a route that answers normally.
492
- Seeing all seven names is what proves startup completed. `panelContract` is the
493
- page/engine boundary the browser half checks before it starts playback. `likes`
494
- is the cache behind the hearts: `cached` is how many answers it holds, and
495
- `error` names why a check produced none — an anonymous session never asks, so
496
- both stay empty.
497
-
498
- ### If the browser blocks autoplay
499
-
500
- Chromium refuses to start audio until the page has been **interacted with**, and
501
- the plugin's desired state can say "playing" long before that — the agent
502
- queued something, or the DJ refilled the queue while the page was loading. The
503
- player then shows:
504
-
505
- > 浏览器需要你先与页面交互一次才会播放声音 / Chromium needs one interaction with this window before it will play audio
506
-
507
- **Click the button, or anywhere in the window.** That one gesture grants sticky
508
- activation for the rest of the page's life, after which agent- and DJ-initiated
509
- playback works without asking again. Typing in the chat counts too.
91
+ | `audioLevel` | `exhigh` | Starting quality, until you pick one in the player |
92
+ | `dataDir` | `$DSH_HOME/music` | Where `session.json` lives |
93
+ | `requestTimeoutMs` | `15000` | NetEase request deadline |
94
+ | `dj.provider` / `dj.model` | session model | The DJ's model, as above |
510
95
 
511
- The engine retries on every 500 ms poll, so recovery is automatic — and it must
512
- be, because a refused `play()` does not change the transport revision. Gating
513
- the retry behind that revision (an earlier bug) left the music stopped for good,
514
- with the hint showing and pressing it doing nothing.
96
+ Batch size (`djBatchSize`, 5) and refill threshold (`djAutoExtendBelow`, 3) have no control in the player. Edit them in `session.json` while the harness is stopped.
515
97
 
516
- ### Who owns the `<audio>` element
98
+ ## Troubleshooting
517
99
 
518
- Normally the client plugin's **engine in the shell document**, so playback
519
- survives opening a session (the layout renders only the *active* panel). But the
520
- player page is re-read from disk on every plugin mount, while the browser bundle
521
- it pairs with is pinned to its own revision — so the two can disagree. When they
522
- do, `GET /music/health` will not advertise the matching `panelContract`, the
523
- engine declares itself inert, and **the page owns the audio element itself**.
524
- That is the older behaviour: it plays normally, it just stops when you open a
525
- session. Exactly one transport ever owns playback; the unusable one is stood
526
- down first. A restart brings both halves back into agreement.
100
+ - **No sound:** Chromium blocks audio until you interact with the page. Click anywhere in the window once.
101
+ - **The DJ isn't using the model:** check `dj.modelError` on the health page.
102
+ - **A provider says your usage breaks its conventions:** use the provider's catalog route name (for example `opencode-go`), and don't set `x-opencode-session` in the profile's `headers`.
103
+ - **Changed a setting in the profile and nothing happened:** restart the app.
527
104
 
528
- ## Development
105
+ **The health page** is `/music/health` on the Harness's own address — for example `http://127.0.0.1:<port>/music/health`, using the port the Harness window is served on. It reports the account, the queue, the DJ's model state, and which tools registered.
529
106
 
530
- ```powershell
531
- npm run check # node --check on every module
532
- npm test # 114 deterministic tests: pure, like state, DJ, browser half
533
- npm run test:live # 33 integration tests against the live NetEase API
534
- npm run test:all # both
535
- ```
536
-
537
- The split matters for CI. `npm test` never touches the network, so it is what
538
- runs on every push and gates a release. `npm run test:live` drives the real API,
539
- and **GitHub's runners cannot reach it** — from a US runner
540
- `/api/search/get/web` answers in ~350 ms with an empty result set, so its first
541
- assertion fails on a network condition rather than a regression. It therefore
542
- lives in `.github/workflows/live.yml` on manual dispatch only, and the
543
- authoritative run is local, before a release. `MUSIC_OFFLINE=1` skips the
544
- network cases inside it.
545
-
546
- Or run one file directly:
547
-
548
- ```powershell
549
- node test/netease.test.mjs # 32 pure: normalisation, quality ladder, likes, cookies, taste, player state
550
- node test/likes.test.mjs # 12 like-state cache: what counts as an answer, refusals, batching, writes
551
- node test/dj.test.mjs # 37 AI DJ: model call identity, route resolution, failure reporting, queue invariants
552
- node test/client.test.mjs # 38 browser half: the engine against a fake DOM, and the page it pairs with
553
- node test/host.test.mjs # 33 integration: routes, streaming, curation, quality, taste
554
- ```
107
+ ## Security
555
108
 
556
- The DJ tests drive `ctx.llm.stream()` with a stub that emits the documented
557
- chunks, and stub `ctx.agentDefaultModel` for route inheritance. So the
558
- pinned-route happy path, both chunk spellings (`type`/`kind`), index filtering,
559
- prose-wrapped JSON, the session identity every call must carry, inheritance from
560
- the session model, discovery, and every fallback are covered without a provider.
561
-
562
- The integration tests mount the plugin against stand-in `tools`/`webServer`
563
- services and drive the captured route over a real `node:http` server, so they
564
- exercise the same path the browser takes — including a real `Range` request
565
- against the NetEase CDN and a real AI DJ plan. Because they talk to a live
566
- third-party API, an occasional failure there can be the network rather than the
567
- code; re-run before investigating.
568
-
569
- The browser-half tests execute `lib/client.js` for real against a minimal fake
570
- DOM (fake `window`, `document`, `fetch`), which is how the central property is
571
- proven: **the engine creates and drives the `<audio>` element with no React
572
- component ever rendered**, so playback cannot depend on the Music page being
573
- mounted. They also cover the seek handshake, failure reporting, disposal, and
574
- the contract handshake.
575
-
576
- The same fake DOM boots `lib/panel.html` itself, with an engine that reports
577
- `playback: true` — the shell document owns the audio element. That is the case
578
- where the page must fetch everything it renders on its own: lyrics used to be
579
- requested only from the local fallback transport's `applySource`, so with the
580
- engine playing the pane stayed empty for every track. Three tests hold the
581
- line: the rendered track is asked for, one fetch per track rather than one per
582
- poll, and a track change replaces the pane. Two more cover the pane's shape: it
583
- is capped to a few lines, collapses to its header on demand, and remembers that
584
- choice across loads — while still fetching the lines, so expanding is instant.
585
-
586
- `npm test` runs the four deterministic files in sequence (`npm run test:all`
587
- adds the live one), deliberately **not** `node --test <dir>`: the directory form forks one child process per file, which
588
- is blocked in sandboxed environments.
589
-
590
- ### Reloading a change
591
-
592
- - **Profile configuration** changes (bundle selection, `cordis.patch.yml`)
593
- recompose the running host: the loader re-reads the layers and mounts or
594
- unmounts the affected entry. Adding the bundle to `dsh.profile.bundles` and
595
- touching `cordis.patch.yml` was enough to load the plugin into an already
596
- running host.
597
- - **Plugin source** changes need a **process restart**. A disable/enable
598
- round-trip does remount the entry (the route genuinely goes away and comes
599
- back), but Node caches the ESM module, so the remounted entry runs the *old*
600
- code. Treat `lib/*.js` and `lib/panel.html` edits as restart-required.
601
- - **Agent tools** register on the host, so they appear in **new** agent
602
- sessions. A session that was already running keeps the tool list it started
603
- with.
604
-
605
- `lib/vendor/qrcode.js` is the MIT-licensed
606
- [qrcode-generator](https://github.com/kazuhikoarase/qrcode-generator) by
607
- Kazuhiko Arase, vendored so QR sign-in needs no network call or build step.
608
-
609
- ### Releasing
610
-
611
- Releases are cut from GitHub and published by the `publish` workflow with **npm
612
- trusted publishing (OIDC)**. There is no `NPM_TOKEN` secret and no
613
- `NODE_AUTH_TOKEN` in the repository, and adding one would disable the OIDC
614
- exchange and break publishing.
615
-
616
- 1. Bump `version` in `package.json`, commit, and push.
617
- 2. Create a GitHub release whose tag is `v<version>` — `v0.1.2` for `0.1.2` —
618
- pointing at that commit.
619
-
620
- The workflow runs `npm run check`, the deterministic suites, asserts the tag
621
- matches `package.json`, and publishes. A tag push alone publishes nothing: the
622
- trigger is `release: published`.
623
-
624
- Two timings look like failures and are not:
625
-
626
- - **A green job is not yet a live version.** The registry records a
627
- `0.0.0-stage` placeholder first and reports the package as *being processed*;
628
- the version becomes installable roughly a minute later. Inside that window the
629
- packument still answers `404`, and publishing the same version from a second
630
- place is refused with `409 Cannot publish over previously staged version`.
631
- - **Registry reads can lag the publish**, so an `npm view` run immediately
632
- afterwards may still say `404`. Wait a minute, or read it from CI instead.
633
-
634
- Versions published this way carry a SLSA provenance attestation naming the
635
- workflow, tag, and commit — `npm view @doitian/dsh-music@<version> dist.attestations`.
636
- `0.1.0` predates the trusted publisher: it was published by hand and has none.
109
+ - The `/music` routes have no authentication of their own; they are served on loopback only. Anyone who can reach the port can browse, stream, and change the account's likes.
110
+ - The NetEase cookie is stored in plain text in `session.json` and is never returned by any endpoint.
637
111
 
638
112
  ## Known limitations
639
113
 
640
- - **Anonymous sessions cannot play VIP tracks**; NetEase returns `url: null`.
641
- - **Some tracks are gated by *purchase*, not VIP**, and stay unplayable even for
642
- a signed-in VIP account — 周杰伦's 晴天 (`id 186016`) is the canonical example,
643
- because it belongs to a digital album. The plugin surfaces NetEase's own
644
- refusal (`403` plus a reason) rather than retrying.
645
- - **No `weapi`/`eapi` encryption**, so scrobbling and playlist writes are not
646
- implemented. Liking a track needs none of it — see
647
- [Likes and taste](#likes-and-taste) — but a *dislike* stays local, because
648
- there is no plain endpoint for one.
649
- - **`apiPrefix` must stay `music`** unless `BASE` in `lib/client.js` is changed
650
- to match.
651
- - **The DJ's model tier is covered against stub contracts, not a live
652
- provider** — request building, the session identity, route resolution, both
653
- chunk spellings, index filtering and every fallback are tested, but a real
654
- end-to-end model call has not been observed here. The heuristic tier is what
655
- the live runs exercised.
656
- - **The identity only becomes a header on the catalog routes that define one.**
657
- pi-ai adds `x-opencode-session` for its own `opencode-go`/`opencode` routes. A
658
- hand-declared route id pointing at the same endpoint gets no wrapper, so the
659
- header is simply absent — keep the catalog route name, and never pin
660
- `x-opencode-session` in a profile's `headers` (a configured value wins over
661
- the generated one and freezes a single id for every conversation).
662
- - **Chromium autoplay policy** may block playback the agent starts before the
663
- user has interacted with the page; the panel then shows a *click to play* hint.
114
+ - VIP tracks don't play while signed out, and some tracks are sold per album, so they don't play even with VIP (for example 晴天, `id 186016`).
115
+ - Without NetEase's encrypted API there is no scrobbling, no playlist editing and no heartbeat mode (心动模式), and a dislike stays local.
116
+ - The DJ's model mode hasn't yet been tested end to end with a real model. If it misbehaves, `dj.modelError` says why, and the DJ keeps working without it.
117
+ - Only your newest 500 likes are offered back as candidates.