dsh-folia 4.26.0-pre.2 → 4.26.0-pre.3

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/lib/client.js CHANGED
@@ -8101,6 +8101,8 @@ window.__ModuleLoader__.load({
8101
8101
  // enabled 与"宠物音效"完全无关(音效开关不影响朗读,反之亦然)。
8102
8102
  // voiceURI 空 = 自动挑中文音色(zh / Chinese / Huihui / Xiaoxiao …)。
8103
8103
  voiceOut: { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' },
8104
+ // 朗读引擎:system = 系统音色(默认、离线);edge = 在线情感朗读(文本经微软,需联网)
8105
+ voiceEngine: 'system',
8104
8106
  },
8105
8107
  };
8106
8108
 
@@ -8882,6 +8884,7 @@ window.__ModuleLoader__.load({
8882
8884
  ? src.quietHours : def.quietHours,
8883
8885
  voiceEnabled: src.voiceEnabled === true,
8884
8886
  voiceOut: readVoiceOut(src.voiceOut),
8887
+ voiceEngine: src.voiceEngine === 'edge' ? 'edge' : 'system',
8885
8888
  };
8886
8889
  }
8887
8890
 
@@ -20665,6 +20668,7 @@ window.__ModuleLoader__.load({
20665
20668
  function petChatHide() {
20666
20669
  if (!petChatEls) return;
20667
20670
  petChatTts.cancel(); // 关闭气泡:立刻停读
20671
+ if (petChatAudioPlayer) { try { petChatAudioPlayer.pause(); } catch { /* ignore */ } petChatAudioPlayer = null; }
20668
20672
  petChatEls.root.style.display = 'none';
20669
20673
  }
20670
20674
 
@@ -20761,7 +20765,7 @@ window.__ModuleLoader__.load({
20761
20765
  // 没有模型:不假装在对话,直接给预设台词
20762
20766
  const presetLine = petChatPresetLine();
20763
20767
  petChatPush('assistant', presetLine);
20764
- petChatTts.finish(presetLine);
20768
+ void petChatSpeak(presetLine, 'calm');
20765
20769
  petChatStatus(weT('未开启对话(设置 → 桌宠 → 桌宠对话)'));
20766
20770
  petChatBusy = false;
20767
20771
  return;
@@ -20804,7 +20808,7 @@ window.__ModuleLoader__.load({
20804
20808
  petChatLines[petChatLines.length - 1] = { role: 'assistant', text: assistant };
20805
20809
  petChatRender();
20806
20810
  } else if (parsed.event === 'done') {
20807
- petChatTts.finish(assistant);
20811
+ void petChatSpeak(assistant, parsed.data && parsed.data.emotion);
20808
20812
  petChatApplyEmotion(parsed.data && parsed.data.emotion);
20809
20813
  petChatStatus('');
20810
20814
  } else if (parsed.event === 'error') {
@@ -20886,6 +20890,26 @@ window.__ModuleLoader__.load({
20886
20890
  let petChatVoice = null;
20887
20891
  let petChatVoiceEnabled = null;
20888
20892
  // 朗读(TTS):默认开;配置由 /state 带回,没拿到时按默认值(开)
20893
+ /** 朗读入口:engine=edge 走宿主合成,其余(或失败)走系统音色。 */
20894
+ async function petChatSpeak(text, emotion) {
20895
+ const config = petChatVoiceOut || {};
20896
+ if (config.enabled !== true) return;
20897
+ if (config.engine === 'edge') {
20898
+ try {
20899
+ const res = await apiPostJson('/pet-chat/speak', { text, emotion: emotion || 'calm' }, { parse: 'always' });
20900
+ const doc = (res && res.data) || {};
20901
+ if (doc.ok && doc.engine === 'edge' && doc.audio) {
20902
+ const player = new Audio('data:' + (doc.mime || 'audio/mpeg') + ';base64,' + doc.audio);
20903
+ petChatAudioPlayer = player;
20904
+ void player.play();
20905
+ return;
20906
+ }
20907
+ // doc.engine==='system'(含回落)⇒ 往下走系统音色
20908
+ } catch { /* 网络问题一律回落系统音色 */ }
20909
+ }
20910
+ petChatTts.finish(text);
20911
+ }
20912
+ let petChatAudioPlayer = null;
20889
20913
  let petChatVoiceOut = { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' };
20890
20914
  const petChatTts = petChatTtsCreate({
20891
20915
  getSpeech: () => (typeof window !== 'undefined' ? window.speechSynthesis : null),
package/lib/index.js CHANGED
@@ -304,6 +304,8 @@ export function apply(ctx) {
304
304
  // 语音输入:宿主自带的转写服务。用户没启用「语音输入」时这里是 undefined,
305
305
  // 路由据此回 asr-not-ready(不是启动失败)。
306
306
  speechToText: ctx.speechToText,
307
+ // edge-tts:默认用内置实现(生产),判据可注入假 transport
308
+ edgeTts: undefined,
307
309
  });
308
310
 
309
311
  // 启动预热(有意不阻塞):站点清单与模块索引各拉一次,让第一次打开面板不冷。
@@ -0,0 +1,105 @@
1
+ /**
2
+ * pet-chat-edge-tts.js — **edge-tts 在线情感朗读**的宿主侧实现(第二档引擎)。
3
+ *
4
+ * 为什么放宿主:文本要经第三方(微软),渲染进程不该直连;桌面端也没有 CORS 可言。
5
+ * 宿主用 Node 22 自带的全局 `WebSocket` 连 Edge 的朗读端点,拿回 mp3 字节交给客户端播。
6
+ *
7
+ * 契约(工单阶段 2):
8
+ * · `voiceEngine: 'system' | 'edge'`(默认 system);edge = 在线、0 下载、需联网;
9
+ * · 风格映射:happy→cheerful、tired→gentle、angry→angry、calm→narration;
10
+ * · 失败(网络/接口变更/超时)⇒ 调用方回落 system,并**只记一次日志**。
11
+ *
12
+ * 这里的 `synthesize()` 是**可注入**的:判据用假 transport(不联网),生产用默认实现。
13
+ */
14
+
15
+ /** 情感 → Edge SSML 的 `mstts:express-as` 风格名。 */
16
+ export const EDGE_STYLE_MAP = Object.freeze({
17
+ happy: 'cheerful',
18
+ tired: 'gentle',
19
+ angry: 'angry',
20
+ calm: 'narration',
21
+ });
22
+
23
+ /** 默认音色(中文女声;与系统音色自动挑选口径一致)。 */
24
+ export const EDGE_DEFAULT_VOICE = 'zh-CN-XiaoxiaoNeural';
25
+
26
+ /** Edge 朗读端点(公开的 read-aloud 通道;接口若变更由回落兜住)。 */
27
+ export const EDGE_ENDPOINT = 'wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1'
28
+ + '?TrustedClientToken=6A5AA1D4EAFF4E9FB37E23D68491D6F4';
29
+
30
+ /** 把段落包成 Edge 要求的 SSML(带情感风格)。 */
31
+ export function buildEdgeSsml({ text, emotion = 'calm', voice = EDGE_DEFAULT_VOICE, rate = 1, pitch = 1, volume = 1 } = {}) {
32
+ const style = EDGE_STYLE_MAP[emotion] || EDGE_STYLE_MAP.calm;
33
+ const escaped = String(text ?? '')
34
+ .replace(/&/g, '&')
35
+ .replace(/</g, '&lt;')
36
+ .replace(/>/g, '&gt;')
37
+ .replace(/"/g, '&quot;');
38
+ // Edge 的 rate/pitch/volume 是相对百分比字符串(+0% = 原速)
39
+ const percent = (value) => `${Math.round((Number(value) || 1) * 100 - 100) >= 0 ? '+' : ''}${Math.round((Number(value) || 1) * 100 - 100)}%`;
40
+ const volPercent = `${Math.round(Math.min(1, Math.max(0, Number(volume) || 1)) * 100)}%`;
41
+ return `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="zh-CN">`
42
+ + `<voice name="${voice}">`
43
+ + `<mstts:express-as style="${style}" styledegree="1.2">`
44
+ + `<prosody rate="${percent(rate)}" pitch="${percent(pitch)}" volume="${volPercent}">${escaped}</prosody>`
45
+ + '</mstts:express-as></voice></speak>';
46
+ }
47
+
48
+ /** 一帧 Edge 响应的解析:二进制帧前 2 字节是大端头长度,头里带 `Path: audio`。 */
49
+ function parseEdgeFrame(frame) {
50
+ if (typeof frame === 'string') return { kind: 'text', text: frame };
51
+ const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame);
52
+ if (bytes.byteLength < 2) return { kind: 'other' };
53
+ const headerLength = (bytes[0] << 8) | bytes[1];
54
+ const header = new TextDecoder().decode(bytes.subarray(2, 2 + headerLength));
55
+ if (!/Path:\s*audio/i.test(header)) return { kind: 'other' };
56
+ return { kind: 'audio', bytes: bytes.subarray(2 + headerLength) };
57
+ }
58
+
59
+ /**
60
+ * 默认 transport:真连 Edge(Node 22 的全局 WebSocket)。
61
+ * 返回 mp3 字节;任何异常都往上抛,由调用方回落。
62
+ */
63
+ export async function edgeTransport({ ssml, endpoint = EDGE_ENDPOINT, timeoutMs = 15000, WebSocketImpl } = {}) {
64
+ const WS = WebSocketImpl || (typeof WebSocket !== 'undefined' ? WebSocket : null);
65
+ if (typeof WS !== 'function') throw new Error('no-websocket');
66
+ return new Promise((resolve, reject) => {
67
+ const socket = new WS(endpoint);
68
+ const chunks = [];
69
+ let settled = false;
70
+ const finish = (error) => {
71
+ if (settled) return;
72
+ settled = true;
73
+ clearTimeout(timer);
74
+ try { socket.close(); } catch { /* ignore */ }
75
+ if (error) reject(error); else resolve(new Uint8Array(Buffer.concat(chunks)));
76
+ };
77
+ const timer = setTimeout(() => finish(new Error('edge-timeout')), timeoutMs);
78
+ socket.binaryType = 'arraybuffer';
79
+ socket.onerror = () => finish(new Error('edge-socket-error'));
80
+ socket.onclose = () => { if (!settled && !chunks.length) finish(new Error('edge-closed')); };
81
+ socket.onopen = () => {
82
+ const now = new Date().toUTCString();
83
+ socket.send(`X-Timestamp:${now}\r\nContent-Type:application/json; charset=utf-8\r\nPath:speech.config\r\n\r\n`
84
+ + '{"context":{"synthesis":{"audio":{"metadataoptions":{"sentenceBoundaryEnabled":"false","wordBoundaryEnabled":"false"},'
85
+ + '"outputFormat":"audio-24khz-48kbitrate-mono-mp3"}}}}');
86
+ socket.send(`X-RequestId:${Math.random().toString(16).slice(2)}\r\nContent-Type:application/ssml+xml\r\nX-Timestamp:${now}Z\r\nPath:ssml\r\n\r\n${ssml}`);
87
+ };
88
+ socket.onmessage = (event) => {
89
+ const frame = parseEdgeFrame(event.data);
90
+ if (frame.kind === 'audio') chunks.push(Buffer.from(frame.bytes));
91
+ else if (frame.kind === 'text' && /Path:\s*turn\.end/i.test(frame.text)) finish(null);
92
+ };
93
+ });
94
+ }
95
+
96
+ /**
97
+ * 合成一段。返回 `{ audio, mime, style }`;失败抛出(调用方负责回落 system)。
98
+ */
99
+ export async function synthesize({ text, emotion = 'calm', voice, rate, pitch, volume, transport, timeoutMs } = {}) {
100
+ const ssml = buildEdgeSsml({ text, emotion, voice: voice || EDGE_DEFAULT_VOICE, rate, pitch, volume });
101
+ const run = typeof transport === 'function' ? transport : edgeTransport;
102
+ const audio = await run({ ssml, timeoutMs });
103
+ if (!audio || !audio.byteLength) throw new Error('edge-empty-audio');
104
+ return { audio, mime: 'audio/mpeg', style: EDGE_STYLE_MAP[emotion] || EDGE_STYLE_MAP.calm };
105
+ }
@@ -46,7 +46,7 @@ const dayKey = (date) => {
46
46
  };
47
47
 
48
48
  export function emptyProactiveState(now = Date.now()) {
49
- return { date: dayKey(now), said: 0, lastAt: 0, skipDate: '' };
49
+ return { date: dayKey(now), said: 0, lastAt: 0, skipDate: '', usedLines: [] };
50
50
  }
51
51
 
52
52
  export function readProactiveState(now = Date.now()) {
@@ -60,8 +60,10 @@ export function readProactiveState(now = Date.now()) {
60
60
  said: Number(doc.said) || 0,
61
61
  lastAt: Number(doc.lastAt) || 0,
62
62
  skipDate: typeof doc.skipDate === 'string' ? doc.skipDate : '',
63
+ // 当天已说过的句子(内容去重用;跨天自动清空)
64
+ usedLines: Array.isArray(doc.usedLines) ? doc.usedLines.filter((x) => typeof x === 'string').slice(-20) : [],
63
65
  };
64
- // 跨天自动归零(不看昨天说了几条)
66
+ // 跨天自动归零(不看昨天说了几条、也不看昨天说过什么)
65
67
  if (state.date !== base.date) return { ...base, skipDate: state.skipDate };
66
68
  return state;
67
69
  } catch {
@@ -136,10 +138,81 @@ export function canSpeak(input) {
136
138
  return { ok: true, reason: 'ok' };
137
139
  }
138
140
 
139
- /** 记一条"说了"(同一天累加;跨天自动归零)。 */
140
- export function markSaid(now = Date.now()) {
141
+ /** 记一条"说了"(同一天累加;跨天自动归零)。`line` 会进当日去重表。 */
142
+ export function markSaid(now = Date.now(), line = '') {
141
143
  const state = readProactiveState(now);
142
- return writeProactiveState({ ...state, said: state.said + 1, lastAt: now });
144
+ const usedLines = typeof line === 'string' && line.trim()
145
+ ? [...state.usedLines, line.trim()].slice(-20)
146
+ : state.usedLines;
147
+ return writeProactiveState({ ...state, said: state.said + 1, lastAt: now, usedLines });
148
+ }
149
+
150
+ /* ── 阶段 4:主动闲聊的**内容生成**(不再用随机废话模板)────────────────── */
151
+
152
+ /** 时段:late(深夜)/morning/noon/afternoon/evening。 */
153
+ export function timeSlot(now = Date.now()) {
154
+ const hour = new Date(now).getHours();
155
+ if (hour < 5) return 'late';
156
+ if (hour < 11) return 'morning';
157
+ if (hour < 14) return 'noon';
158
+ if (hour < 18) return 'afternoon';
159
+ if (hour < 23) return 'evening';
160
+ return 'late';
161
+ }
162
+
163
+ const SLOT_TIPS = Object.freeze({
164
+ late: '这么晚还在,早点睡。',
165
+ morning: '早上好,今天想从哪张壁纸开始?',
166
+ noon: '中午了,歇一会儿看看桌面?',
167
+ afternoon: '下午容易犯困,换张亮一点的?',
168
+ evening: '晚上了,要不要换个安静的壁纸?',
169
+ });
170
+
171
+ /** 时段短词(拼进带壁纸的句子,避免整句过长)。 */
172
+ const SLOT_WORD = Object.freeze({
173
+ late: '夜深了',
174
+ morning: '早上好',
175
+ noon: '中午了',
176
+ afternoon: '下午了',
177
+ evening: '晚上了',
178
+ });
179
+
180
+ /**
181
+ * 生成一条主动闲聊。**必须**带上下文要素(时间 / 当前壁纸 / 记忆偏好 / 最近话题),
182
+ * ≤40 字;同一句话当天不重复(调用方把 `usedLines` 传进来)。
183
+ *
184
+ * 返回 `{ line, slot, source }`,`source` 说明这条是靠什么要素生成的(判据要看)。
185
+ */
186
+ export function buildProactiveLine(input = {}) {
187
+ const now = input.now || Date.now();
188
+ const slot = timeSlot(now);
189
+ const wallpaper = String(input.wallpaperTitle || '').trim().slice(0, 20);
190
+ const topic = String(input.recentTopic || '').trim().slice(0, 16);
191
+ const memory = input.memory || {};
192
+ const likes = Array.isArray(memory.likes) ? memory.likes.filter((x) => typeof x === 'string' && x.trim()) : [];
193
+ const like = (likes[0] || '').trim().slice(0, 12);
194
+ const used = new Set((input.usedLines || []).map((x) => String(x).trim()));
195
+
196
+ /** 候选:越靠前越"有上下文",最后一个永远是纯时间兜底。 */
197
+ const candidates = [];
198
+ if (wallpaper) {
199
+ // 句 6 个模板,全部 ≤40 字;`source` 标明靠什么要素生成的(判据要看)
200
+ candidates.push({ line: `「${wallpaper}」这张不错,${SLOT_WORD[slot]}。`, source: 'wallpaper' });
201
+ candidates.push({ line: `${SLOT_WORD[slot]},还在看「${wallpaper}」?`, source: 'wallpaper' });
202
+ }
203
+ if (like && wallpaper) candidates.push({ line: `又看${like}呢?「${wallpaper}」也不错。`, source: 'memory+wallpaper' });
204
+ if (like) candidates.push({ line: `想起你喜欢${like},最近又收了新图。`, source: 'memory' });
205
+ if (topic) candidates.push({ line: `刚聊到${topic},我还记着呢。`, source: 'topic' });
206
+ if (wallpaper) candidates.push({ line: `${SLOT_WORD[slot]},要不换个「${wallpaper}」的搭配?`, source: 'time+wallpaper' });
207
+ candidates.push({ line: SLOT_TIPS[slot], source: 'time' });
208
+
209
+ for (const candidate of candidates) {
210
+ const line = candidate.line.slice(0, 40);
211
+ if (!used.has(line)) return { line, slot, source: candidate.source };
212
+ }
213
+ // 全都说过了:加时段前缀凑一条新的(仍然 ≤40 字,且带时间要素)
214
+ const fallback = `${SLOT_WORD[slot]},${wallpaper ? `「${wallpaper}」` : '我还在'}。`.slice(0, 40);
215
+ return { line: fallback, slot, source: 'time-dedup' };
143
216
  }
144
217
 
145
218
  /** 「今天别说了」:当天不再主动。 */
@@ -89,7 +89,7 @@ export const FEATURE_ROUTE_FAMILIES = [
89
89
  file: 'lib/routes/pet-chat.js',
90
90
  register: registerPetChatRoutes,
91
91
  deps: (c) => ({
92
- disposers: c.disposers, base: c.base, log: c.log, readSettings: c.readSettings, speechToText: c.speechToText,
92
+ disposers: c.disposers, base: c.base, log: c.log, readSettings: c.readSettings, speechToText: c.speechToText, edgeTts: c.edgeTts,
93
93
  }),
94
94
  },
95
95
  {
@@ -22,15 +22,18 @@
22
22
  /** 注入契约:本族从 `c` 消费的**必需**键(门面/注册表调用点必须逐键给到)。 */
23
23
  // `speechToText`:DSH 宿主的转写服务(`ctx.speechToText`)。它可能**不存在**(用户没启用
24
24
  // 「语音输入」实验特性)—— 那种情况由路由回 `asr-not-ready`,而不是启动失败。
25
- export const DEPS = ['disposers', 'base', 'log', 'readSettings', 'speechToText'];
25
+ // `edgeTts`:在线情感朗读的合成函数(判据注入假 transport;生产为 undefined ⇒ 用默认实现)。
26
+ export const DEPS = ['disposers', 'base', 'log', 'readSettings', 'speechToText', 'edgeTts'];
26
27
 
27
28
  import {
28
29
  readMemory, writeMemory, clearMemory, parseExplicitMemory, rememberExplicit,
29
30
  mergeSummary, memoryPromptLine, MEMORY_SUMMARY_PROMPT,
30
31
  } from '../pet-chat-memory.js';
31
32
  import {
32
- canSpeak, markSaid, skipToday, todayUsage, QUIET_HOURS_DEFAULT,
33
+ canSpeak, markSaid, skipToday, todayUsage, QUIET_HOURS_DEFAULT, buildProactiveLine,
34
+ readProactiveState,
33
35
  } from '../pet-chat-proactive.js';
36
+ import { synthesize as edgeSynthesize } from '../pet-chat-edge-tts.js';
34
37
 
35
38
  /** 单次输入上限(工单:≤400 字)。 */
36
39
  const MAX_INPUT_CHARS = 400;
@@ -50,6 +53,8 @@ const ASR_MAX_BYTES = 2 * 1024 * 1024;
50
53
  const ASR_RATE_LIMIT_MS = 2000;
51
54
  /** 转写超时:模型推理可能要几秒,给 20s。 */
52
55
  const ASR_TIMEOUT_MS = 20000;
56
+ /** edge-tts 超时(在线合成,给宽一点)。 */
57
+ const EDGE_TIMEOUT_MS = 15000;
53
58
  /** DSH 语音输入 bundle 注册的本地 provider id(契约见 docs/ASR-INTEGRATION.md)。 */
54
59
  const ASR_PROVIDER_ID = 'sensevoice-local';
55
60
  /** 转写语言(本功能只做中文;要别的语种先改契约)。 */
@@ -239,7 +244,7 @@ function* decodeStreamChunk(provider, line) {
239
244
  }
240
245
 
241
246
  export function registerPetChatRoutes(webServer, c) {
242
- const { disposers, base: BASE, log, readSettings, speechToText } = c;
247
+ const { disposers, base: BASE, log, readSettings, speechToText, edgeTts } = c;
243
248
 
244
249
  /** 当前进程内的会话记忆(重启即忘;`/reset` 清空)。 */
245
250
  let memory = [];
@@ -250,6 +255,8 @@ export function registerPetChatRoutes(webServer, c) {
250
255
  const lastAt = new Map();
251
256
  /** 转写限频(1 次 / 2 秒):同一来源一张表。 */
252
257
  const asrLastAt = new Map();
258
+ /** edge-tts 失败只记一次日志(工单:不刷屏)。 */
259
+ let edgeFallbackLogged = false;
253
260
  /** 最近一次失败原因(`/state` 里回给界面)。 */
254
261
  let lastError = null;
255
262
 
@@ -281,6 +288,7 @@ export function registerPetChatRoutes(webServer, c) {
281
288
  proactiveMinGapMin: Number.isFinite(Number(raw.proactiveMinGapMin)) ? Math.max(30, Math.min(720, Number(raw.proactiveMinGapMin))) : 120,
282
289
  quietHours: typeof raw.quietHours === 'string' && /^\d{2}:\d{2}-\d{2}:\d{2}$/.test(raw.quietHours) ? raw.quietHours : '22:00-08:00',
283
290
  voiceEnabled: raw.voiceEnabled === true,
291
+ voiceEngine: raw.voiceEngine === 'edge' ? 'edge' : 'system',
284
292
  voiceOut: raw.voiceOut && typeof raw.voiceOut === 'object' ? { enabled: raw.voiceOut.enabled !== false, rate: Number(raw.voiceOut.rate) || 1, pitch: Number(raw.voiceOut.pitch) || 0, volume: Number(raw.voiceOut.volume) || 1, voiceURI: String(raw.voiceOut.voiceURI || '') } : { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' },
285
293
  };
286
294
  }
@@ -523,17 +531,19 @@ export function registerPetChatRoutes(webServer, c) {
523
531
  }
524
532
  }
525
533
 
526
- /** C3:主动说话的内容(≤40 字;基于时间 + 记忆里的偏好,不做随机废话)。 */
527
- function proactiveLine(now) {
528
- const mem = readMemory();
529
- const hour = new Date(now).getHours();
530
- const like = Array.isArray(mem.likes) && mem.likes.length ? mem.likes[0] : '';
531
- const lines = hour >= 23 || hour < 6
532
- ? ['夜深了,早点休息。', '我先趴一会儿,晚安。']
533
- : (like
534
- ? [`今天还在看${like}相关的壁纸吗?`, `要不要换一张${like}的?`]
535
- : ['桌面看累了吧,换一张?', '要不要试试轮播?', '我在这儿,陪你待会儿。']);
536
- return lines[Math.floor(Math.random() * lines.length)].slice(0, 40);
534
+ /**
535
+ * 阶段 4:主动说话的内容。
536
+ * 要素优先级:当前壁纸 → 记忆偏好 → 最近话题 → 时段;≤40 字,当日不重复。
537
+ */
538
+ function proactiveLine(now, context = {}) {
539
+ const state = readProactiveState(now);
540
+ return buildProactiveLine({
541
+ now,
542
+ wallpaperTitle: context.wallpaperTitle,
543
+ recentTopic: context.recentTopic,
544
+ memory: readMemory(),
545
+ usedLines: state.usedLines,
546
+ });
537
547
  }
538
548
 
539
549
  /** C2:客户端问"现在能主动说话吗"。五条件全过才 ok,且 ok 时立刻记一条。 */
@@ -552,12 +562,15 @@ export function registerPetChatRoutes(webServer, c) {
552
562
  randomHit: body.randomHit !== false,
553
563
  });
554
564
  let line = null;
565
+ let lineSource = null;
555
566
  if (decision.ok) {
556
- markSaid();
557
- line = proactiveLine(Date.now());
567
+ const built = proactiveLine(Date.now(), { wallpaperTitle: body.wallpaperTitle, recentTopic: body.recentTopic });
568
+ markSaid(Date.now(), built.line);
569
+ line = built.line;
570
+ lineSource = built.source;
558
571
  }
559
572
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
560
- res.end(JSON.stringify({ ok: decision.ok, reason: decision.reason, line, usage: todayUsage(Date.now(), config.proactiveDailyLimit) }));
573
+ res.end(JSON.stringify({ ok: decision.ok, reason: decision.reason, line, source: lineSource, usage: todayUsage(Date.now(), config.proactiveDailyLimit) }));
561
574
  }
562
575
 
563
576
  function handleReset2(res) {
@@ -683,6 +696,66 @@ export function registerPetChatRoutes(webServer, c) {
683
696
  }
684
697
  }
685
698
 
699
+ /** Uint8Array → base64(Node 与 Worker 都能用)。 */
700
+ function toBase64(bytes) {
701
+ if (!bytes || !bytes.byteLength) return '';
702
+ if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64');
703
+ let binary = '';
704
+ for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
705
+ return btoa(binary);
706
+ }
707
+
708
+ /**
709
+ * POST /pet-chat/speak —— **朗读**.的宿主侧。
710
+ *
711
+ * 两档引擎(工单阶段 2):
712
+ * · `system`(默认):**不发任何网络请求**,只回 `{engine:'system'}`,客户端用系统音色读;
713
+ * · `edge`:宿主去连微软的在线朗读,拿回 mp3 字节(base64)交给客户端播;
714
+ * 失败(网络/接口变更/超时)⇒ **回落 system**,日志只记一次,不弹窗。
715
+ * 关闭朗读(`voiceOut.enabled=false`)⇒ 两档都不触发。
716
+ */
717
+ async function handleSpeak(req, res) {
718
+ const send = (payload, status = 200) => {
719
+ res.statusCode = status;
720
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
721
+ res.end(JSON.stringify(payload));
722
+ };
723
+ let body = {};
724
+ try { body = await readJsonBody(req); } catch { send({ ok: false, code: 'bad-request', hint: '请求体不是合法 JSON' }, 400); return; }
725
+ const text = String(body.text || '').trim();
726
+ const emotionRaw = String(body.emotion || 'calm');
727
+ const emotion = ['happy', 'tired', 'angry', 'calm'].includes(emotionRaw) ? emotionRaw : 'calm';
728
+ if (!text) { send({ ok: false, code: 'bad-request', hint: '文本为空' }, 400); return; }
729
+ if (text.length > 400) { send({ ok: false, code: 'bad-request', hint: '一次最多 400 字' }, 400); return; }
730
+
731
+ const config = readPetChat();
732
+ const voiceOut = config.voiceOut && typeof config.voiceOut === 'object' ? config.voiceOut : {};
733
+ // ⑤ 关闭朗读:两档都不触发(也不发网络)
734
+ if (voiceOut.enabled !== true) { send({ ok: false, code: 'voice-out-disabled', hint: '朗读已关闭' }); return; }
735
+ // ① engine=system:不请求网络,直接让客户端用系统音色
736
+ if (config.voiceEngine !== 'edge') { send({ ok: true, engine: 'system', style: null }); return; }
737
+
738
+ try {
739
+ const synth = typeof edgeTts === 'function' ? edgeTts : edgeSynthesize;
740
+ const result = await synth({
741
+ text,
742
+ emotion,
743
+ rate: voiceOut.rate,
744
+ pitch: voiceOut.pitch,
745
+ volume: voiceOut.volume,
746
+ timeoutMs: EDGE_TIMEOUT_MS,
747
+ });
748
+ send({ ok: true, engine: 'edge', mime: result.mime || 'audio/mpeg', style: result.style || null, audio: toBase64(result.audio) });
749
+ } catch (error) {
750
+ // ③ 失败回落 system;日志**只记一次**(不刷屏、不弹窗)
751
+ if (!edgeFallbackLogged) {
752
+ edgeFallbackLogged = true;
753
+ log('[pet-chat] edge-tts 失败,回落系统语音:' + String((error && error.message) || error));
754
+ }
755
+ send({ ok: true, engine: 'system', fallback: 'edge-failed', style: null });
756
+ }
757
+ }
758
+
686
759
  function handleReset(res) {
687
760
  clearMemory();
688
761
  memory = [];
@@ -703,6 +776,7 @@ export function registerPetChatRoutes(webServer, c) {
703
776
  if (tail === '/chat' && method === 'POST') { handleChat(req, res); return; }
704
777
  if (tail === '/reset' && method === 'POST') { handleReset(res); return; }
705
778
  if (tail === '/transcribe' && method === 'POST') { handleTranscribe(req, res); return; }
779
+ if (tail === '/speak' && method === 'POST') { handleSpeak(req, res); return; }
706
780
  if (tail === '/proactive' && (method === 'GET' || method === 'HEAD')) {
707
781
  const config = readPetChat();
708
782
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
@@ -344,6 +344,8 @@ export function registerPetsRoutes(webServer, c) {
344
344
  id: String((it && (it.slug || it.id)) || ''),
345
345
  title: String((it && it.title) || ''),
346
346
  bytes: Number(it && it.bytes) || null,
347
+ // 4.26:站点 DTO 现在给 sha256(门 1 起);有就传给下载队列按 sha 校验。
348
+ sha256: typeof (it && it.sha256) === 'string' ? it.sha256 : '',
347
349
  url: abs,
348
350
  cover: thumb && /\.(jpg|jpeg|png|webp|gif|avif)(\?|#|$)/i.test(thumb)
349
351
  ? (/^https?:/i.test(thumb) ? thumb : base + thumb) : null,
@@ -597,6 +599,32 @@ export function registerPetsRoutes(webServer, c) {
597
599
  return;
598
600
  }
599
601
 
602
+ /**
603
+ * **sha256 校验**(阶段 3):站点给了 sha 就必须对得上。
604
+ *
605
+ * 为什么要在校验失败时连目录一起删:安装是「先下载、再解压、后落盘」,
606
+ * 但只要上一次中途失败留下半个目录,`/pets/list` 就可能把它当成一只坏宠物。
607
+ * 这里统一 `cleanupPartial()`:删半成品目录 + 删缓存 zip,保证失败后磁盘干净。
608
+ */
609
+ const cleanupPartial = () => {
610
+ try { rmSync(join(dataRoot(), id), { recursive: true, force: true }); } catch { /* ignore */ }
611
+ try { rmSync(zipDest, { force: true }); } catch { /* ignore */ }
612
+ };
613
+ if (item.sha256) {
614
+ const digest = createHash('sha256').update(buf).digest('hex');
615
+ if (digest !== item.sha256) {
616
+ cleanupPartial();
617
+ failInstall('sha-mismatch', 'expected=' + item.sha256.slice(0, 12) + ' actual=' + digest.slice(0, 12));
618
+ sendJson(res, 422, {
619
+ ok: false,
620
+ error: 'sha-mismatch',
621
+ expected: item.sha256,
622
+ actual: digest,
623
+ });
624
+ return;
625
+ }
626
+ }
627
+
600
628
  let entries;
601
629
  try { entries = unzip(buf); } catch (e) {
602
630
  failInstall('bad-zip', String((e && e.message) || e));
@@ -604,12 +632,12 @@ export function registerPetsRoutes(webServer, c) {
604
632
  return;
605
633
  }
606
634
  const manifestRaw = entries.get('pet.json');
607
- if (!manifestRaw) { failInstall('no-manifest'); sendJson(res, 422, { ok: false, error: 'no-manifest' }); return; }
635
+ if (!manifestRaw) { cleanupPartial(); failInstall('no-manifest'); sendJson(res, 422, { ok: false, error: 'no-manifest' }); return; }
608
636
  let manifest;
609
637
  try { manifest = JSON.parse(manifestRaw.toString('utf8')); } catch { failInstall('bad-manifest'); sendJson(res, 422, { ok: false, error: 'bad-manifest' }); return; }
610
638
  const sheetName = basename((manifest.sprite2d && manifest.sprite2d.spritesheetPath) || 'spritesheet.webp');
611
639
  const sheet = entries.get(sheetName);
612
- if (!sheet) { failInstall('no-spritesheet', sheetName); sendJson(res, 422, { ok: false, error: 'no-spritesheet', detail: sheetName }); return; }
640
+ if (!sheet) { cleanupPartial(); failInstall('no-spritesheet', sheetName); sendJson(res, 422, { ok: false, error: 'no-spritesheet', detail: sheetName }); return; }
613
641
 
614
642
  const dir = join(dataRoot(), id);
615
643
  try {
@@ -1013,6 +1013,8 @@ const DEFAULTS = {
1013
1013
  // enabled 与"宠物音效"完全无关(音效开关不影响朗读,反之亦然)。
1014
1014
  // voiceURI 空 = 自动挑中文音色(zh / Chinese / Huihui / Xiaoxiao …)。
1015
1015
  voiceOut: { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' },
1016
+ // 朗读引擎:system = 系统音色(默认、离线);edge = 在线情感朗读(文本经微软,需联网)
1017
+ voiceEngine: 'system',
1016
1018
  },
1017
1019
  };
1018
1020
 
@@ -1794,6 +1796,7 @@ function readPetChat(raw) {
1794
1796
  ? src.quietHours : def.quietHours,
1795
1797
  voiceEnabled: src.voiceEnabled === true,
1796
1798
  voiceOut: readVoiceOut(src.voiceOut),
1799
+ voiceEngine: src.voiceEngine === 'edge' ? 'edge' : 'system',
1797
1800
  };
1798
1801
  }
1799
1802
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-folia",
3
- "version": "4.26.0-pre.2",
3
+ "version": "4.26.0-pre.3",
4
4
  "description": "DSH 壁纸引擎:本机 WE 壁纸实时渲染,视频/网页/开机动画/桌宠皮肤,一键拉取在线素材。",
5
5
  "type": "module",
6
6
  "engines": {
@@ -45,6 +45,7 @@
45
45
  "lib/client.js",
46
46
  "lib/pet-chat-memory.js",
47
47
  "lib/pet-chat-proactive.js",
48
+ "lib/pet-chat-edge-tts.js",
48
49
  "lib/routes/pet-chat.js",
49
50
  "lib/download-queue.js",
50
51
  "lib/host-boot.js",