dsh-folia 4.26.0-pre.1 → 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
@@ -8097,6 +8097,12 @@ window.__ModuleLoader__.load({
8097
8097
  // ── 语音输入(默认关):真正干活的转写由 DSH 宿主的 speechToText 服务承担,
8098
8098
  // 模型由那个 provider 自己下载/校验 —— 插件这边只负责录音与回填。
8099
8099
  voiceEnabled: false,
8100
+ // ── 朗读回答(TTS):**默认开**;走系统 speechSynthesis,零依赖零 token。
8101
+ // enabled 与"宠物音效"完全无关(音效开关不影响朗读,反之亦然)。
8102
+ // voiceURI 空 = 自动挑中文音色(zh / Chinese / Huihui / Xiaoxiao …)。
8103
+ voiceOut: { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' },
8104
+ // 朗读引擎:system = 系统音色(默认、离线);edge = 在线情感朗读(文本经微软,需联网)
8105
+ voiceEngine: 'system',
8100
8106
  },
8101
8107
  };
8102
8108
 
@@ -8814,6 +8820,10 @@ window.__ModuleLoader__.load({
8814
8820
  const PET_CHAT_PERSONA_MAX = 200;
8815
8821
 
8816
8822
  const petChatStr = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
8823
+ const petChatFloat = (v, lo, hi, fallback) => {
8824
+ const n = Number(v);
8825
+ return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : fallback;
8826
+ };
8817
8827
  const petChatInt = (v, lo, hi, fallback) => {
8818
8828
  const n = Number(v);
8819
8829
  return Number.isFinite(n) ? Math.min(hi, Math.max(lo, Math.round(n))) : fallback;
@@ -8827,6 +8837,25 @@ window.__ModuleLoader__.load({
8827
8837
  * 主机名拼错的 URL 与其"修好",不如让用户重新填一次。
8828
8838
  * `apiKey` 原样保留(只在本机 profile 里),但**限长**,避免设置文件被灌爆。
8829
8839
  */
8840
+ /**
8841
+ * 朗读设置(TTS)的消毒。
8842
+ *
8843
+ * `enabled` 默认 **true**(工单要求默认开),所以判据是 `!== false` 而不是 `=== true` ——
8844
+ * 老档里没有这个键的人也会直接得到"开"。
8845
+ * rate/pitch/volume 走 clamp;voiceURI 只做长度限制(音色由运行时按 URI/中文名挑)。
8846
+ */
8847
+ function readVoiceOut(raw) {
8848
+ const def = DEFAULTS.petChat.voiceOut;
8849
+ const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
8850
+ return {
8851
+ enabled: src.enabled !== false,
8852
+ rate: petChatFloat(src.rate, 0.5, 2, def.rate),
8853
+ pitch: petChatFloat(src.pitch, 0, 2, def.pitch),
8854
+ volume: petChatFloat(src.volume, 0, 1, def.volume),
8855
+ voiceURI: petChatStr(src.voiceURI, 200).trim(),
8856
+ };
8857
+ }
8858
+
8830
8859
  function readPetChat(raw) {
8831
8860
  const def = DEFAULTS.petChat;
8832
8861
  const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
@@ -8854,6 +8883,8 @@ window.__ModuleLoader__.load({
8854
8883
  quietHours: (typeof src.quietHours === 'string' && /^\d{2}:\d{2}-\d{2}:\d{2}$/.test(src.quietHours))
8855
8884
  ? src.quietHours : def.quietHours,
8856
8885
  voiceEnabled: src.voiceEnabled === true,
8886
+ voiceOut: readVoiceOut(src.voiceOut),
8887
+ voiceEngine: src.voiceEngine === 'edge' ? 'edge' : 'system',
8857
8888
  };
8858
8889
  }
8859
8890
 
@@ -20255,6 +20286,185 @@ window.__ModuleLoader__.load({
20255
20286
  } catch { return () => {}; }
20256
20287
  }
20257
20288
 
20289
+ // ── 内联模块:src/pet-chat-tts.js —— 朗读回答:speechSynthesis 薄封装(整段读 / 流式按句读 / 取消),不碰 DOM、不改文字(构建期注入;勿手改本段)──
20290
+ /**
20291
+ * pet-chat-tts.js — **朗读回答**(浏览器 / Electron 内置 speechSynthesis 的薄封装)。
20292
+ *
20293
+ * 三条铁律(来自工单):
20294
+ * ① **文字照常显示**:本模块只调 `speechSynthesis`,**不碰 DOM、不改文本** ——
20295
+ * 朗读是叠加,不是替换(气泡 + 打字机该显示什么还显示什么)。
20296
+ * ② **零依赖零 token**:走系统语音(Electron 下是 Windows SAPI);没有就说没有。
20297
+ * ③ 与宠物"音效"开关**无关**:这里只看 `petChat.voiceOut.enabled`。
20298
+ *
20299
+ * 朗读节奏:
20300
+ * · 整段到达(非流式 / 预设台词)⇒ `finish(text)` 整段读一次;
20301
+ * · 流式增量 ⇒ `push(chunk)`,凑满句末标点就按句读(不打断打字机)。
20302
+ *
20303
+ * 为什么要做成工厂并把 speechSynthesis / Utterance 注入进来:
20304
+ * 判据要能 mock(`test/verify-pet-chat.mjs` 的 6 条),而渲染进程的真实实现
20305
+ * 就是 `window.speechSynthesis` + `window.SpeechSynthesisUtterance`。
20306
+ */
20307
+
20308
+ /** 句末标点(中英混排;省略号也算一句的结尾)。 */
20309
+ const PET_CHAT_TTS_SENTENCE_END = /[。!?!?;;…]+/;
20310
+
20311
+ /**
20312
+ * 按句末标点切句(保留标点)。
20313
+ * 单句过长(>120 字)时按逗号再切一次,避免一口气念 300 字。
20314
+ */
20315
+ function petChatTtsSplit(text) {
20316
+ const raw = String(text ?? '');
20317
+ if (!raw.trim()) return [];
20318
+ const out = [];
20319
+ let buffer = '';
20320
+ for (const char of raw) {
20321
+ buffer += char;
20322
+ if (PET_CHAT_TTS_SENTENCE_END.test(char)) {
20323
+ if (buffer.trim()) out.push(buffer.trim());
20324
+ buffer = '';
20325
+ }
20326
+ }
20327
+ if (buffer.trim()) out.push(buffer.trim());
20328
+ // 保险:单句 >120 字再按逗号切
20329
+ const final = [];
20330
+ for (const sentence of out) {
20331
+ if (sentence.length <= 120) { final.push(sentence); continue; }
20332
+ let piece = '';
20333
+ for (const char of sentence) {
20334
+ piece += char;
20335
+ if (char === ',' || char === ',' ) { final.push(piece); piece = ''; }
20336
+ }
20337
+ if (piece.trim()) final.push(piece);
20338
+ }
20339
+ return final;
20340
+ }
20341
+
20342
+ /** 中文音色识别:`zh-*`、名字里带 Chinese / Huihui / Xiaoxiao。 */
20343
+ function petChatTtsIsChinese(voice) {
20344
+ if (!voice) return false;
20345
+ const lang = String(voice.lang || '').toLowerCase();
20346
+ const name = String(voice.name || '');
20347
+ return lang.startsWith('zh') || /chinese|huihui|xiaoxiao|kangkang|yaoyao|tingting|hanhan/i.test(name);
20348
+ }
20349
+
20350
+ /**
20351
+ * 造一个朗读引擎。
20352
+ *
20353
+ * @param {object} deps
20354
+ * @param {() => any} deps.getSpeech 返回 speechSynthesis(可能不存在)
20355
+ * @param {() => any[]} deps.getVoices 返回音色列表(可能为空)
20356
+ * @param {() => object} deps.getConfig 返回 `{ enabled, rate, pitch, volume, voiceURI }`
20357
+ * @param {Function} [deps.Utterance] `SpeechSynthesisUtterance` 构造器
20358
+ * @param {(code:string, message:string) => void} [deps.onHint] 一次性提示回调
20359
+ */
20360
+ function petChatTtsCreate(deps) {
20361
+ const options = deps || {};
20362
+ const getSpeech = typeof options.getSpeech === 'function' ? options.getSpeech : () => null;
20363
+ const getVoices = typeof options.getVoices === 'function' ? options.getVoices : () => [];
20364
+ const getConfig = typeof options.getConfig === 'function' ? options.getConfig : () => ({ enabled: false });
20365
+ const onHint = typeof options.onHint === 'function' ? options.onHint : () => {};
20366
+ const Utterance = options.Utterance;
20367
+
20368
+ let pending = ''; // 流式未成句的尾巴
20369
+ let spokenInTurn = 0; // 本回合已经读了几段(决定 finish 要不要整段读)
20370
+ let hintShown = {}; // 一次性提示去重(按 code)
20371
+
20372
+ const hintOnce = (code, message) => {
20373
+ if (hintShown[code]) return;
20374
+ hintShown[code] = true;
20375
+ onHint(code, message);
20376
+ };
20377
+
20378
+ /** 选音色:voiceURI 优先,其次第一个中文音色;都没有返回 null(并提示一次)。 */
20379
+ function pickVoice(config, voices) {
20380
+ const list = Array.isArray(voices) ? voices : [];
20381
+ const wanted = String(config.voiceURI || '').trim();
20382
+ if (wanted) {
20383
+ const hit = list.find((voice) => voice && (voice.voiceURI === wanted || voice.name === wanted));
20384
+ if (hit) return hit;
20385
+ }
20386
+ const chinese = list.find((voice) => petChatTtsIsChinese(voice));
20387
+ if (chinese) return chinese;
20388
+ if (list.length) hintOnce('no-chinese-voice', '系统里没有中文音色,朗读可能不自然');
20389
+ return null;
20390
+ }
20391
+
20392
+ /** 读一段(内部):config 关了就什么都不做。 */
20393
+ function speakOne(text, speech, config, voices) {
20394
+ const trimmed = String(text ?? '').trim();
20395
+ if (!trimmed) return false;
20396
+ if (typeof Utterance !== 'function') return false;
20397
+ const utterance = new Utterance(trimmed);
20398
+ utterance.rate = Number.isFinite(Number(config.rate)) ? Number(config.rate) : 1;
20399
+ utterance.pitch = Number.isFinite(Number(config.pitch)) ? Number(config.pitch) : 1;
20400
+ utterance.volume = Number.isFinite(Number(config.volume)) ? Number(config.volume) : 1;
20401
+ const voice = pickVoice(config, voices);
20402
+ if (voice) utterance.voice = voice;
20403
+ speech.speak(utterance);
20404
+ if (!hintShown['first-speak']) {
20405
+ hintShown['first-speak'] = true;
20406
+ hintOnce('first-speak', '使用系统语音,无需下载 / 不耗 token');
20407
+ }
20408
+ return true;
20409
+ }
20410
+
20411
+ /** 新回合开始:停掉上一段朗读,清空缓冲。 */
20412
+ function start() {
20413
+ pending = '';
20414
+ spokenInTurn = 0;
20415
+ cancel();
20416
+ }
20417
+
20418
+ /** 取消朗读(关闭气泡 / 点停止 / 新消息)。 */
20419
+ function cancel() {
20420
+ const speech = getSpeech();
20421
+ if (speech && typeof speech.cancel === 'function') speech.cancel();
20422
+ }
20423
+
20424
+ /** 流式增量:凑满整句就先读(保证"边出字边读",但不打断打字机)。 */
20425
+ function push(chunk) {
20426
+ const config = getConfig() || {};
20427
+ if (config.enabled !== true) return;
20428
+ const speech = getSpeech();
20429
+ if (!speech || typeof speech.speak !== 'function') return; // ⑤ 没有 speechSynthesis ⇒ 静默跳过
20430
+ const text = String(chunk ?? '');
20431
+ if (!text) return;
20432
+ pending += text;
20433
+ const sentences = petChatTtsSplit(pending);
20434
+ // 只有"以标点结尾"的才算成句;最后一段若不以标点结尾,留到下次
20435
+ const endsWithPunct = PET_CHAT_TTS_SENTENCE_END.test(pending.slice(-1));
20436
+ const ready = endsWithPunct ? sentences : sentences.slice(0, -1);
20437
+ if (!ready.length) return;
20438
+ if (endsWithPunct) pending = '';
20439
+ else pending = sentences[sentences.length - 1] || '';
20440
+ const voices = getVoices();
20441
+ for (const sentence of ready) if (speakOne(sentence, speech, config, voices)) spokenInTurn += 1;
20442
+ }
20443
+
20444
+ /**
20445
+ * 回复结束:整段朗读。
20446
+ * 已经边流边读过句子的,这里只读剩下的尾巴;从没读过 ⇒ 整段读一次(判据①)。
20447
+ */
20448
+ function finish(fullText) {
20449
+ const config = getConfig() || {};
20450
+ if (config.enabled !== true) return;
20451
+ const speech = getSpeech();
20452
+ if (!speech || typeof speech.speak !== 'function') return;
20453
+ const whole = String(fullText ?? '');
20454
+ const tail = pending;
20455
+ pending = '';
20456
+ const voices = getVoices();
20457
+ if (spokenInTurn === 0) {
20458
+ // 整段一次读完(气泡里显示的还是同一段文字,这里只是读它)
20459
+ if (whole.trim()) speakOne(whole.trim(), speech, config, voices);
20460
+ return;
20461
+ }
20462
+ if (tail.trim()) speakOne(tail.trim(), speech, config, voices);
20463
+ }
20464
+
20465
+ return { start, push, finish, cancel, split: petChatTtsSplit };
20466
+ }
20467
+
20258
20468
  // ── 内联模块:src/pet-chat.js —— 桌宠对话气泡:点宠物出输入框,走宿主 /folia/pet-chat/* 的 SSE;没配模型时给预设台词(构建期注入;勿手改本段)──
20259
20469
  /**
20260
20470
  * pet-chat.js(客户端)— **桌宠对话气泡**(门 2 / 任务 A3)。
@@ -20349,6 +20559,12 @@ window.__ModuleLoader__.load({
20349
20559
  petChatOn(voiceBtn, 'pointerdown', (event) => { if (event && event.preventDefault) event.preventDefault(); void petChatVoiceStart(); });
20350
20560
  petChatOn(voiceBtn, 'pointerup', () => { void petChatVoiceStop(); });
20351
20561
  petChatOn(voiceBtn, 'pointerleave', () => { if (petChatVoice) void petChatVoiceStop(); });
20562
+ // 停止朗读:只停语音,不动文字(文字已经显示在气泡里)
20563
+ const stopBtn = document.createElement('button');
20564
+ stopBtn.type = 'button';
20565
+ stopBtn.textContent = weT('停止朗读');
20566
+ stopBtn.style.cssText = 'background:none;border:1px solid rgba(255,255,255,.14);border-radius:7px;color:#c9c9d1;font-size:11px;padding:2px 6px;cursor:pointer';
20567
+ petChatOn(stopBtn, 'click', () => petChatTts.cancel());
20352
20568
  const memoryBtn = document.createElement('button');
20353
20569
  memoryBtn.type = 'button';
20354
20570
  memoryBtn.textContent = weT('查看记忆');
@@ -20365,7 +20581,7 @@ window.__ModuleLoader__.load({
20365
20581
  close.title = weT('关闭');
20366
20582
  close.style.cssText = 'background:none;border:0;color:#c9c9d1;font-size:18px;cursor:pointer;line-height:1';
20367
20583
  petChatOn(close, 'click', () => petChatHide());
20368
- petChatAppend(tools, voiceBtn, memoryBtn, clear, close);
20584
+ petChatAppend(tools, voiceBtn, stopBtn, memoryBtn, clear, close);
20369
20585
  petChatAppend(head, title, tools);
20370
20586
 
20371
20587
  const log = document.createElement('div');
@@ -20451,6 +20667,8 @@ window.__ModuleLoader__.load({
20451
20667
 
20452
20668
  function petChatHide() {
20453
20669
  if (!petChatEls) return;
20670
+ petChatTts.cancel(); // 关闭气泡:立刻停读
20671
+ if (petChatAudioPlayer) { try { petChatAudioPlayer.pause(); } catch { /* ignore */ } petChatAudioPlayer = null; }
20454
20672
  petChatEls.root.style.display = 'none';
20455
20673
  }
20456
20674
 
@@ -20489,6 +20707,7 @@ window.__ModuleLoader__.load({
20489
20707
  const doc = probe && probe.data;
20490
20708
  // 语音输入开关由宿主带回来:false ⇒ 按麦克风只提示"先去 DSH 开",不弹权限框
20491
20709
  petChatVoiceEnabled = doc && doc.voiceEnabled === true;
20710
+ if (doc && doc.voiceOut && typeof doc.voiceOut === 'object') petChatVoiceOut = doc.voiceOut;
20492
20711
  if (!doc || doc.enabled !== true) {
20493
20712
  petChatStatus(weT('未开启对话(设置 → 桌宠 → 桌宠对话)'));
20494
20713
  return null;
@@ -20537,13 +20756,16 @@ window.__ModuleLoader__.load({
20537
20756
  if ([...text].length > 400) { petChatStatus(weT('一次最多 400 字')); return; }
20538
20757
  els.input.value = '';
20539
20758
  petChatPush('user', text);
20759
+ petChatTts.start(); // 新消息:停掉上一段朗读
20540
20760
  petChatBusy = true;
20541
20761
  petChatStatus(weT('思考中…'));
20542
20762
 
20543
20763
  const state = await petChatSyncState();
20544
20764
  if (!state || state.enabled !== true) {
20545
20765
  // 没有模型:不假装在对话,直接给预设台词
20546
- petChatPush('assistant', petChatPresetLine());
20766
+ const presetLine = petChatPresetLine();
20767
+ petChatPush('assistant', presetLine);
20768
+ void petChatSpeak(presetLine, 'calm');
20547
20769
  petChatStatus(weT('未开启对话(设置 → 桌宠 → 桌宠对话)'));
20548
20770
  petChatBusy = false;
20549
20771
  return;
@@ -20582,9 +20804,11 @@ window.__ModuleLoader__.load({
20582
20804
  if (parsed.event === 'delta' && parsed.data && typeof parsed.data.t === 'string') {
20583
20805
  assistant += parsed.data.t;
20584
20806
  ensureBubble();
20807
+ petChatTts.push(parsed.data.t);
20585
20808
  petChatLines[petChatLines.length - 1] = { role: 'assistant', text: assistant };
20586
20809
  petChatRender();
20587
20810
  } else if (parsed.event === 'done') {
20811
+ void petChatSpeak(assistant, parsed.data && parsed.data.emotion);
20588
20812
  petChatApplyEmotion(parsed.data && parsed.data.emotion);
20589
20813
  petChatStatus('');
20590
20814
  } else if (parsed.event === 'error') {
@@ -20665,6 +20889,38 @@ window.__ModuleLoader__.load({
20665
20889
  const PET_CHAT_VOICE_MAX_SECONDS = 15;
20666
20890
  let petChatVoice = null;
20667
20891
  let petChatVoiceEnabled = null;
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;
20913
+ let petChatVoiceOut = { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' };
20914
+ const petChatTts = petChatTtsCreate({
20915
+ getSpeech: () => (typeof window !== 'undefined' ? window.speechSynthesis : null),
20916
+ getVoices: () => {
20917
+ const speech = typeof window !== 'undefined' ? window.speechSynthesis : null;
20918
+ return speech && typeof speech.getVoices === 'function' ? speech.getVoices() : [];
20919
+ },
20920
+ getConfig: () => petChatVoiceOut,
20921
+ Utterance: typeof window !== 'undefined' ? window.SpeechSynthesisUtterance : undefined,
20922
+ onHint: (code, message) => petChatStatus(message),
20923
+ });
20668
20924
 
20669
20925
  /** Float32 PCM → 16kHz 单声道 PCM16 WAV。 */
20670
20926
  function petChatEncodeWav(samples, sampleRate) {
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, '&amp;')
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,8 @@ 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',
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: '' },
284
293
  };
285
294
  }
286
295
 
@@ -352,6 +361,7 @@ export function registerPetChatRoutes(webServer, c) {
352
361
  lastError,
353
362
  // 语音输入:客户端据此决定麦克风按钮是"可直接录"还是"先提示去开启"
354
363
  voiceEnabled: config.voiceEnabled === true,
364
+ voiceOut: config.voiceOut,
355
365
  asrProvider: ASR_PROVIDER_ID,
356
366
  }));
357
367
  }
@@ -521,17 +531,19 @@ export function registerPetChatRoutes(webServer, c) {
521
531
  }
522
532
  }
523
533
 
524
- /** C3:主动说话的内容(≤40 字;基于时间 + 记忆里的偏好,不做随机废话)。 */
525
- function proactiveLine(now) {
526
- const mem = readMemory();
527
- const hour = new Date(now).getHours();
528
- const like = Array.isArray(mem.likes) && mem.likes.length ? mem.likes[0] : '';
529
- const lines = hour >= 23 || hour < 6
530
- ? ['夜深了,早点休息。', '我先趴一会儿,晚安。']
531
- : (like
532
- ? [`今天还在看${like}相关的壁纸吗?`, `要不要换一张${like}的?`]
533
- : ['桌面看累了吧,换一张?', '要不要试试轮播?', '我在这儿,陪你待会儿。']);
534
- 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
+ });
535
547
  }
536
548
 
537
549
  /** C2:客户端问"现在能主动说话吗"。五条件全过才 ok,且 ok 时立刻记一条。 */
@@ -550,12 +562,15 @@ export function registerPetChatRoutes(webServer, c) {
550
562
  randomHit: body.randomHit !== false,
551
563
  });
552
564
  let line = null;
565
+ let lineSource = null;
553
566
  if (decision.ok) {
554
- markSaid();
555
- 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;
556
571
  }
557
572
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
558
- 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) }));
559
574
  }
560
575
 
561
576
  function handleReset2(res) {
@@ -681,6 +696,66 @@ export function registerPetChatRoutes(webServer, c) {
681
696
  }
682
697
  }
683
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
+
684
759
  function handleReset(res) {
685
760
  clearMemory();
686
761
  memory = [];
@@ -701,6 +776,7 @@ export function registerPetChatRoutes(webServer, c) {
701
776
  if (tail === '/chat' && method === 'POST') { handleChat(req, res); return; }
702
777
  if (tail === '/reset' && method === 'POST') { handleReset(res); return; }
703
778
  if (tail === '/transcribe' && method === 'POST') { handleTranscribe(req, res); return; }
779
+ if (tail === '/speak' && method === 'POST') { handleSpeak(req, res); return; }
704
780
  if (tail === '/proactive' && (method === 'GET' || method === 'HEAD')) {
705
781
  const config = readPetChat();
706
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 {
@@ -1009,6 +1009,12 @@ const DEFAULTS = {
1009
1009
  // ── 语音输入(默认关):真正干活的转写由 DSH 宿主的 speechToText 服务承担,
1010
1010
  // 模型由那个 provider 自己下载/校验 —— 插件这边只负责录音与回填。
1011
1011
  voiceEnabled: false,
1012
+ // ── 朗读回答(TTS):**默认开**;走系统 speechSynthesis,零依赖零 token。
1013
+ // enabled 与"宠物音效"完全无关(音效开关不影响朗读,反之亦然)。
1014
+ // voiceURI 空 = 自动挑中文音色(zh / Chinese / Huihui / Xiaoxiao …)。
1015
+ voiceOut: { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' },
1016
+ // 朗读引擎:system = 系统音色(默认、离线);edge = 在线情感朗读(文本经微软,需联网)
1017
+ voiceEngine: 'system',
1012
1018
  },
1013
1019
  };
1014
1020
 
@@ -1726,6 +1732,10 @@ const PET_CHAT_MODEL_MAX = 120;
1726
1732
  const PET_CHAT_PERSONA_MAX = 200;
1727
1733
 
1728
1734
  const petChatStr = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
1735
+ const petChatFloat = (v, lo, hi, fallback) => {
1736
+ const n = Number(v);
1737
+ return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : fallback;
1738
+ };
1729
1739
  const petChatInt = (v, lo, hi, fallback) => {
1730
1740
  const n = Number(v);
1731
1741
  return Number.isFinite(n) ? Math.min(hi, Math.max(lo, Math.round(n))) : fallback;
@@ -1739,6 +1749,25 @@ const petChatInt = (v, lo, hi, fallback) => {
1739
1749
  * 主机名拼错的 URL 与其"修好",不如让用户重新填一次。
1740
1750
  * `apiKey` 原样保留(只在本机 profile 里),但**限长**,避免设置文件被灌爆。
1741
1751
  */
1752
+ /**
1753
+ * 朗读设置(TTS)的消毒。
1754
+ *
1755
+ * `enabled` 默认 **true**(工单要求默认开),所以判据是 `!== false` 而不是 `=== true` ——
1756
+ * 老档里没有这个键的人也会直接得到"开"。
1757
+ * rate/pitch/volume 走 clamp;voiceURI 只做长度限制(音色由运行时按 URI/中文名挑)。
1758
+ */
1759
+ function readVoiceOut(raw) {
1760
+ const def = DEFAULTS.petChat.voiceOut;
1761
+ const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
1762
+ return {
1763
+ enabled: src.enabled !== false,
1764
+ rate: petChatFloat(src.rate, 0.5, 2, def.rate),
1765
+ pitch: petChatFloat(src.pitch, 0, 2, def.pitch),
1766
+ volume: petChatFloat(src.volume, 0, 1, def.volume),
1767
+ voiceURI: petChatStr(src.voiceURI, 200).trim(),
1768
+ };
1769
+ }
1770
+
1742
1771
  function readPetChat(raw) {
1743
1772
  const def = DEFAULTS.petChat;
1744
1773
  const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
@@ -1766,6 +1795,8 @@ function readPetChat(raw) {
1766
1795
  quietHours: (typeof src.quietHours === 'string' && /^\d{2}:\d{2}-\d{2}:\d{2}$/.test(src.quietHours))
1767
1796
  ? src.quietHours : def.quietHours,
1768
1797
  voiceEnabled: src.voiceEnabled === true,
1798
+ voiceOut: readVoiceOut(src.voiceOut),
1799
+ voiceEngine: src.voiceEngine === 'edge' ? 'edge' : 'system',
1769
1800
  };
1770
1801
  }
1771
1802
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-folia",
3
- "version": "4.26.0-pre.1",
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",