@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/index.js
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `music` — NetEase Cloud Music (music.163.com) playback and AI DJ for DSH.
|
|
3
|
+
*
|
|
4
|
+
* The host half owns the NetEase session, the playback queue, the audio proxy,
|
|
5
|
+
* and the agent-facing tools. The browser half (`lib/client.js`) adds a sidebar
|
|
6
|
+
* page that embeds the player served from this plugin's own route prefix.
|
|
7
|
+
*
|
|
8
|
+
* Deliberately dependency-free: only `node:` builtins plus global `fetch`, so
|
|
9
|
+
* the plugin installs from a local path with no package build or peer
|
|
10
|
+
* resolution. Tool definitions and the single HTTP route are written directly
|
|
11
|
+
* against the documented registry shapes.
|
|
12
|
+
*
|
|
13
|
+
* @module @doitian/dsh-music
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import os from 'node:os';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import { fileURLToPath } from 'node:url';
|
|
20
|
+
|
|
21
|
+
import { Netease } from './netease.js';
|
|
22
|
+
import { QrLogin, SessionStore, ANONYMOUS_COOKIE } from './session.js';
|
|
23
|
+
import { Player } from './state.js';
|
|
24
|
+
import { AiDj } from './dj.js';
|
|
25
|
+
import { MusicRouter } from './router.js';
|
|
26
|
+
|
|
27
|
+
export const name = 'music';
|
|
28
|
+
|
|
29
|
+
/** Requires the tool registry and the HTTP server to compose the plugin. */
|
|
30
|
+
export const inject = ['tools', 'webServer'];
|
|
31
|
+
|
|
32
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
33
|
+
|
|
34
|
+
/** Read a shipped asset once at module load; both are small. */
|
|
35
|
+
function readAsset(...segments) {
|
|
36
|
+
return fs.readFileSync(path.join(HERE, ...segments), 'utf8');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Shipped browser assets, read once per module generation.
|
|
41
|
+
*
|
|
42
|
+
* Deliberately module-scoped rather than read inside {@link apply}: a plugin
|
|
43
|
+
* remount re-runs `apply`, and reading here instead would let a remounted
|
|
44
|
+
* plugin serve a page from a *newer* working tree than the code it is running
|
|
45
|
+
* beside. The page and the module must describe the same contract.
|
|
46
|
+
*/
|
|
47
|
+
const PANEL_HTML = readAsset('panel.html');
|
|
48
|
+
const QRCODE_JS = readAsset('vendor', 'qrcode.js');
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Build a `{warn, info, debug}` logger over the Cordis logger.
|
|
52
|
+
* @param {object} ctx plugin context.
|
|
53
|
+
*/
|
|
54
|
+
function makeLogger(ctx) {
|
|
55
|
+
const write = (level, message) => {
|
|
56
|
+
const logger = ctx?.logger;
|
|
57
|
+
if (typeof logger?.[level] === 'function') logger[level](message);
|
|
58
|
+
else if (level === 'warn') console.warn(message);
|
|
59
|
+
};
|
|
60
|
+
return {
|
|
61
|
+
info: (message) => write('info', message),
|
|
62
|
+
warn: (message) => write('warn', message),
|
|
63
|
+
debug: (message) => write('debug', message),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Wrap a definition into the registry-ready tool shape.
|
|
69
|
+
*
|
|
70
|
+
* `ctx.tools.register()` accepts a plain object; `defineTool()` in
|
|
71
|
+
* `@deepseek-ai/dsh-tools` only compiles a friendlier spec into exactly this
|
|
72
|
+
* shape. Writing it directly keeps this plugin free of DSH imports.
|
|
73
|
+
*
|
|
74
|
+
* @param {object} spec
|
|
75
|
+
* @param {string} spec.name
|
|
76
|
+
* @param {string} spec.description
|
|
77
|
+
* @param {object} spec.parameters JSON Schema for the arguments.
|
|
78
|
+
* @param {string} spec.title card title shown in the transcript.
|
|
79
|
+
* @param {(args: object, exec: object) => Promise<object>} spec.execute
|
|
80
|
+
* @param {(args: object, value: object) => object[]} spec.render content blocks.
|
|
81
|
+
*/
|
|
82
|
+
function defineMusicTool({ name: toolName, description, parameters, title, execute, render }) {
|
|
83
|
+
return {
|
|
84
|
+
name: toolName,
|
|
85
|
+
description,
|
|
86
|
+
parameters,
|
|
87
|
+
output: {
|
|
88
|
+
// Results are heterogeneous per action; the model reads the rendered text
|
|
89
|
+
// and the panel reads its own HTTP endpoints, so the schema stays open.
|
|
90
|
+
schema: { type: 'object', properties: {}, additionalProperties: true },
|
|
91
|
+
render: (args, value) => render(args, value),
|
|
92
|
+
},
|
|
93
|
+
presentCall: (args) => ({ card: 'generic', title, kind: 'other', rawInput: args }),
|
|
94
|
+
execute: (args, exec) => execute(args ?? {}, exec),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** One line per track, the form the model reads best. */
|
|
99
|
+
function trackLine(track, index) {
|
|
100
|
+
const artists = (track.artists ?? []).join('/');
|
|
101
|
+
const minutes = Math.floor((track.duration ?? 0) / 60000);
|
|
102
|
+
const seconds = String(Math.floor(((track.duration ?? 0) % 60000) / 1000)).padStart(2, '0');
|
|
103
|
+
return `${index === undefined ? '' : `${index + 1}. `}${track.name} — ${artists}${track.album ? ` (${track.album})` : ''} [id:${track.id}, ${minutes}:${seconds}${track.vip ? ', VIP' : ''}]`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Resolve the harness home the way the rest of DSH does. */
|
|
107
|
+
function dshHome() {
|
|
108
|
+
const fromEnv = process.env.DSH_HOME?.trim();
|
|
109
|
+
return fromEnv || path.join(os.homedir(), '.dsh');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function apply(ctx, config = {}) {
|
|
113
|
+
const logger = makeLogger(ctx);
|
|
114
|
+
const base = `/${String(config.apiPrefix ?? 'music').replace(/^\/+|\/+$/g, '')}`;
|
|
115
|
+
const dataDir = config.dataDir || path.join(dshHome(), 'music');
|
|
116
|
+
|
|
117
|
+
const store = new SessionStore({ file: path.join(dataDir, 'session.json'), logger });
|
|
118
|
+
store.load();
|
|
119
|
+
|
|
120
|
+
const api = new Netease({
|
|
121
|
+
cookie: store.cookie || ANONYMOUS_COOKIE,
|
|
122
|
+
timeoutMs: config.requestTimeoutMs ?? 15_000,
|
|
123
|
+
logger,
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
const player = new Player({ logger });
|
|
127
|
+
// Restore the persisted DJ preference so continuous mode survives a restart.
|
|
128
|
+
player.dj.enabled = Boolean(store.settings.djEnabled);
|
|
129
|
+
|
|
130
|
+
const qr = new QrLogin({ api, store, logger });
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The LLM service is optional: the DJ falls back to its heuristic tier when
|
|
134
|
+
* absent, so the plugin still works in a composition without a model route.
|
|
135
|
+
*/
|
|
136
|
+
const resolveLlm = () => {
|
|
137
|
+
try {
|
|
138
|
+
return ctx.get?.('llm') ?? ctx.llm ?? undefined;
|
|
139
|
+
} catch {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const dj = new AiDj({
|
|
145
|
+
api,
|
|
146
|
+
player,
|
|
147
|
+
store,
|
|
148
|
+
resolveLlm,
|
|
149
|
+
logger,
|
|
150
|
+
// The picker's saved choice wins over the profile patch, so a route chosen
|
|
151
|
+
// in the GUI is not silently overridden by a stale `config.dj` pin.
|
|
152
|
+
model: {
|
|
153
|
+
provider: store.settings.djProvider || config.dj?.provider,
|
|
154
|
+
model: store.settings.djModel || config.dj?.model,
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
player.onLowQueue = () => dj.topUp();
|
|
158
|
+
|
|
159
|
+
/** Tool names that registered successfully; surfaced by `/music/health`. */
|
|
160
|
+
const registeredTools = [];
|
|
161
|
+
|
|
162
|
+
// ------------------------------------------------------------ session boot
|
|
163
|
+
void api
|
|
164
|
+
.fetchAccount()
|
|
165
|
+
.then((account) => {
|
|
166
|
+
if (account) logger.info(`[music] signed in as ${account.nickname}`);
|
|
167
|
+
else if (api.authenticated) logger.warn('[music] session cookie present but the account check failed');
|
|
168
|
+
else logger.info('[music] anonymous session (search and non-VIP playback only)');
|
|
169
|
+
})
|
|
170
|
+
.catch((error) => logger.warn(`[music] account check failed: ${error.message}`));
|
|
171
|
+
|
|
172
|
+
// ---------------------------------------------------------- history + DJ
|
|
173
|
+
let lastRecorded = null;
|
|
174
|
+
player.subscribe(() => {
|
|
175
|
+
const current = player.current();
|
|
176
|
+
if (!current || current.id === lastRecorded) return;
|
|
177
|
+
lastRecorded = current.id;
|
|
178
|
+
store.recordPlay(current);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
// A periodic sweep catches the cases the track-end hook misses: a paused
|
|
182
|
+
// panel, a failed track, or a DJ that was switched on with a short queue.
|
|
183
|
+
const sweep = setInterval(() => {
|
|
184
|
+
if (!player.dj.enabled || player.dj.busy) return;
|
|
185
|
+
const threshold = Math.max(Number(store.settings.djAutoExtendBelow) || 3, 0);
|
|
186
|
+
if (player.remaining().length < threshold) void dj.topUp();
|
|
187
|
+
}, 20_000);
|
|
188
|
+
sweep.unref?.();
|
|
189
|
+
|
|
190
|
+
// ------------------------------------------------------------------ routes
|
|
191
|
+
const router = new MusicRouter({
|
|
192
|
+
base,
|
|
193
|
+
api,
|
|
194
|
+
player,
|
|
195
|
+
store,
|
|
196
|
+
qr,
|
|
197
|
+
dj,
|
|
198
|
+
panelHtml: PANEL_HTML,
|
|
199
|
+
qrcodeJs: QRCODE_JS,
|
|
200
|
+
config,
|
|
201
|
+
listRoutes: () => dj.listRoutes(),
|
|
202
|
+
diagnostics: () => ({
|
|
203
|
+
tools: registeredTools,
|
|
204
|
+
dj: {
|
|
205
|
+
enabled: player.dj.enabled,
|
|
206
|
+
busy: player.dj.busy,
|
|
207
|
+
source: player.dj.source,
|
|
208
|
+
model: dj.modelConfigured ? `${dj.model.provider}/${dj.model.model}` : null,
|
|
209
|
+
/** Where the live route came from: the player, the patch, or discovery. */
|
|
210
|
+
modelSource: store.settings.djProvider || store.settings.djModel
|
|
211
|
+
? 'panel'
|
|
212
|
+
: config.dj?.provider || config.dj?.model
|
|
213
|
+
? 'config'
|
|
214
|
+
: 'discovered',
|
|
215
|
+
/** Route that actually curated the last batch, model tier or not. */
|
|
216
|
+
lastRoute: player.dj.lastPlan?.route ?? null,
|
|
217
|
+
/** Why the model tier last declined; null once it succeeds. */
|
|
218
|
+
modelError: player.dj.modelError ?? null,
|
|
219
|
+
lastPlanAt: player.dj.lastPlanAt,
|
|
220
|
+
error: player.dj.error,
|
|
221
|
+
},
|
|
222
|
+
dataDir,
|
|
223
|
+
session: { authenticated: api.authenticated, nickname: api.account?.nickname ?? null, vip: Boolean(api.account?.vip) },
|
|
224
|
+
uptimeMs: Math.round(process.uptime() * 1000),
|
|
225
|
+
}),
|
|
226
|
+
logger,
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
const disposeRoute = ctx.webServer.register({
|
|
230
|
+
kind: 'prefix',
|
|
231
|
+
path: base,
|
|
232
|
+
handler: (req, res) => router.handle(req, res),
|
|
233
|
+
});
|
|
234
|
+
const panelUrl = () => `http://127.0.0.1:${ctx.webServer.port}${base}/panel`;
|
|
235
|
+
logger.info(`[music] player panel at ${panelUrl()}`);
|
|
236
|
+
|
|
237
|
+
// ------------------------------------------------------------------- tools
|
|
238
|
+
/**
|
|
239
|
+
* Register a tool and record its name for `/music/health`.
|
|
240
|
+
*
|
|
241
|
+
* The route is registered before these calls, so a tool that failed to
|
|
242
|
+
* register would otherwise leave a route that answers normally; reporting the
|
|
243
|
+
* names makes that partial state observable instead of silent.
|
|
244
|
+
*/
|
|
245
|
+
const registerTool = (spec) => {
|
|
246
|
+
ctx.tools.register(defineMusicTool(spec));
|
|
247
|
+
registeredTools.push(spec.name);
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
registerTool({
|
|
251
|
+
name: 'music_search',
|
|
252
|
+
title: 'Search NetEase Cloud Music',
|
|
253
|
+
description:
|
|
254
|
+
'Search NetEase Cloud Music (music.163.com) for songs. Returns track ids usable with music_play. ' +
|
|
255
|
+
'Use this to resolve a request such as "play 周杰伦 晴天" into concrete tracks before queueing anything.',
|
|
256
|
+
parameters: {
|
|
257
|
+
type: 'object',
|
|
258
|
+
additionalProperties: false,
|
|
259
|
+
properties: {
|
|
260
|
+
query: { type: 'string', description: 'Search text: song, artist, or album.' },
|
|
261
|
+
limit: { type: 'integer', description: 'Maximum results (1-50, default 10).' },
|
|
262
|
+
},
|
|
263
|
+
required: ['query'],
|
|
264
|
+
},
|
|
265
|
+
render: (_args, value) => [
|
|
266
|
+
{
|
|
267
|
+
type: 'text',
|
|
268
|
+
text:
|
|
269
|
+
value.tracks.length === 0
|
|
270
|
+
? `No tracks matched "${value.query}" on NetEase Cloud Music.`
|
|
271
|
+
: `${value.total} match(es) for "${value.query}"; showing ${value.tracks.length}:\n` +
|
|
272
|
+
value.tracks.map((track, index) => trackLine(track, index)).join('\n'),
|
|
273
|
+
},
|
|
274
|
+
],
|
|
275
|
+
async execute(args) {
|
|
276
|
+
const query = String(args.query ?? '').trim();
|
|
277
|
+
if (!query) throw new Error('query is required');
|
|
278
|
+
const limit = Math.min(Math.max(Number(args.limit) || 10, 1), 50);
|
|
279
|
+
const result = await api.searchSongs(query, { limit });
|
|
280
|
+
const tracks = await api.withCovers(result.tracks).catch(() => result.tracks);
|
|
281
|
+
return { query, total: result.total, tracks };
|
|
282
|
+
},
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
registerTool({
|
|
286
|
+
name: 'music_play',
|
|
287
|
+
title: 'Play on NetEase Cloud Music',
|
|
288
|
+
description:
|
|
289
|
+
'Queue and start NetEase Cloud Music playback in the user\'s DSH music panel. ' +
|
|
290
|
+
'Pass `ids` when you already have track ids from music_search, or `query` to search and play the best match. ' +
|
|
291
|
+
'Playback happens in the browser panel, so nothing is audible if the user has not opened the Music page.',
|
|
292
|
+
parameters: {
|
|
293
|
+
type: 'object',
|
|
294
|
+
additionalProperties: false,
|
|
295
|
+
properties: {
|
|
296
|
+
ids: { type: 'array', items: { type: 'integer' }, description: 'Track ids to play, in order.' },
|
|
297
|
+
query: { type: 'string', description: 'Search text; the top matches are played when `ids` is omitted.' },
|
|
298
|
+
mode: {
|
|
299
|
+
type: 'string',
|
|
300
|
+
enum: ['replace', 'append', 'next'],
|
|
301
|
+
description: 'replace the queue (default), append to it, or insert right after the current track.',
|
|
302
|
+
},
|
|
303
|
+
limit: { type: 'integer', description: 'How many search matches to queue when using `query` (default 1).' },
|
|
304
|
+
},
|
|
305
|
+
},
|
|
306
|
+
render: (_args, value) => [
|
|
307
|
+
{
|
|
308
|
+
type: 'text',
|
|
309
|
+
text:
|
|
310
|
+
`${value.added} track(s) ${value.mode === 'replace' ? 'queued' : value.mode === 'next' ? 'inserted next' : 'appended'}. ` +
|
|
311
|
+
`Now playing: ${value.current ? `${value.current.name} — ${value.current.artists.join('/')}` : '(nothing)'}. ` +
|
|
312
|
+
`${value.remaining} track(s) after it.` +
|
|
313
|
+
(value.current?.vip ? ' This track is VIP-gated; it needs a signed-in NetEase account.' : '') +
|
|
314
|
+
(value.authenticated ? '' : ' NOTE: the NetEase session is anonymous, so VIP tracks will not play.'),
|
|
315
|
+
},
|
|
316
|
+
],
|
|
317
|
+
async execute(args) {
|
|
318
|
+
let tracks = [];
|
|
319
|
+
if (Array.isArray(args.ids) && args.ids.length > 0) {
|
|
320
|
+
tracks = await api.songDetail(args.ids);
|
|
321
|
+
} else if (args.query) {
|
|
322
|
+
const limit = Math.min(Math.max(Number(args.limit) || 1, 1), 25);
|
|
323
|
+
const result = await api.searchSongs(String(args.query), { limit });
|
|
324
|
+
tracks = await api.withCovers(result.tracks).catch(() => result.tracks);
|
|
325
|
+
}
|
|
326
|
+
if (tracks.length === 0) throw new Error('nothing to play: pass `ids` or a `query` that matches a track');
|
|
327
|
+
|
|
328
|
+
const mode = args.mode ?? 'replace';
|
|
329
|
+
if (mode === 'append') player.append(tracks, { source: 'agent' });
|
|
330
|
+
else if (mode === 'next') player.insertNext(tracks, { source: 'agent' });
|
|
331
|
+
else player.setQueue(tracks, { startIndex: 0, play: true, source: 'agent' });
|
|
332
|
+
store.recordPlay(player.current() ?? tracks[0]);
|
|
333
|
+
|
|
334
|
+
const summary = player.summary();
|
|
335
|
+
return {
|
|
336
|
+
added: tracks.length,
|
|
337
|
+
mode,
|
|
338
|
+
current: summary.current,
|
|
339
|
+
remaining: summary.remaining,
|
|
340
|
+
authenticated: api.authenticated,
|
|
341
|
+
panelUrl: panelUrl(),
|
|
342
|
+
};
|
|
343
|
+
},
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
registerTool({
|
|
347
|
+
name: 'music_queue',
|
|
348
|
+
title: 'Edit the music queue',
|
|
349
|
+
description:
|
|
350
|
+
'Inspect or edit the NetEase Cloud Music queue in the user\'s DSH music panel: append, insert, replace, remove one entry, jump to an entry, or clear.',
|
|
351
|
+
parameters: {
|
|
352
|
+
type: 'object',
|
|
353
|
+
additionalProperties: false,
|
|
354
|
+
properties: {
|
|
355
|
+
action: {
|
|
356
|
+
type: 'string',
|
|
357
|
+
enum: ['show', 'append', 'insert', 'replace', 'remove', 'jump', 'clear'],
|
|
358
|
+
description: 'Queue operation. `show` only reports the current queue.',
|
|
359
|
+
},
|
|
360
|
+
ids: { type: 'array', items: { type: 'integer' }, description: 'Track ids for append/insert/replace.' },
|
|
361
|
+
index: { type: 'integer', description: 'Zero-based queue position for remove/jump.' },
|
|
362
|
+
},
|
|
363
|
+
required: ['action'],
|
|
364
|
+
},
|
|
365
|
+
render: (_args, value) => [
|
|
366
|
+
{
|
|
367
|
+
type: 'text',
|
|
368
|
+
text:
|
|
369
|
+
`Queue: ${value.queued} track(s), ${value.remaining} after the current one.\n` +
|
|
370
|
+
(value.upNext.length
|
|
371
|
+
? `Up next:\n${value.upNext.map((track, index) => trackLine(track, index)).join('\n')}`
|
|
372
|
+
: 'Nothing is queued after the current track.'),
|
|
373
|
+
},
|
|
374
|
+
],
|
|
375
|
+
async execute(args) {
|
|
376
|
+
const action = String(args.action ?? 'show');
|
|
377
|
+
if (action === 'show') return player.summary();
|
|
378
|
+
if (action === 'clear') {
|
|
379
|
+
player.clear();
|
|
380
|
+
return player.summary();
|
|
381
|
+
}
|
|
382
|
+
if (action === 'remove' || action === 'jump') {
|
|
383
|
+
const index = Number(args.index);
|
|
384
|
+
if (!Number.isInteger(index)) throw new Error(`\`index\` is required for ${action}`);
|
|
385
|
+
if (action === 'remove') player.remove(index);
|
|
386
|
+
else player.jump(index);
|
|
387
|
+
return player.summary();
|
|
388
|
+
}
|
|
389
|
+
const tracks = await api.songDetail(args.ids ?? []);
|
|
390
|
+
if (tracks.length === 0) throw new Error('`ids` must name at least one known track');
|
|
391
|
+
if (action === 'append') player.append(tracks, { source: 'agent' });
|
|
392
|
+
else if (action === 'insert') player.insertNext(tracks, { source: 'agent' });
|
|
393
|
+
else if (action === 'replace') player.setQueue(tracks, { startIndex: 0, play: true, source: 'agent' });
|
|
394
|
+
else throw new Error(`unknown action "${action}"`);
|
|
395
|
+
return player.summary();
|
|
396
|
+
},
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
registerTool({
|
|
400
|
+
name: 'music_control',
|
|
401
|
+
title: 'Control music playback',
|
|
402
|
+
description:
|
|
403
|
+
'Control the NetEase Cloud Music panel: play, pause, next, previous, seek, volume, mute, or repeat mode. ' +
|
|
404
|
+
'Use music_now_playing first when you need to know what is playing.',
|
|
405
|
+
parameters: {
|
|
406
|
+
type: 'object',
|
|
407
|
+
additionalProperties: false,
|
|
408
|
+
properties: {
|
|
409
|
+
action: {
|
|
410
|
+
type: 'string',
|
|
411
|
+
enum: ['play', 'pause', 'toggle', 'next', 'previous', 'seek', 'volume', 'mute', 'mode'],
|
|
412
|
+
},
|
|
413
|
+
value: {
|
|
414
|
+
description:
|
|
415
|
+
'seek: absolute milliseconds. volume: 0-1. mute: boolean. mode: list | single | shuffle.',
|
|
416
|
+
},
|
|
417
|
+
},
|
|
418
|
+
required: ['action'],
|
|
419
|
+
},
|
|
420
|
+
render: (_args, value) => [
|
|
421
|
+
{
|
|
422
|
+
type: 'text',
|
|
423
|
+
text:
|
|
424
|
+
`${value.playing ? 'Playing' : 'Paused'}${
|
|
425
|
+
value.current ? `: ${value.current.name} — ${value.current.artists.join('/')}` : ' (queue empty)'
|
|
426
|
+
}. Mode ${value.mode}, volume ${Math.round(value.volume * 100)}%. ` +
|
|
427
|
+
`${value.remaining} track(s) after the current one.`,
|
|
428
|
+
},
|
|
429
|
+
],
|
|
430
|
+
async execute(args) {
|
|
431
|
+
switch (args.action) {
|
|
432
|
+
case 'play': player.setPlaying(true); break;
|
|
433
|
+
case 'pause': player.setPlaying(false); break;
|
|
434
|
+
case 'toggle': player.toggle(); break;
|
|
435
|
+
case 'next': player.move(1); break;
|
|
436
|
+
case 'previous': player.move(-1); break;
|
|
437
|
+
case 'seek': player.seek(Number(args.value) || 0); break;
|
|
438
|
+
case 'volume': player.setVolume(args.value); break;
|
|
439
|
+
case 'mute': player.setMuted(Boolean(args.value)); break;
|
|
440
|
+
case 'mode': player.setMode(String(args.value)); break;
|
|
441
|
+
default: throw new Error(`unknown action "${args.action}"`);
|
|
442
|
+
}
|
|
443
|
+
return player.summary();
|
|
444
|
+
},
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
registerTool({
|
|
448
|
+
name: 'music_dj',
|
|
449
|
+
title: 'AI DJ (NetEase Cloud Music)',
|
|
450
|
+
description:
|
|
451
|
+
'Run or configure the continuous AI DJ for the user\'s NetEase Cloud Music panel. ' +
|
|
452
|
+
'With `enabled: true` the DJ keeps the queue stocked: it gathers candidates from similar songs, the daily ' +
|
|
453
|
+
'recommendations, the charts and any mood brief, then either asks the model to choose or scores them by the ' +
|
|
454
|
+
'listener\'s liked artists, novelty and feedback. Pass `prompt` for a mood or vibe, and `replan` to refill now.',
|
|
455
|
+
parameters: {
|
|
456
|
+
type: 'object',
|
|
457
|
+
additionalProperties: false,
|
|
458
|
+
properties: {
|
|
459
|
+
enabled: { type: 'boolean', description: 'Turn continuous queue topping-up on or off.' },
|
|
460
|
+
prompt: { type: 'string', description: 'Mood or request, e.g. "rainy afternoon jazz", "90s cantopop".' },
|
|
461
|
+
replan: { type: 'boolean', description: 'Plan and queue a fresh batch immediately.' },
|
|
462
|
+
count: { type: 'integer', description: 'How many tracks to plan (1-25, default 8 for `replan`).' },
|
|
463
|
+
start: { type: 'boolean', description: 'Replace the queue with a freshly planned batch (a full DJ session).' },
|
|
464
|
+
},
|
|
465
|
+
},
|
|
466
|
+
render: (_args, value) => [
|
|
467
|
+
{
|
|
468
|
+
type: 'text',
|
|
469
|
+
text:
|
|
470
|
+
`AI DJ is ${value.enabled ? 'on' : 'off'} (${value.source}${value.route ? ` via ${value.route}` : ''}). ` +
|
|
471
|
+
(value.modelError ? `Model tier unavailable: ${value.modelError}. ` : '') +
|
|
472
|
+
(value.vibe ? `Vibe: ${value.vibe}. ` : '') +
|
|
473
|
+
(value.names.length
|
|
474
|
+
? `Queued ${value.added} track(s):\n${value.names.map((entry, index) => `${index + 1}. ${entry}`).join('\n')}`
|
|
475
|
+
: value.note || 'No new tracks were queued.') +
|
|
476
|
+
(value.authenticated ? '' : ' The NetEase session is anonymous, so VIP tracks will be skipped by the browser.'),
|
|
477
|
+
},
|
|
478
|
+
],
|
|
479
|
+
async execute(args) {
|
|
480
|
+
const enabled = args.enabled === undefined ? undefined : Boolean(args.enabled);
|
|
481
|
+
const prompt = args.prompt === undefined ? undefined : String(args.prompt);
|
|
482
|
+
if (enabled !== undefined || prompt !== undefined) dj.setEnabled(enabled ?? player.dj.enabled, { prompt });
|
|
483
|
+
|
|
484
|
+
const count = Math.min(Math.max(Number(args.count) || 8, 1), 25);
|
|
485
|
+
let plan = null;
|
|
486
|
+
if (args.start) {
|
|
487
|
+
plan = await dj.start({ prompt, count });
|
|
488
|
+
} else if (args.replan || (enabled === true && player.queue.length === 0)) {
|
|
489
|
+
plan = await dj.topUp({ force: true });
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
const summary = player.summary();
|
|
493
|
+
return {
|
|
494
|
+
enabled: summary.dj.enabled,
|
|
495
|
+
source: plan?.source ?? summary.dj.source ?? (dj.modelConfigured ? 'model' : 'heuristic'),
|
|
496
|
+
route: plan?.route ?? summary.dj.lastPlan?.route ?? null,
|
|
497
|
+
modelError: player.dj.modelError ?? null,
|
|
498
|
+
vibe: plan?.vibe ?? summary.dj.lastPlan?.vibe ?? '',
|
|
499
|
+
note: plan?.note ?? (plan && plan.tracks.length === 0 ? 'no candidates were available' : ''),
|
|
500
|
+
added: plan?.tracks.length ?? 0,
|
|
501
|
+
names: (plan?.tracks ?? []).map((track) => `${track.name} — ${(track.artists ?? []).join('/')}`),
|
|
502
|
+
authenticated: api.authenticated,
|
|
503
|
+
current: summary.current,
|
|
504
|
+
remaining: summary.remaining,
|
|
505
|
+
};
|
|
506
|
+
},
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
registerTool({
|
|
510
|
+
name: 'music_now_playing',
|
|
511
|
+
title: 'What is playing',
|
|
512
|
+
description:
|
|
513
|
+
'Report what the NetEase Cloud Music panel is playing, what comes next, and whether the NetEase account is signed in.',
|
|
514
|
+
parameters: { type: 'object', additionalProperties: false, properties: {} },
|
|
515
|
+
render: (_args, value) => [
|
|
516
|
+
{
|
|
517
|
+
type: 'text',
|
|
518
|
+
text:
|
|
519
|
+
(value.current
|
|
520
|
+
? `${value.playing ? 'Playing' : 'Paused'}: ${value.current.name} — ${value.current.artists.join('/')} ` +
|
|
521
|
+
`at ${Math.floor((value.positionMs ?? 0) / 1000)}s of ${Math.floor((value.current.durationMs ?? 0) / 1000)}s.`
|
|
522
|
+
: 'Nothing is playing; the music queue is empty.') +
|
|
523
|
+
`\nUp next: ${value.upNext.length ? value.upNext.map((track) => `${track.name} — ${track.artists.join('/')}`).join('; ') : '(nothing)'}` +
|
|
524
|
+
`\nAccount: ${value.account ? `${value.account.nickname}${value.account.vip ? ' (VIP)' : ''}` : 'anonymous (VIP tracks unavailable)'}` +
|
|
525
|
+
(value.lastError ? `\nNote: a track failed and was skipped (${value.lastError}).` : '') +
|
|
526
|
+
`\nPanel: ${value.panelUrl}`,
|
|
527
|
+
},
|
|
528
|
+
],
|
|
529
|
+
async execute() {
|
|
530
|
+
return { ...player.summary(), account: api.account, authenticated: api.authenticated, panelUrl: panelUrl() };
|
|
531
|
+
},
|
|
532
|
+
});
|
|
533
|
+
|
|
534
|
+
registerTool({
|
|
535
|
+
name: 'music_login',
|
|
536
|
+
title: 'NetEase Cloud Music sign-in',
|
|
537
|
+
description:
|
|
538
|
+
'Check or change the NetEase Cloud Music sign-in. `status` reports the account. `qr` starts a QR sign-in and ' +
|
|
539
|
+
'returns a URL the user scans with the NetEase Cloud Music mobile app (they can also just open the Music page). ' +
|
|
540
|
+
'`set_cookie` accepts a MUSIC_U cookie pasted from a browser session. `logout` forgets the session.',
|
|
541
|
+
parameters: {
|
|
542
|
+
type: 'object',
|
|
543
|
+
additionalProperties: false,
|
|
544
|
+
properties: {
|
|
545
|
+
action: { type: 'string', enum: ['status', 'qr', 'poll', 'set_cookie', 'logout'] },
|
|
546
|
+
cookie: { type: 'string', description: 'Cookie header value, for `set_cookie`.' },
|
|
547
|
+
},
|
|
548
|
+
required: ['action'],
|
|
549
|
+
},
|
|
550
|
+
render: (_args, value) => [
|
|
551
|
+
{
|
|
552
|
+
type: 'text',
|
|
553
|
+
text:
|
|
554
|
+
value.loggedIn
|
|
555
|
+
? `Signed in to NetEase Cloud Music as ${value.account?.nickname ?? '(unknown)'}${value.account?.vip ? ' (VIP)' : ''}.`
|
|
556
|
+
: `Not signed in to NetEase Cloud Music (${value.message ?? 'anonymous'}). Only non-VIP tracks play.` +
|
|
557
|
+
(value.scanUrl ? `\nScan this QR with the NetEase Cloud Music app, or open ${value.panelUrl} and use 登录: ${value.scanUrl}` : ''),
|
|
558
|
+
},
|
|
559
|
+
],
|
|
560
|
+
async execute(args) {
|
|
561
|
+
const panel = panelUrl();
|
|
562
|
+
switch (args.action) {
|
|
563
|
+
case 'status': {
|
|
564
|
+
const account = api.authenticated ? await api.fetchAccount().catch(() => null) : null;
|
|
565
|
+
return { loggedIn: Boolean(account), account, message: account ? '' : 'anonymous session', panelUrl: panel };
|
|
566
|
+
}
|
|
567
|
+
case 'qr': {
|
|
568
|
+
const attempt = await qr.start();
|
|
569
|
+
return {
|
|
570
|
+
loggedIn: false,
|
|
571
|
+
account: null,
|
|
572
|
+
message: 'QR code ready; it expires in about two minutes',
|
|
573
|
+
scanUrl: attempt.loginUrl,
|
|
574
|
+
panelUrl: panel,
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
case 'poll': {
|
|
578
|
+
const result = await qr.poll();
|
|
579
|
+
return {
|
|
580
|
+
loggedIn: Boolean(api.account),
|
|
581
|
+
account: api.account,
|
|
582
|
+
message: result.message,
|
|
583
|
+
scanUrl: result.loginUrl,
|
|
584
|
+
panelUrl: panel,
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
case 'set_cookie': {
|
|
588
|
+
if (!args.cookie) throw new Error('`cookie` is required for set_cookie');
|
|
589
|
+
api.setCookie(String(args.cookie).trim());
|
|
590
|
+
const account = await api.fetchAccount();
|
|
591
|
+
if (!account) throw new Error('that cookie did not yield an account (expired or malformed)');
|
|
592
|
+
store.setSession(api.jar.header(), account);
|
|
593
|
+
return { loggedIn: true, account, message: 'signed in', panelUrl: panel };
|
|
594
|
+
}
|
|
595
|
+
case 'logout': {
|
|
596
|
+
api.clearCookie();
|
|
597
|
+
store.clearSession();
|
|
598
|
+
qr.reset();
|
|
599
|
+
return { loggedIn: false, account: null, message: 'signed out', panelUrl: panel };
|
|
600
|
+
}
|
|
601
|
+
default:
|
|
602
|
+
throw new Error(`unknown action "${args.action}"`);
|
|
603
|
+
}
|
|
604
|
+
},
|
|
605
|
+
});
|
|
606
|
+
|
|
607
|
+
// ----------------------------------------------------------------- cleanup
|
|
608
|
+
ctx.effect(() => () => {
|
|
609
|
+
clearInterval(sweep);
|
|
610
|
+
try {
|
|
611
|
+
disposeRoute();
|
|
612
|
+
} catch {
|
|
613
|
+
// The route table is already gone when the webserver unloads first.
|
|
614
|
+
}
|
|
615
|
+
store.close();
|
|
616
|
+
logger.debug('[music] unloaded');
|
|
617
|
+
});
|
|
618
|
+
}
|