@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/cordis.patch.yml CHANGED
@@ -9,7 +9,8 @@
9
9
  # apiPrefix route prefix (default `music`) — keep it `music` unless
10
10
  # you also rebuild the browser half.
11
11
  # dataDir where session.json lives (default $DSH_HOME/music).
12
- # audioLevel exhigh (320 kbps, default) | standard | higher | lossless
12
+ # audioLevel exhigh (320 kbps, default); also standard, higher,
13
+ # lossless, hires, jymaster, dolby, sky, jyeffect.
13
14
  # requestTimeoutMs NetEase request deadline (default 15000).
14
15
  # dj.provider model route for the AI DJ's model tier, e.g. opencode-go.
15
16
  # dj.model exact model id, e.g. deepseek-v4.1-flash.
@@ -23,14 +24,17 @@
23
24
  # conversation.
24
25
  #
25
26
  # Route resolution, highest first: the player's picker -> `dj.provider`/`dj.model`
26
- # -> the deployment's own `agent-default-model` (the model the agent loop runs
27
- # on, which is why "use my session model" needs no configuration) -> discovery,
28
- # whose first row is arbitrary. The DJ is not an agent and starts none: each
29
- # plan is one stateless leaf call, so there is no session to rotate or dispose.
27
+ # -> the session's default model (`agent-default-model`, which is why "use my
28
+ # session model" needs no configuration) -> discovery, whose first row is
29
+ # arbitrary. Only the choice of model is shared with the session: the DJ is not
30
+ # an agent and starts none. It makes stateless leaf calls — one to curate each
31
+ # plan, and one to rewrite a mood brief into search terms the first time that
32
+ # brief is seen — so there is no session to rotate or dispose.
30
33
  #
31
- # Without `dj.provider`/`dj.model` the DJ still works: it falls back to scoring
32
- # similar songs, the daily recommendations and the charts by the listener's
33
- # liked artists, novelty and feedback.
34
+ # With no model route at all the DJ still works: it scores its candidates —
35
+ # similar songs, personal FM, rested likes, the daily recommendations, the
36
+ # charts and any mood brief — by brief match, artist affinity, and the
37
+ # listener's likes, dislikes and skips.
34
38
  - insert:
35
39
  - id: music
36
40
  name: '@doitian/dsh-music'
