@doitian/dsh-music 0.0.0-stage → 0.1.1
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/LICENSE +28 -0
- package/README.md +482 -2
- package/cordis.patch.yml +22 -0
- package/icon.svg +8 -0
- package/lib/client.js +466 -0
- package/lib/dj.js +543 -0
- package/lib/index.js +618 -0
- package/lib/netease.js +609 -0
- package/lib/panel.html +1105 -0
- package/lib/router.js +569 -0
- package/lib/session.js +346 -0
- package/lib/state.js +389 -0
- package/lib/vendor/qrcode.js +2297 -0
- package/package.json +67 -4
package/lib/dj.js
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The AI DJ: keeps the queue stocked with tracks that fit what is being
|
|
3
|
+
* listened to.
|
|
4
|
+
*
|
|
5
|
+
* Two tiers, tried in order:
|
|
6
|
+
*
|
|
7
|
+
* 1. **Model tier** — when a model is configured (or discoverable), the
|
|
8
|
+
* candidate pool plus a taste digest go to `ctx.llm.stream()`, and the
|
|
9
|
+
* model returns the picks and a one-line vibe. This is what makes the DJ
|
|
10
|
+
* reason about a mood brief rather than only follow similarity edges.
|
|
11
|
+
* 2. **Heuristic tier** — always available, no model required: NetEase's own
|
|
12
|
+
* signals (similar songs, daily recommendations, anonymous new-song feed,
|
|
13
|
+
* charts, keyword search) scored by artist affinity, novelty, and the
|
|
14
|
+
* listener's like/dislike/skip feedback, then interleaved so consecutive
|
|
15
|
+
* tracks do not share an artist.
|
|
16
|
+
*
|
|
17
|
+
* The DJ never blocks playback: every entry point resolves to a plan or to
|
|
18
|
+
* `null`, and the caller keeps whatever is already queued.
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-music/dj
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Render a model-tier failure so its stable code survives.
|
|
25
|
+
*
|
|
26
|
+
* `dsh-llm` documents that consumers must route on the failure `code`, never on
|
|
27
|
+
* message text — and a provider is free to send a message as useless as
|
|
28
|
+
* `"error"`. Reporting only `name: message` collapses every distinct failure,
|
|
29
|
+
* including a whole provider being down, into one unactionable line.
|
|
30
|
+
*/
|
|
31
|
+
function describeFailure(error) {
|
|
32
|
+
const code = error?.code === undefined ? '' : String(error.code);
|
|
33
|
+
const message = error?.message === undefined ? String(error) : String(error.message);
|
|
34
|
+
const head = code && !message.startsWith(code) ? `${code}: ${message}` : message || code;
|
|
35
|
+
const details = error?.failure?.details;
|
|
36
|
+
if (details === undefined) return head;
|
|
37
|
+
try {
|
|
38
|
+
return `${head} | ${JSON.stringify(details).slice(0, 200)}`;
|
|
39
|
+
} catch {
|
|
40
|
+
return head;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Candidate pool handed to the model; keeps the prompt inside a small budget. */
|
|
45
|
+
const MAX_POOL = 45;
|
|
46
|
+
|
|
47
|
+
/** Only the first `MAX_SEEDS` history entries seed similarity expansion. */
|
|
48
|
+
const MAX_SEEDS = 4;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @typedef {object} Plan
|
|
52
|
+
* @property {object[]} tracks chosen tracks, in play order.
|
|
53
|
+
* @property {'model'|'heuristic'} source which tier produced the picks.
|
|
54
|
+
* @property {string} [vibe] one-line description of the set.
|
|
55
|
+
* @property {string} [note] why the heuristic tier ran, when it did.
|
|
56
|
+
* @property {number} poolSize how many candidates were considered.
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
export class AiDj {
|
|
60
|
+
/**
|
|
61
|
+
* @param {object} options
|
|
62
|
+
* @param {import('./netease.js').Netease} options.api
|
|
63
|
+
* @param {import('./state.js').Player} options.player
|
|
64
|
+
* @param {import('./session.js').SessionStore} options.store
|
|
65
|
+
* @param {() => object | undefined} [options.resolveLlm] returns the LLM service when mounted.
|
|
66
|
+
* @param {{warn: Function, info: Function, debug: Function}} [options.logger]
|
|
67
|
+
* @param {object} [options.model] `{ provider, model }` enabling the model tier.
|
|
68
|
+
*/
|
|
69
|
+
constructor({ api, player, store, resolveLlm, logger, model = {} } = {}) {
|
|
70
|
+
this.api = api;
|
|
71
|
+
this.player = player;
|
|
72
|
+
this.store = store;
|
|
73
|
+
this.resolveLlm = resolveLlm;
|
|
74
|
+
this.logger = logger;
|
|
75
|
+
this.model = { provider: model.provider ?? null, model: model.model ?? null };
|
|
76
|
+
/**
|
|
77
|
+
* Why the model tier last declined, or `null` when it last succeeded.
|
|
78
|
+
*
|
|
79
|
+
* The tier is deliberately non-fatal, which makes a silent fallback the
|
|
80
|
+
* default failure mode: a bad route, a missing credential and a
|
|
81
|
+
* misconfigured model all look identical from the outside. Recording the
|
|
82
|
+
* reason here is what makes `/music/health` able to explain it.
|
|
83
|
+
*/
|
|
84
|
+
this.modelError = null;
|
|
85
|
+
/** Guards against overlapping plans when a track ends mid-plan. */
|
|
86
|
+
this.busy = false;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Record a model-tier decline and carry on with the heuristic tier. */
|
|
90
|
+
#decline(reason) {
|
|
91
|
+
this.modelError = reason;
|
|
92
|
+
this.player.dj.modelError = reason;
|
|
93
|
+
this.logger?.warn?.(`[music] DJ model tier unavailable: ${reason}`);
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Update the configured model target at runtime. */
|
|
98
|
+
setModel({ provider, model } = {}) {
|
|
99
|
+
if (provider !== undefined) this.model.provider = provider || null;
|
|
100
|
+
if (model !== undefined) this.model.model = model || null;
|
|
101
|
+
// A changed route invalidates the previous verdict, so the next plan is
|
|
102
|
+
// judged on its own result rather than the old failure.
|
|
103
|
+
this.modelError = null;
|
|
104
|
+
this.player.dj.modelError = null;
|
|
105
|
+
return this.model;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Whether a model tier is configured. */
|
|
109
|
+
get modelConfigured() {
|
|
110
|
+
return Boolean(this.model.provider && this.model.model);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Enumerate the provider routes and catalogued models the DJ could use, for
|
|
115
|
+
* the player's picker.
|
|
116
|
+
*
|
|
117
|
+
* The catalogue is advisory only: core resolution accepts unlisted ids, so
|
|
118
|
+
* the picker also allows a typed model. Without a mounted LLM service there
|
|
119
|
+
* is nothing to offer, and `error` says so rather than returning a bare
|
|
120
|
+
* empty list.
|
|
121
|
+
*
|
|
122
|
+
* @returns {Promise<{routes: {provider: string, models: {id: string, name: string}[], error?: string}[], error: string | null}>}
|
|
123
|
+
*/
|
|
124
|
+
async listRoutes() {
|
|
125
|
+
const llm = this.resolveLlm?.();
|
|
126
|
+
if (!llm?.stream) {
|
|
127
|
+
return { routes: [], error: 'no LLM service is mounted (ctx.get("llm") returned nothing)' };
|
|
128
|
+
}
|
|
129
|
+
let providers = [];
|
|
130
|
+
try {
|
|
131
|
+
providers = (llm.listProviders?.() ?? [])
|
|
132
|
+
.map((entry) => entry?.id ?? entry?.provider)
|
|
133
|
+
.filter(Boolean);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
return { routes: [], error: `could not list providers: ${error.message}` };
|
|
136
|
+
}
|
|
137
|
+
const routes = [];
|
|
138
|
+
for (const provider of providers) {
|
|
139
|
+
try {
|
|
140
|
+
const models = (await llm.listModels?.(provider)) ?? [];
|
|
141
|
+
routes.push({
|
|
142
|
+
provider,
|
|
143
|
+
models: models
|
|
144
|
+
.map((model) => ({
|
|
145
|
+
id: model?.id ?? model?.model ?? null,
|
|
146
|
+
name: model?.name ?? model?.id ?? model?.model ?? null,
|
|
147
|
+
}))
|
|
148
|
+
.filter((model) => model.id),
|
|
149
|
+
});
|
|
150
|
+
} catch (error) {
|
|
151
|
+
routes.push({ provider, models: [], error: `could not list models: ${error.message}` });
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return { routes, error: routes.length === 0 ? 'no provider route is registered' : null };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ------------------------------------------------------------- candidates
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Gather a de-duplicated candidate pool from every available signal.
|
|
161
|
+
*
|
|
162
|
+
* Every source is independent and failure-tolerant: a source that throws or
|
|
163
|
+
* needs a session the listener lacks contributes nothing.
|
|
164
|
+
*/
|
|
165
|
+
async #candidates({ prompt = '', count = 30 } = {}) {
|
|
166
|
+
const digest = this.store.tasteDigest();
|
|
167
|
+
const excluded = new Set([...digest.dislikedIds, ...digest.recentIds]);
|
|
168
|
+
const pool = [];
|
|
169
|
+
const seen = new Set();
|
|
170
|
+
const add = (tracks, origin) => {
|
|
171
|
+
for (const track of tracks ?? []) {
|
|
172
|
+
if (!track?.id || seen.has(track.id) || excluded.has(track.id)) continue;
|
|
173
|
+
seen.add(track.id);
|
|
174
|
+
pool.push({ ...track, origin });
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const current = this.player.current();
|
|
179
|
+
const seeds = [current?.id, ...this.store.recentIds(MAX_SEEDS)].filter(Boolean).slice(0, MAX_SEEDS);
|
|
180
|
+
|
|
181
|
+
const tasks = [];
|
|
182
|
+
// Similarity expansion from what is playing and what was played recently.
|
|
183
|
+
for (const seed of seeds) {
|
|
184
|
+
tasks.push(
|
|
185
|
+
this.api.simiSongs(seed, { limit: 12 }).then((tracks) => add(tracks, 'similar')).catch(() => {}),
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
// A mood brief is a search term; the raw text searches well enough.
|
|
189
|
+
if (prompt.trim()) {
|
|
190
|
+
tasks.push(
|
|
191
|
+
this.api.searchSongs(prompt.trim(), { limit: 15 }).then((r) => add(r.tracks, 'prompt')).catch(() => {}),
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
// Editorial and anonymous feeds keep the pool from collapsing to one genre.
|
|
195
|
+
tasks.push(this.api.recommendSongs(20).then((tracks) => add(tracks, 'daily')).catch(() => {}));
|
|
196
|
+
tasks.push(this.api.personalizedNewsongs(15).then((tracks) => add(tracks, 'new')).catch(() => {}));
|
|
197
|
+
tasks.push(
|
|
198
|
+
this.api
|
|
199
|
+
.playlistDetail('3778678', { limit: 40 })
|
|
200
|
+
.then((playlist) => add(playlist.tracks, 'chart'))
|
|
201
|
+
.catch(() => {}),
|
|
202
|
+
);
|
|
203
|
+
await Promise.all(tasks);
|
|
204
|
+
|
|
205
|
+
// Keep the prompt cheap when the pool overflowed: prefer prompt/similar
|
|
206
|
+
// matches, then the feeds.
|
|
207
|
+
const priority = { prompt: 0, similar: 1, daily: 2, new: 3, chart: 4 };
|
|
208
|
+
pool.sort((a, b) => (priority[a.origin] ?? 9) - (priority[b.origin] ?? 9));
|
|
209
|
+
const trimmed = pool.slice(0, Math.max(count, MAX_POOL));
|
|
210
|
+
return { pool: await this.api.withCovers(trimmed).catch(() => trimmed), digest };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// --------------------------------------------------------------- model tier
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Assemble streamed chunks into text.
|
|
217
|
+
*
|
|
218
|
+
* The terminal failure lives at `reason.failure` and carries the stable code
|
|
219
|
+
* the service documents (`AUTH`, `RATE_LIMIT`, `NO_ADAPTER`, …). No top-level
|
|
220
|
+
* `failure` exists, so reading only that discards the code and leaves an
|
|
221
|
+
* invented message — which is how a provider outage once read as `Error: error`.
|
|
222
|
+
*/
|
|
223
|
+
async #collect(stream) {
|
|
224
|
+
let text = '';
|
|
225
|
+
let failure = null;
|
|
226
|
+
for await (const chunk of stream) {
|
|
227
|
+
// The service emits `type`; its documentation says `kind`. Accept both.
|
|
228
|
+
const type = chunk?.type ?? chunk?.kind;
|
|
229
|
+
if (type === 'text-delta') {
|
|
230
|
+
text += chunk.text ?? '';
|
|
231
|
+
} else if (type === 'finish') {
|
|
232
|
+
const reason = chunk?.reason;
|
|
233
|
+
const kind = typeof reason === 'string' ? reason : reason?.kind;
|
|
234
|
+
if (kind === 'error' || kind === 'aborted') {
|
|
235
|
+
// Keep the reason kind alongside the descriptor: a descriptor with no
|
|
236
|
+
// code still has a kind, and that is the only signal left for the code.
|
|
237
|
+
failure = { kind, ...(reason?.failure ?? chunk?.failure ?? {}) };
|
|
238
|
+
}
|
|
239
|
+
} else if (type === 'error') {
|
|
240
|
+
failure = { kind: 'error', ...(chunk?.failure ?? {}) };
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (failure) {
|
|
244
|
+
const code =
|
|
245
|
+
failure.code ?? failure.name ?? (failure.kind === 'aborted' ? 'ABORTED' : 'UNKNOWN');
|
|
246
|
+
const error = new Error(
|
|
247
|
+
failure.message ?? (failure.kind ? `stream ${failure.kind}` : 'stream failed'),
|
|
248
|
+
);
|
|
249
|
+
error.code = code;
|
|
250
|
+
error.failure = failure;
|
|
251
|
+
throw error;
|
|
252
|
+
}
|
|
253
|
+
return text;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Decide which provider route to call.
|
|
258
|
+
*
|
|
259
|
+
* An explicit pin always wins. Otherwise the gaps are filled from the
|
|
260
|
+
* registered adapters' catalogues, preferring a pinned provider (or model)
|
|
261
|
+
* over the first one. Discovery is a convenience, not a recommendation: the
|
|
262
|
+
* catalogue's first entry is arbitrary, so pinning both fields is the only
|
|
263
|
+
* way to know which model curates.
|
|
264
|
+
*
|
|
265
|
+
* @param {object} llm the mounted LLM service.
|
|
266
|
+
* @returns {Promise<{provider: string, model: string} | null>}
|
|
267
|
+
*/
|
|
268
|
+
async #resolveTarget(llm) {
|
|
269
|
+
const pinned = { provider: this.model.provider, model: this.model.model };
|
|
270
|
+
if (pinned.provider && pinned.model) return pinned;
|
|
271
|
+
|
|
272
|
+
let providers = [];
|
|
273
|
+
try {
|
|
274
|
+
providers = (llm.listProviders?.() ?? [])
|
|
275
|
+
.map((entry) => entry?.id ?? entry?.provider)
|
|
276
|
+
.filter(Boolean);
|
|
277
|
+
} catch {
|
|
278
|
+
providers = [];
|
|
279
|
+
}
|
|
280
|
+
const provider = pinned.provider ?? providers[0];
|
|
281
|
+
if (!provider) return null;
|
|
282
|
+
|
|
283
|
+
let model = pinned.model;
|
|
284
|
+
if (!model) {
|
|
285
|
+
try {
|
|
286
|
+
const models = await llm.listModels?.(provider);
|
|
287
|
+
model = models?.[0]?.id ?? models?.[0]?.model ?? null;
|
|
288
|
+
} catch {
|
|
289
|
+
model = null;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return model ? { provider, model } : null;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Ask the model to choose from the pool.
|
|
297
|
+
* @returns {Promise<{picks: number[], vibe: string} | null>} `null` when the
|
|
298
|
+
* tier is unavailable or answered with nothing usable.
|
|
299
|
+
*/
|
|
300
|
+
async #askModel({ pool, digest, prompt, count }) {
|
|
301
|
+
const llm = this.resolveLlm?.();
|
|
302
|
+
if (!llm?.stream) {
|
|
303
|
+
return this.#decline('no LLM service is mounted (ctx.get("llm") returned nothing)');
|
|
304
|
+
}
|
|
305
|
+
const target = await this.#resolveTarget(llm);
|
|
306
|
+
if (!target?.provider || !target?.model) {
|
|
307
|
+
return this.#decline(
|
|
308
|
+
this.model.provider || this.model.model
|
|
309
|
+
? `no usable route for the configured provider/model (${this.model.provider ?? '?'}/${this.model.model ?? '?'})`
|
|
310
|
+
: 'no provider route is registered, and none could be discovered',
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const catalogue = pool
|
|
315
|
+
.map((track, index) => `${index}. ${track.name} — ${(track.artists ?? []).join('/')}${track.album ? ` (${track.album})` : ''}`)
|
|
316
|
+
.join('\n');
|
|
317
|
+
const brief = [
|
|
318
|
+
`Mood or request: ${prompt?.trim() || '(none — continue the current listening session)'}`,
|
|
319
|
+
`Currently playing: ${this.player.current() ? `${this.player.current().name} — ${this.player.current().artists.join('/')}` : '(nothing)'}`,
|
|
320
|
+
digest.recentlyPlayed.length ? `Recently played: ${digest.recentlyPlayed.join('; ')}` : '',
|
|
321
|
+
digest.topArtists.length ? `Favourite artists: ${digest.topArtists.join(', ')}` : '',
|
|
322
|
+
digest.liked.length ? `Liked: ${digest.liked.join('; ')}` : '',
|
|
323
|
+
digest.disliked.length ? `Disliked (never pick): ${digest.disliked.join('; ')}` : '',
|
|
324
|
+
'',
|
|
325
|
+
`CANDIDATES (choose only by index):\n${catalogue}`,
|
|
326
|
+
'',
|
|
327
|
+
`Choose exactly ${count} tracks in play order.`,
|
|
328
|
+
]
|
|
329
|
+
.filter(Boolean)
|
|
330
|
+
.join('\n');
|
|
331
|
+
|
|
332
|
+
const messages = [
|
|
333
|
+
{
|
|
334
|
+
role: 'user',
|
|
335
|
+
content: [
|
|
336
|
+
{
|
|
337
|
+
type: 'text',
|
|
338
|
+
text:
|
|
339
|
+
'You are the music programmer for a personal NetEase Cloud Music player. ' +
|
|
340
|
+
'Choose the next tracks from the CANDIDATES list only, by index. ' +
|
|
341
|
+
'Favour artists the listener likes and the requested mood; keep variety — never place two tracks by the same artist back to back; ' +
|
|
342
|
+
'avoid anything listed as recently played or disliked. ' +
|
|
343
|
+
'Reply with JSON only, no prose, no code fence: ' +
|
|
344
|
+
'{"vibe":"<one short line describing the set>","picks":[{"index":<candidate index>,"why":"<max 8 words>"}]}',
|
|
345
|
+
},
|
|
346
|
+
{ type: 'text', text: brief },
|
|
347
|
+
],
|
|
348
|
+
},
|
|
349
|
+
];
|
|
350
|
+
|
|
351
|
+
try {
|
|
352
|
+
const text = await this.#collect(llm.stream({ ...target, messages }));
|
|
353
|
+
const json = /\{[\s\S]*\}/.exec(text);
|
|
354
|
+
if (!json) throw new Error('response contained no JSON object');
|
|
355
|
+
const parsed = JSON.parse(json[0]);
|
|
356
|
+
const picks = (parsed.picks ?? [])
|
|
357
|
+
.map((pick) => Number(typeof pick === 'object' ? pick.index : pick))
|
|
358
|
+
.filter((index) => Number.isInteger(index) && index >= 0 && index < pool.length);
|
|
359
|
+
if (picks.length === 0) return this.#decline('the model returned no usable picks');
|
|
360
|
+
const seen = new Set();
|
|
361
|
+
const ordered = [];
|
|
362
|
+
for (const index of picks) {
|
|
363
|
+
if (seen.has(index)) continue;
|
|
364
|
+
seen.add(index);
|
|
365
|
+
ordered.push(index);
|
|
366
|
+
}
|
|
367
|
+
this.logger?.info?.(`[music] DJ model tier chose ${ordered.length} track(s) via ${target.provider}/${target.model}`);
|
|
368
|
+
this.modelError = null;
|
|
369
|
+
this.player.dj.modelError = null;
|
|
370
|
+
return { picks: ordered, vibe: typeof parsed.vibe === 'string' ? parsed.vibe : '', target };
|
|
371
|
+
} catch (error) {
|
|
372
|
+
return this.#decline(describeFailure(error));
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ----------------------------------------------------------- heuristic tier
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Score and interleave candidates without a model.
|
|
380
|
+
*
|
|
381
|
+
* Scoring is deliberately simple and explainable: artist affinity dominates,
|
|
382
|
+
* familiarity is penalised, explicit dislikes are excluded earlier, and a
|
|
383
|
+
* small jitter keeps repeat requests from returning an identical order.
|
|
384
|
+
*/
|
|
385
|
+
#rank({ pool, digest, count }) {
|
|
386
|
+
const favourites = new Set(digest.topArtists);
|
|
387
|
+
const currentArtists = new Set(this.player.current()?.artists ?? []);
|
|
388
|
+
const playedArtists = new Map();
|
|
389
|
+
for (const entry of this.store.state.history.slice(0, 60)) {
|
|
390
|
+
for (const artist of entry.artists ?? []) playedArtists.set(artist, (playedArtists.get(artist) ?? 0) + 1);
|
|
391
|
+
}
|
|
392
|
+
const recentlyPlayed = new Set(digest.recentIds);
|
|
393
|
+
|
|
394
|
+
const scored = pool.map((track) => {
|
|
395
|
+
let score = Math.random() * 0.8;
|
|
396
|
+
for (const artist of track.artists ?? []) {
|
|
397
|
+
if (favourites.has(artist)) score += 2.2;
|
|
398
|
+
if (currentArtists.has(artist)) score += 1.4;
|
|
399
|
+
score += Math.min((playedArtists.get(artist) ?? 0) * 0.15, 1.0);
|
|
400
|
+
}
|
|
401
|
+
if (!recentlyPlayed.has(track.id)) score += 1.0;
|
|
402
|
+
if (track.vip) score -= 0.4; // still playable when signed in, but riskier
|
|
403
|
+
return { track, score };
|
|
404
|
+
});
|
|
405
|
+
scored.sort((a, b) => b.score - a.score);
|
|
406
|
+
|
|
407
|
+
// Interleave so one artist cannot own consecutive slots.
|
|
408
|
+
const picked = [];
|
|
409
|
+
let lastArtist = this.player.current()?.artists?.[0] ?? null;
|
|
410
|
+
while (picked.length < count && scored.length > 0) {
|
|
411
|
+
let chosen = scored.findIndex((entry) => entry.track.artists?.[0] !== lastArtist);
|
|
412
|
+
if (chosen === -1) chosen = 0;
|
|
413
|
+
const [entry] = scored.splice(chosen, 1);
|
|
414
|
+
picked.push(entry.track);
|
|
415
|
+
lastArtist = entry.track.artists?.[0] ?? null;
|
|
416
|
+
}
|
|
417
|
+
return picked;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// ------------------------------------------------------------------- plans
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Produce the next batch.
|
|
424
|
+
* @param {object} [options]
|
|
425
|
+
* @param {string} [options.prompt] mood/request brief.
|
|
426
|
+
* @param {number} [options.count] how many tracks to choose.
|
|
427
|
+
* @returns {Promise<Plan>}
|
|
428
|
+
*/
|
|
429
|
+
async plan({ prompt = '', count = 5 } = {}) {
|
|
430
|
+
const size = Math.min(Math.max(Number(count) || 5, 1), 25);
|
|
431
|
+
const { pool, digest } = await this.#candidates({ prompt, count: size });
|
|
432
|
+
if (pool.length === 0) {
|
|
433
|
+
return { tracks: [], source: 'heuristic', note: 'no candidates were available', poolSize: 0 };
|
|
434
|
+
}
|
|
435
|
+
const answer = await this.#askModel({ pool, digest, prompt, count: size });
|
|
436
|
+
if (answer) {
|
|
437
|
+
return {
|
|
438
|
+
tracks: answer.picks.map((index) => pool[index]),
|
|
439
|
+
source: 'model',
|
|
440
|
+
vibe: answer.vibe,
|
|
441
|
+
/** Which provider route curated, so the choice is observable. */
|
|
442
|
+
route: `${answer.target.provider}/${answer.target.model}`,
|
|
443
|
+
poolSize: pool.length,
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
return {
|
|
447
|
+
tracks: this.#rank({ pool, digest, count: size }),
|
|
448
|
+
source: 'heuristic',
|
|
449
|
+
note: this.modelError
|
|
450
|
+
? `model tier unavailable (${this.modelError}); used similarity, charts and taste feedback`
|
|
451
|
+
: 'no model configured; used similarity, charts and taste feedback',
|
|
452
|
+
poolSize: pool.length,
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Extend the queue when it runs low. Safe to call on every track change: the
|
|
458
|
+
* busy flag and the threshold check make it a no-op most of the time.
|
|
459
|
+
* @returns {Promise<Plan | null>}
|
|
460
|
+
*/
|
|
461
|
+
async topUp({ force = false } = {}) {
|
|
462
|
+
const settings = this.store.settings;
|
|
463
|
+
if (!this.player.dj.enabled && !force) return null;
|
|
464
|
+
if (this.busy) return null;
|
|
465
|
+
const threshold = Math.max(Number(settings.djAutoExtendBelow) || 3, 0);
|
|
466
|
+
if (!force && this.player.index >= 0 && this.player.remaining().length >= threshold) return null;
|
|
467
|
+
|
|
468
|
+
this.busy = true;
|
|
469
|
+
this.player.dj.busy = true;
|
|
470
|
+
this.player.bump();
|
|
471
|
+
try {
|
|
472
|
+
const plan = await this.plan({ prompt: settings.djPrompt ?? '', count: settings.djBatchSize ?? 5 });
|
|
473
|
+
if (plan.tracks.length === 0) {
|
|
474
|
+
this.player.dj = { ...this.player.dj, busy: false, error: plan.note ?? 'no tracks found', lastPlanAt: Date.now() };
|
|
475
|
+
return plan;
|
|
476
|
+
}
|
|
477
|
+
// The DJ only stocks the queue; it never changes the transport state.
|
|
478
|
+
// `play: false` preserves whatever the listener chose, so a top-up while
|
|
479
|
+
// paused does not start playback, while a queue refilled after the last
|
|
480
|
+
// track ended still resumes because `playing` was already true.
|
|
481
|
+
this.player.append(plan.tracks, { source: plan.source, play: false });
|
|
482
|
+
this.player.dj = {
|
|
483
|
+
...this.player.dj,
|
|
484
|
+
busy: false,
|
|
485
|
+
error: null,
|
|
486
|
+
lastPlanAt: Date.now(),
|
|
487
|
+
lastPlan: {
|
|
488
|
+
source: plan.source,
|
|
489
|
+
vibe: plan.vibe ?? plan.note ?? '',
|
|
490
|
+
route: plan.route ?? null,
|
|
491
|
+
added: plan.tracks.length,
|
|
492
|
+
names: plan.tracks.map((track) => `${track.name} — ${(track.artists ?? []).join('/')}`),
|
|
493
|
+
},
|
|
494
|
+
};
|
|
495
|
+
this.player.bump();
|
|
496
|
+
this.logger?.info?.(`[music] DJ added ${plan.tracks.length} track(s) via ${plan.source}`);
|
|
497
|
+
return plan;
|
|
498
|
+
} catch (error) {
|
|
499
|
+
this.player.dj = { ...this.player.dj, busy: false, error: error.message };
|
|
500
|
+
this.player.bump();
|
|
501
|
+
this.logger?.warn?.(`[music] DJ top-up failed: ${error.message}`);
|
|
502
|
+
return null;
|
|
503
|
+
} finally {
|
|
504
|
+
this.busy = false;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Start a DJ session: enable continuous mode, then replace the queue with a
|
|
510
|
+
* freshly planned batch.
|
|
511
|
+
* @returns {Promise<Plan>}
|
|
512
|
+
*/
|
|
513
|
+
async start({ prompt, count = 8 } = {}) {
|
|
514
|
+
this.store.updateSettings({ djEnabled: true, ...(prompt === undefined ? {} : { djPrompt: prompt }) });
|
|
515
|
+
this.player.dj.enabled = true;
|
|
516
|
+
const plan = await this.plan({ prompt: prompt ?? this.store.settings.djPrompt ?? '', count });
|
|
517
|
+
if (plan.tracks.length > 0) {
|
|
518
|
+
this.player.setQueue(plan.tracks, { startIndex: 0, play: true, source: plan.source });
|
|
519
|
+
this.player.dj.lastPlanAt = Date.now();
|
|
520
|
+
this.player.dj.lastPlan = {
|
|
521
|
+
source: plan.source,
|
|
522
|
+
vibe: plan.vibe ?? plan.note ?? '',
|
|
523
|
+
route: plan.route ?? null,
|
|
524
|
+
added: plan.tracks.length,
|
|
525
|
+
names: plan.tracks.map((track) => `${track.name} — ${(track.artists ?? []).join('/')}`),
|
|
526
|
+
};
|
|
527
|
+
this.player.dj.error = null;
|
|
528
|
+
} else {
|
|
529
|
+
this.player.dj.error = plan.note ?? 'no tracks found';
|
|
530
|
+
}
|
|
531
|
+
this.player.bump();
|
|
532
|
+
return plan;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** Turn continuous mode on or off without touching the queue. */
|
|
536
|
+
setEnabled(enabled, { prompt } = {}) {
|
|
537
|
+
const next = Boolean(enabled);
|
|
538
|
+
this.store.updateSettings({ djEnabled: next, ...(prompt === undefined ? {} : { djPrompt: prompt }) });
|
|
539
|
+
this.player.dj.enabled = next;
|
|
540
|
+
this.player.bump();
|
|
541
|
+
return next;
|
|
542
|
+
}
|
|
543
|
+
}
|