package/lib/cache.js ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * How the DJ reads its sources: a time-bounded cache, the sampling it draws
3
+ * its pool with, and the pacing its requests are sent at.
4
+ *
5
+ * Most of the DJ's sources change on the scale of hours or days — a chart
6
+ * daily, similarity effectively never — so fetching each one on every plan
7
+ * spends requests to learn nothing. The cache keeps each source for as long as
8
+ * it plausibly stays the same, and the DJ samples from what it holds, so a
9
+ * long cached list still yields a different handful each time. What does go
10
+ * out is paced like a person browsing, not fired as a burst.
11
+ *
12
+ * @module dsh-music/cache
13
+ */
14
+
15
+ /** Entries kept at most; the oldest are dropped first. */
16
+ const MAX_ENTRIES = 2_000;
17
+
18
+ export class TtlCache {
19
+ /**
20
+ * @param {object} [options]
21
+ * @param {() => number} [options.now] clock, injectable for tests.
22
+ * @param {number} [options.maxEntries]
23
+ */
24
+ constructor({ now = Date.now, maxEntries = MAX_ENTRIES } = {}) {
25
+ this.now = now;
26
+ this.maxEntries = maxEntries;
27
+ /** @type {Map<string, {value: unknown, expiresAt: number}>} */
28
+ this.entries = new Map();
29
+ }
30
+
31
+ /** The live value for `key`, or `undefined` when absent or expired. */
32
+ peek(key) {
33
+ const entry = this.entries.get(key);
34
+ if (!entry) return undefined;
35
+ if (entry.expiresAt <= this.now()) {
36
+ this.entries.delete(key);
37
+ return undefined;
38
+ }
39
+ return entry.value;
40
+ }
41
+
42
+ set(key, value, ttlMs) {
43
+ this.entries.delete(key);
44
+ this.entries.set(key, { value, expiresAt: this.now() + ttlMs });
45
+ while (this.entries.size > this.maxEntries) this.entries.delete(this.entries.keys().next().value);
46
+ return value;
47
+ }
48
+
49
+ /**
50
+ * The cached value for `key`, loading it when absent or expired.
51
+ *
52
+ * The pending load is what gets cached, so two plans racing for the same
53
+ * source share one request. A failed load is forgotten rather than cached:
54
+ * the next plan should try again, not inherit the outage for the whole TTL.
55
+ *
56
+ * @template T
57
+ * @param {string} key
58
+ * @param {number} ttlMs
59
+ * @param {() => Promise<T>} load
60
+ * @returns {Promise<T>}
61
+ */
62
+ get(key, ttlMs, load) {
63
+ const cached = this.peek(key);
64
+ if (cached !== undefined) return cached;
65
+ const pending = Promise.resolve().then(load);
66
+ this.set(key, pending, ttlMs);
67
+ pending.catch(() => {
68
+ if (this.entries.get(key)?.value === pending) this.entries.delete(key);
69
+ });
70
+ return pending;
71
+ }
72
+
73
+ clear() {
74
+ this.entries.clear();
75
+ }
76
+
77
+ get size() {
78
+ return this.entries.size;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * A random `count` of `items`, kept in their original order.
84
+ *
85
+ * Random so a cached list still yields a different handful each plan — taking
86
+ * the first `count` would serve the same tracks until the source changes. In
87
+ * order, because a source's order carries meaning (chart rank, search
88
+ * relevance), and the pool keeps it.
89
+ *
90
+ * @template T
91
+ * @param {T[]} items
92
+ * @param {number} count
93
+ * @param {() => number} [random]
94
+ * @returns {T[]}
95
+ */
96
+ export function sampleInOrder(items, count, random = Math.random) {
97
+ if (count >= items.length) return [...items];
98
+ if (count <= 0) return [];
99
+ const indices = items.map((_, index) => index);
100
+ for (let index = 0; index < count; index += 1) {
101
+ const swap = index + Math.floor(random() * (indices.length - index));
102
+ [indices[index], indices[swap]] = [indices[swap], indices[index]];
103
+ }
104
+ return indices
105
+ .slice(0, count)
106
+ .sort((a, b) => a - b)
107
+ .map((index) => items[index]);
108
+ }
109
+
110
+ /**
111
+ * Spaces out request starts by a randomised gap.
112
+ *
113
+ * A plan touches up to a dozen sources, and firing them at once is a crawler's
114
+ * signature: a tight burst at a machine-regular rhythm. Starts are spaced
115
+ * instead, each by its own random gap, so the traffic reads like someone
116
+ * clicking through the app. Only starts are spaced — a request already sent may
117
+ * still be in flight when the next starts, as on any page that is loading.
118
+ */
119
+ export class Pacer {
120
+ /**
121
+ * @param {object} [options]
122
+ * @param {number} [options.minGapMs] the shortest gap between two starts.
123
+ * @param {number} [options.jitterMs] the random span added to each gap.
124
+ * @param {() => number} [options.now]
125
+ * @param {(ms: number) => Promise<void>} [options.sleep]
126
+ * @param {() => number} [options.random]
127
+ */
128
+ constructor({
129
+ minGapMs = 250,
130
+ jitterMs = 500,
131
+ now = Date.now,
132
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
133
+ random = Math.random,
134
+ } = {}) {
135
+ this.minGapMs = minGapMs;
136
+ this.jitterMs = jitterMs;
137
+ this.now = now;
138
+ this.sleep = sleep;
139
+ this.random = random;
140
+ /** The earliest the next request may start. */
141
+ this.nextAt = 0;
142
+ }
143
+
144
+ /**
145
+ * Run `task` at the next free start slot.
146
+ * @template T
147
+ * @param {() => Promise<T>} task
148
+ * @returns {Promise<T>}
149
+ */
150
+ run(task) {
151
+ const at = Math.max(this.now(), this.nextAt);
152
+ this.nextAt = at + this.minGapMs + this.random() * this.jitterMs;
153
+ const wait = at - this.now();
154
+ return (wait > 0 ? this.sleep(wait) : Promise.resolve()).then(task);
155
+ }
156
+ }