dsh-voice-mode 0.7.39 → 0.7.40

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/index.js CHANGED
@@ -1,11 +1,56 @@
1
1
  // src/index.ts
2
- import z from "@deepseek-ai/schemastery";
2
+ import z2 from "@deepseek-ai/schemastery";
3
3
  import { dirname as dirname2, join as join5 } from "node:path";
4
4
  import { homedir as homedir2 } from "node:os";
5
5
  import { rm } from "node:fs/promises";
6
6
 
7
7
  // src/asr-host.ts
8
8
  import { statSync } from "node:fs";
9
+
10
+ // src/redact.ts
11
+ var PREFIXED = [
12
+ { re: /\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi, to: "$1<redacted>" },
13
+ { re: /\b(Basic\s+)[A-Za-z0-9+/=-]{8,}/gi, to: "$1<redacted>" },
14
+ { re: /\b((?:api[-_]?key|x-api-key)\s*[:=]\s*)[A-Za-z0-9._~+/=-]{8,}/gi, to: "$1<redacted>" },
15
+ // URL 内嵌凭据(https://user:pass@host)与查询参数密钥(?api_key=... / &token=... / &key=...)
16
+ { re: /(https?:\/\/)([^:@/\s]+:[^@/\s]+)(@)/gi, to: "$1<redacted>$3" },
17
+ { re: /([?&](?:api[_-]?key|access_token|token|key)=)([^&\s#]+)/gi, to: "$1<redacted>" },
18
+ // JSON 形态:{"apiKey":"..."} / {"mimoApiKey":"..."} / {"openaiApiKey":"..."} / {"token":"..."}(只遮引号内的值)
19
+ {
20
+ re: /("(?:[a-zA-Z0-9_-]*?(?:api[_-]?key|token|secret|password))"\s*:\s*")([^"\\]{6,})(")/gi,
21
+ to: "$1<redacted>$3"
22
+ }
23
+ ];
24
+ var BARE = [
25
+ /\bsk[-_][A-Za-z0-9._-]{8,}/g,
26
+ // 更多厂商前缀(2026-11-20 审计实测:Groq 的 gsk_ 原样漏出,而 Groq 就在本仓预设里)。
27
+ /\bgsk_[A-Za-z0-9._-]{8,}/g,
28
+ /\bsk-(?:proj|live|test)-[A-Za-z0-9._-]{8,}/g,
29
+ /\brk_(?:live|test)_[A-Za-z0-9]{8,}/g,
30
+ /\bAIza[A-Za-z0-9._-]{10,}/g,
31
+ /\bgh[pousr]_[A-Za-z0-9]{10,}/g,
32
+ // 通用兜底:≥20 连续 base64-ish 字符,要求**同时含大写、小写与数字**(真密钥的典型特征),
33
+ // 且排除纯十六进制(SHA256/MD5 是排障信息)。这样不会吃掉全小写的模型名、
34
+ // 也不会吃掉被 - / 分隔的 UUID 与路径。
35
+ // 注意:字符类**不含 '/'**——路径与 provider/model:voice 形态都靠 '/' 分隔,含进来会误伤排障信息。
36
+ // 豁免仅限 64 位 sha256(模型摘要);32 位 hex 也可能是 key(审计实测漏遮)。
37
+ /\b(?![0-9a-fA-F]{64}\b)(?=[A-Za-z0-9+=_-]*[A-Z])(?=[A-Za-z0-9+=_-]*[a-z])(?=[A-Za-z0-9+=_-]*[0-9])[A-Za-z0-9+=_-]{20,}\b/g,
38
+ // 32 位 hex(md5 形状)也可能是 key:通用规则要求大小写混合,纯小写 hex 会被漏掉。
39
+ // 64 位 sha256 不在此列(模型摘要要保留排障)。
40
+ /\b[0-9a-f]{32}\b/gi
41
+ ];
42
+ function redactSecrets(text) {
43
+ let out = typeof text === "string" ? text : String(text ?? "");
44
+ for (const { re, to } of PREFIXED) out = out.replace(re, to);
45
+ for (const re of BARE) out = out.replace(re, "<redacted>");
46
+ return out;
47
+ }
48
+ function redactBodySnippet(body, n = 200) {
49
+ const raw = typeof body === "string" ? body : String(body ?? "");
50
+ return redactSecrets(raw.slice(0, n + 128)).slice(0, n);
51
+ }
52
+
53
+ // src/asr-host.ts
9
54
  import { join as join2 } from "node:path";
10
55
  import { fileURLToPath } from "node:url";
11
56
  import { Worker } from "node:worker_threads";
@@ -32,7 +77,11 @@ function createSenseWorkerClient(worker) {
32
77
  if (!p) return;
33
78
  pending.delete(msg.id);
34
79
  if (!msg.ok) {
35
- p.resolve(null);
80
+ if (p.op === "create") {
81
+ p.reject(new Error(msg.error ?? "sense worker create failed"));
82
+ } else {
83
+ p.resolve(null);
84
+ }
36
85
  return;
37
86
  }
38
87
  p.resolve(p.op === "create" ? true : msg.text ?? "");
@@ -189,9 +238,15 @@ var MODEL_FETCH_HEADERS_TIMEOUT_MS = 6e4;
189
238
  var MODEL_BODY_IDLE_TIMEOUT_MS = 12e4;
190
239
  function makeIdleWatch(ac, ms) {
191
240
  let t;
192
- const stop = () => clearTimeout(t);
241
+ let stopped = false;
242
+ const stop = () => {
243
+ stopped = true;
244
+ clearTimeout(t);
245
+ t = void 0;
246
+ };
193
247
  const kick = () => {
194
- stop();
248
+ if (stopped) return;
249
+ clearTimeout(t);
195
250
  t = setTimeout(() => ac.abort(new Error("model download idle timeout")), ms);
196
251
  };
197
252
  return { kick, stop };
@@ -258,8 +313,12 @@ async function downloadVerified(opts) {
258
313
  if (resumeFrom > 0) headers.range = `bytes=${resumeFrom}-`;
259
314
  const res = await fetchWithHeadersTimeout(url, { headers, redirect: "follow" }, ac);
260
315
  idle.kick();
261
- if (!redirectHostAllowed(res.url, allowCustomHost)) return false;
316
+ if (!redirectHostAllowed(res.url, allowCustomHost)) {
317
+ await res.body?.cancel().catch(() => void 0);
318
+ return false;
319
+ }
262
320
  if (res.status === 416) {
321
+ await res.body?.cancel().catch(() => void 0);
263
322
  if (await sha256OfFile(partPath).catch(() => "") === spec.sha256) {
264
323
  await rename(partPath, localPath);
265
324
  return true;
@@ -267,7 +326,10 @@ async function downloadVerified(opts) {
267
326
  await unlink(partPath).catch(() => void 0);
268
327
  return false;
269
328
  }
270
- if (res.status !== 200 && res.status !== 206) return false;
329
+ if (res.status !== 200 && res.status !== 206) {
330
+ await res.body?.cancel().catch(() => void 0);
331
+ return false;
332
+ }
271
333
  const resume = res.status === 206 ? resumeFrom : 0;
272
334
  const total = Number(res.headers.get("content-length") ?? 0) + resume;
273
335
  const src = res.body;
@@ -276,17 +338,39 @@ async function downloadVerified(opts) {
276
338
  const reader = src.getReader();
277
339
  let received = resume;
278
340
  await new Promise((resolve, reject) => {
279
- sink.on("error", (e) => reject(e));
341
+ let failed = false;
342
+ let wakeDrain = null;
343
+ sink.on("error", (e) => {
344
+ if (failed) return;
345
+ failed = true;
346
+ ac.abort(e);
347
+ wakeDrain?.();
348
+ wakeDrain = null;
349
+ void reader.cancel(e).catch(() => void 0);
350
+ reject(e);
351
+ });
280
352
  sink.on("finish", () => resolve());
281
353
  void (async () => {
282
354
  try {
283
355
  for (; ; ) {
356
+ if (failed) return;
284
357
  const { done, value } = await reader.read();
285
- if (done) break;
358
+ if (done || failed) break;
286
359
  idle.kick();
287
360
  received += value.byteLength;
288
361
  if (!sink.write(value)) {
289
- await new Promise((r) => sink.once("drain", r));
362
+ await new Promise((r) => {
363
+ if (failed) {
364
+ r();
365
+ return;
366
+ }
367
+ wakeDrain = r;
368
+ sink.once("drain", () => {
369
+ wakeDrain = null;
370
+ r();
371
+ });
372
+ });
373
+ if (failed) return;
290
374
  idle.kick();
291
375
  }
292
376
  if (total > 0) {
@@ -296,10 +380,14 @@ async function downloadVerified(opts) {
296
380
  });
297
381
  }
298
382
  }
299
- sink.end();
383
+ if (!failed) sink.end();
300
384
  } catch (e) {
301
- sink.destroy(e);
302
- reject(e);
385
+ if (!failed) {
386
+ failed = true;
387
+ sink.destroy(e);
388
+ void reader.cancel(e).catch(() => void 0);
389
+ reject(e);
390
+ }
303
391
  }
304
392
  })();
305
393
  });
@@ -354,17 +442,33 @@ async function ensureModelTree(opts) {
354
442
  await mkdir(subRoot, { recursive: true }).catch(() => void 0);
355
443
  let tree = [];
356
444
  for (const host of hosts) {
445
+ if (opts.signal?.aborted) break;
446
+ const listAc = new AbortController();
447
+ const onListAbort = () => listAc.abort(opts.signal?.reason);
448
+ if (opts.signal?.aborted) onListAbort();
449
+ else opts.signal?.addEventListener("abort", onListAbort, { once: true });
450
+ const listIdle = makeIdleWatch(listAc, opts.idleTimeoutMs ?? MODEL_BODY_IDLE_TIMEOUT_MS);
357
451
  try {
358
452
  const res = await fetchWithHeadersTimeout(host + "/api/models/" + repo + "?blobs=true", {
359
453
  headers: { "user-agent": "dsh-voice-mode" }
360
- });
361
- if (!redirectHostAllowed(res.url, allowCustomHost)) continue;
454
+ }, listAc);
455
+ if (!redirectHostAllowed(res.url, allowCustomHost)) {
456
+ await res.body?.cancel().catch(() => void 0);
457
+ continue;
458
+ }
362
459
  if (res.ok) {
460
+ listIdle.kick();
363
461
  const j = await res.json();
364
462
  tree = (j.siblings ?? []).map((s) => s.rfilename ?? "").filter((f) => isSafeModelRel(f, subdir));
365
463
  if (tree.length > 0) break;
464
+ } else {
465
+ await res.body?.cancel().catch(() => void 0);
366
466
  }
367
467
  } catch {
468
+ if (opts.signal?.aborted) break;
469
+ } finally {
470
+ listIdle.stop();
471
+ opts.signal?.removeEventListener("abort", onListAbort);
368
472
  }
369
473
  }
370
474
  if (tree.length === 0) return false;
@@ -377,7 +481,8 @@ async function ensureModelTree(opts) {
377
481
  if (rel === void 0) return;
378
482
  const localPath = join(repoDir, rel);
379
483
  const partPath = localPath + ".part";
380
- if ((await stat(localPath).catch(() => null))?.isFile() && (await stat(localPath)).size > 0) {
484
+ const localSt = await stat(localPath).catch(() => null);
485
+ if (localSt?.isFile() && localSt.size > 0) {
381
486
  done++;
382
487
  continue;
383
488
  }
@@ -385,7 +490,8 @@ async function ensureModelTree(opts) {
385
490
  let ok = false;
386
491
  for (const host of hosts) {
387
492
  try {
388
- const url = host + "/" + repo + "/resolve/main/" + encodeURIComponent(rel);
493
+ const encodedRel = rel.split("/").map(encodeURIComponent).join("/");
494
+ const url = host + "/" + repo + "/resolve/main/" + encodedRel;
389
495
  const ac = new AbortController();
390
496
  const onAbort = () => ac.abort(opts.signal?.reason);
391
497
  if (opts.signal?.aborted) onAbort();
@@ -393,32 +499,64 @@ async function ensureModelTree(opts) {
393
499
  const idle = makeIdleWatch(ac, opts.idleTimeoutMs ?? MODEL_BODY_IDLE_TIMEOUT_MS);
394
500
  try {
395
501
  const res = await fetchWithHeadersTimeout(url, { headers: { "user-agent": "dsh-voice-mode" }, redirect: "follow" }, ac);
396
- if (!redirectHostAllowed(res.url, allowCustomHost)) continue;
397
- if (res.status !== 200) continue;
502
+ if (!redirectHostAllowed(res.url, allowCustomHost)) {
503
+ await res.body?.cancel().catch(() => void 0);
504
+ continue;
505
+ }
506
+ if (res.status !== 200) {
507
+ await res.body?.cancel().catch(() => void 0);
508
+ continue;
509
+ }
398
510
  idle.kick();
399
511
  const reader = res.body?.getReader();
400
512
  if (!reader) continue;
401
513
  const sink = createWriteStream(partPath);
402
514
  let size = 0;
403
515
  await new Promise((resolve, reject) => {
404
- sink.on("error", reject);
516
+ let failed = false;
517
+ let wakeDrain = null;
518
+ sink.on("error", (e) => {
519
+ if (failed) return;
520
+ failed = true;
521
+ ac.abort(e);
522
+ wakeDrain?.();
523
+ wakeDrain = null;
524
+ void reader.cancel(e).catch(() => void 0);
525
+ reject(e);
526
+ });
405
527
  sink.on("finish", resolve);
406
528
  void (async () => {
407
529
  try {
408
530
  for (; ; ) {
531
+ if (failed) return;
409
532
  const r = await reader.read();
410
- if (r.done) break;
533
+ if (r.done || failed) break;
411
534
  idle.kick();
412
535
  size += r.value.byteLength;
413
536
  if (!sink.write(r.value)) {
414
- await new Promise((r2) => sink.once("drain", r2));
537
+ await new Promise((r2) => {
538
+ if (failed) {
539
+ r2();
540
+ return;
541
+ }
542
+ wakeDrain = r2;
543
+ sink.once("drain", () => {
544
+ wakeDrain = null;
545
+ r2();
546
+ });
547
+ });
548
+ if (failed) return;
415
549
  idle.kick();
416
550
  }
417
551
  }
418
- sink.end();
552
+ if (!failed) sink.end();
419
553
  } catch (e) {
420
- sink.destroy(e);
421
- reject(e);
554
+ if (!failed) {
555
+ failed = true;
556
+ sink.destroy(e);
557
+ void reader.cancel(e).catch(() => void 0);
558
+ reject(e);
559
+ }
422
560
  }
423
561
  })();
424
562
  });
@@ -475,9 +613,27 @@ var SENSE_FILES = [
475
613
  { file: "model.int8.onnx", sha256: "c71f0ce00bec95b07744e116345e33d8cbbe08cef896382cf907bf4b51a2cd51" },
476
614
  { file: "tokens.txt", sha256: "f449eb28dc567533d7fa59be34e2abca8784f771850c78a47fb731a31429a1dc" }
477
615
  ];
616
+ var DECODE_YIELD_EVERY = 8;
617
+ var yieldToLoop = () => new Promise((resolve) => setImmediate(resolve));
478
618
  function pcmToSamples(buf) {
479
619
  if (buf.length % 4 !== 0) return null;
480
- return new Float32Array(buf.buffer, buf.byteOffset, buf.length / 4);
620
+ const len = buf.length / 4;
621
+ const out = new Float32Array(len);
622
+ if (buf.byteOffset % 4 === 0) {
623
+ out.set(new Float32Array(buf.buffer, buf.byteOffset, len));
624
+ } else {
625
+ const aligned = Buffer.from(buf);
626
+ out.set(new Float32Array(aligned.buffer, aligned.byteOffset, len));
627
+ }
628
+ let bad = 0;
629
+ for (let i = 0; i < out.length; i++) {
630
+ if (!Number.isFinite(out[i])) {
631
+ out[i] = 0;
632
+ bad++;
633
+ }
634
+ }
635
+ if (bad > 0) console.warn(`[dsh-voice-mode] pcm contained ${bad} non-finite sample(s); coerced to 0`);
636
+ return out;
481
637
  }
482
638
  var MAX_ASR_BYTES = 4 * 1024 * 1024;
483
639
  var SEGMENT_IDLE_MS = 9e4;
@@ -510,6 +666,36 @@ function createAsrRuntime(options) {
510
666
  const vadDir = join2(cacheDir, VAD_REPO);
511
667
  const senseDir = join2(cacheDir, SENSE_REPO);
512
668
  const normalizedModelHost = () => validateModelHost(modelHost(), allowCustomHost) ?? HOST_PRIMARY;
669
+ const freeSegment = (s) => {
670
+ if (s.freed) return;
671
+ s.freed = true;
672
+ try {
673
+ s.vad?.free?.();
674
+ } catch {
675
+ }
676
+ try {
677
+ s.stream.free();
678
+ } catch {
679
+ }
680
+ };
681
+ const dlAbort = new AbortController();
682
+ const segChains = /* @__PURE__ */ new Map();
683
+ const withSegLock = async (key, fn) => {
684
+ const prev = segChains.get(key) ?? Promise.resolve();
685
+ let release;
686
+ const next = new Promise((r) => {
687
+ release = r;
688
+ });
689
+ const tail = prev.then(() => next);
690
+ segChains.set(key, tail);
691
+ await prev;
692
+ try {
693
+ return await fn();
694
+ } finally {
695
+ release();
696
+ if (segChains.get(key) === tail) segChains.delete(key);
697
+ }
698
+ };
513
699
  const segments = /* @__PURE__ */ new Map();
514
700
  const finalized = /* @__PURE__ */ new Map();
515
701
  const finalizing = /* @__PURE__ */ new Map();
@@ -525,7 +711,7 @@ function createAsrRuntime(options) {
525
711
  if (!modelsLoading) {
526
712
  modelsLoading = (async () => {
527
713
  for (const f of MODEL_FILES) {
528
- if (!await ensureModelFile({ repo: MODEL_REPO, repoDir, spec: f, primaryHost: normalizedModelHost(), allowCustomHost, broadcast: localBroadcast })) {
714
+ if (!await ensureModelFile({ repo: MODEL_REPO, repoDir, spec: f, primaryHost: normalizedModelHost(), allowCustomHost, broadcast: localBroadcast, signal: dlAbort.signal })) {
529
715
  asrFailAt = Date.now() + 6e4;
530
716
  broadcast("asr-error", { file: f.file });
531
717
  return false;
@@ -571,7 +757,7 @@ function createAsrRuntime(options) {
571
757
  if (!vadLoading) {
572
758
  vadLoading = (async () => {
573
759
  for (const f of VAD_FILES) {
574
- if (!await ensureModelFile({ repo: VAD_REPO, repoDir: vadDir, spec: f, primaryHost: normalizedModelHost(), allowCustomHost, broadcast: localBroadcast })) {
760
+ if (!await ensureModelFile({ repo: VAD_REPO, repoDir: vadDir, spec: f, primaryHost: normalizedModelHost(), allowCustomHost, broadcast: localBroadcast, signal: dlAbort.signal })) {
575
761
  vadFailAt = Date.now() + 6e4;
576
762
  return null;
577
763
  }
@@ -601,19 +787,24 @@ function createAsrRuntime(options) {
601
787
  bufferSizeInSeconds: 30
602
788
  });
603
789
  const ensureSessionVad = async (seg) => {
790
+ if (seg.freed || recognizerDisposed) return null;
604
791
  if (seg.vad) return seg.vad;
605
792
  const vadPath = await ensureVadModel();
606
- if (!vadPath) return null;
793
+ if (!vadPath || seg.freed || recognizerDisposed) return null;
794
+ if (seg.vad) return seg.vad;
607
795
  seg.vad = newVad(vadPath, 0.5, silenceMs() / 1e3);
608
796
  return seg.vad;
609
797
  };
610
798
  const detectVads = /* @__PURE__ */ new Map();
611
799
  const detectVadLastUse = /* @__PURE__ */ new Map();
612
800
  const ensureDetectVad = async (sessionId) => {
801
+ if (recognizerDisposed) return null;
613
802
  const existing = detectVads.get(sessionId);
614
803
  if (existing) return existing;
615
804
  const vadPath = await ensureVadModel();
616
- if (!vadPath) return null;
805
+ if (!vadPath || recognizerDisposed) return null;
806
+ const existingAfter = detectVads.get(sessionId);
807
+ if (existingAfter) return existingAfter;
617
808
  const vad = newVad(vadPath, 0.35);
618
809
  detectVads.set(sessionId, vad);
619
810
  return vad;
@@ -621,13 +812,14 @@ function createAsrRuntime(options) {
621
812
  let senseModelReady = false;
622
813
  let senseLoading = null;
623
814
  let senseFailAt = 0;
815
+ let senseWorkerFailAt = 0;
624
816
  const ensureSenseModel = async () => {
625
817
  if (senseModelReady) return join2(senseDir, SENSE_FILES[0].file);
626
818
  if (Date.now() < senseFailAt) return null;
627
819
  if (!senseLoading) {
628
820
  senseLoading = (async () => {
629
821
  for (const f of SENSE_FILES) {
630
- if (!await ensureModelFile({ repo: SENSE_REPO, repoDir: senseDir, spec: f, primaryHost: normalizedModelHost(), allowCustomHost, broadcast: localBroadcast })) {
822
+ if (!await ensureModelFile({ repo: SENSE_REPO, repoDir: senseDir, spec: f, primaryHost: normalizedModelHost(), allowCustomHost, broadcast: localBroadcast, signal: dlAbort.signal })) {
631
823
  senseFailAt = Date.now() + 6e4;
632
824
  return null;
633
825
  }
@@ -647,19 +839,22 @@ function createAsrRuntime(options) {
647
839
  let senseDisposed = false;
648
840
  const getSenseWorker = async () => {
649
841
  if (!senseVoice()) return null;
842
+ if (senseDisposed) return null;
650
843
  const langKey = `auto\0${senseITN() ? "1" : "0"}`;
651
844
  if (senseWorker && langKey !== senseWorkerLangKey) {
652
845
  void senseWorker.terminate();
653
846
  senseWorker = null;
654
847
  senseWorkerSyncing = null;
655
848
  }
656
- senseWorkerLangKey = langKey;
657
849
  if (senseWorker) return senseWorker;
658
- if (senseWorkerSyncing) return senseWorkerSyncing;
659
- senseWorkerSyncing = (async () => {
850
+ if (Date.now() < senseWorkerFailAt) return null;
851
+ if (senseWorkerSyncing && langKey === senseWorkerLangKey) return senseWorkerSyncing;
852
+ const myLangKey = langKey;
853
+ senseWorkerLangKey = myLangKey;
854
+ const syncP = (async () => {
660
855
  if (senseDisposed) return null;
661
856
  const sensePath = await ensureSenseModel();
662
- if (!sensePath) return null;
857
+ if (!sensePath || senseDisposed || senseWorkerLangKey !== myLangKey) return null;
663
858
  try {
664
859
  const workerPath = fileURLToPath(new URL("./sense-worker.mjs", import.meta.url));
665
860
  const w = new Worker(workerPath, {
@@ -667,33 +862,38 @@ function createAsrRuntime(options) {
667
862
  sherpaModule: "sherpa-onnx",
668
863
  modelDir: senseDir,
669
864
  language: "auto",
670
- useITN: senseITN() ? 1 : 0
865
+ useITN: myLangKey.endsWith("1") ? 1 : 0
671
866
  }
672
867
  });
673
868
  const client = createSenseWorkerClient(w);
674
869
  client.onDeath(() => {
675
- senseWorker = null;
676
- senseWorkerSyncing = null;
677
- senseWorkerLangKey = "";
870
+ if (senseWorker === client) {
871
+ senseWorker = null;
872
+ senseWorkerSyncing = null;
873
+ senseWorkerLangKey = "";
874
+ }
678
875
  });
679
876
  if (!await client.request("create")) {
680
877
  await client.terminate();
681
- return null;
878
+ throw new Error("sense worker create returned false");
682
879
  }
683
- if (senseDisposed) {
880
+ if (senseDisposed || senseWorkerLangKey !== myLangKey) {
684
881
  await client.terminate();
685
882
  return null;
686
883
  }
687
884
  senseWorker = client;
688
885
  return client;
689
886
  } catch (e) {
690
- console.warn("[dsh-voice-mode] SenseVoice worker init failed: " + String(e));
887
+ senseWorkerFailAt = Date.now() + 6e4;
888
+ console.warn("[dsh-voice-mode] SenseVoice worker init failed: " + redactSecrets(e));
889
+ broadcast?.("asr-notice", { code: "sense_degraded" });
691
890
  return null;
692
891
  }
693
892
  })().finally(() => {
694
- if (!senseWorker || senseDisposed) senseWorkerSyncing = null;
893
+ if (senseWorkerSyncing === syncP && (!senseWorker || senseDisposed)) senseWorkerSyncing = null;
695
894
  });
696
- return senseWorkerSyncing;
895
+ senseWorkerSyncing = syncP;
896
+ return syncP;
697
897
  };
698
898
  const senseTranscribe = async (allSamples) => {
699
899
  try {
@@ -709,153 +909,183 @@ function createAsrRuntime(options) {
709
909
  }
710
910
  return await worker.request("decode", buf);
711
911
  } catch (e) {
712
- console.warn("[dsh-voice-mode] SenseVoice re-transcribe failed: " + String(e));
912
+ console.warn("[dsh-voice-mode] SenseVoice re-transcribe failed: " + redactSecrets(e));
713
913
  return null;
714
914
  }
715
915
  };
716
- const feed = async (sessionId, samples, final, offset = 0, epoch = 0, manualPressed = false) => {
916
+ const feedRaw = async (sessionId, samples, final, offset = 0, epoch = 0, manualPressed = false) => {
717
917
  if (bargeInMode() === "manual" && !manualPressed) {
718
918
  return { text: "" };
719
919
  }
720
920
  const rec = await getRecognizer();
721
921
  if (!rec) return { text: "", loading: true };
922
+ if (recognizerDisposed) return { text: "" };
722
923
  if (!final && senseVoice()) {
723
924
  void getSenseWorker().catch(() => {
724
925
  });
725
926
  }
726
- let finMap = finalized.get(sessionId);
727
- const myGen = resetGen.get(sessionId) ?? 0;
728
- const cached2 = finMap?.get(epoch);
729
- if (cached2 !== void 0) return { text: cached2 };
730
- let sessSegs = segments.get(sessionId);
731
- if (!sessSegs) {
732
- sessSegs = /* @__PURE__ */ new Map();
733
- segments.set(sessionId, sessSegs);
734
- }
735
- let seg = sessSegs.get(epoch);
736
- if (!seg) {
737
- if (samples.length === 0 && final) return { text: "" };
738
- seg = { stream: rec.createStream(), fed: 0, vad: null, pendingEndpoint: null, lastText: "", allSamples: [], lastActivity: Date.now() };
739
- sessSegs.set(epoch, seg);
740
- }
741
- seg.lastActivity = Date.now();
742
- let endpoint = false;
743
- let text = "";
744
- let isSpeech;
745
- if (offset + samples.length > seg.fed) {
746
- const skip = Math.max(seg.fed - offset, 0);
747
- const inc = samples.subarray(skip);
748
- seg.stream.acceptWaveform(rec.config.featConfig.sampleRate, inc);
749
- seg.fed = offset + samples.length;
750
- if (seg.fed <= rec.config.featConfig.sampleRate * 60) seg.allSamples.push(inc);
751
- while (rec.isReady(seg.stream)) rec.decode(seg.stream);
752
- text = rec.getResult(seg.stream).text;
753
- seg.lastText = text;
754
- if (!final) {
755
- const vad = await ensureSessionVad(seg);
756
- if (vad) {
757
- if (seg.pendingEndpoint) {
758
- const now = Date.now();
759
- const rms = rmsOf(inc);
760
- if (rms > VAD_CONTINUE_RMS) {
761
- seg.pendingEndpoint = null;
762
- } else if (now - seg.pendingEndpoint.at >= CONFIRM_MIN_MS && text === seg.pendingEndpoint.textAtPending) {
763
- seg.pendingEndpoint = null;
764
- endpoint = true;
765
- } else if (now - seg.pendingEndpoint.at >= seg.pendingEndpoint.confirmMs) {
766
- seg.pendingEndpoint = null;
767
- endpoint = true;
768
- }
927
+ return withSegLock(`${sessionId}\0${epoch}`, async () => {
928
+ if (recognizerDisposed) return { text: "" };
929
+ const finMap = finalized.get(sessionId);
930
+ const myGen = resetGen.get(sessionId) ?? 0;
931
+ const cached2 = finMap?.get(epoch);
932
+ if (cached2 !== void 0) return { text: cached2 };
933
+ const existingInflight = finalizing.get(sessionId)?.get(epoch);
934
+ if (final && existingInflight) return { text: await existingInflight };
935
+ let sessSegs = segments.get(sessionId);
936
+ if (!sessSegs) {
937
+ sessSegs = /* @__PURE__ */ new Map();
938
+ segments.set(sessionId, sessSegs);
939
+ }
940
+ let seg = sessSegs.get(epoch);
941
+ if (!seg) {
942
+ if (samples.length === 0 && final) return { text: "" };
943
+ seg = { stream: rec.createStream(), fed: 0, vad: null, pendingEndpoint: null, lastText: "", allSamples: [], lastActivity: Date.now(), freed: false };
944
+ sessSegs.set(epoch, seg);
945
+ }
946
+ seg.lastActivity = Date.now();
947
+ let endpoint = false;
948
+ let text = "";
949
+ let isSpeech;
950
+ if (offset + samples.length > seg.fed) {
951
+ const skip = Math.max(seg.fed - offset, 0);
952
+ const inc = samples.subarray(skip);
953
+ if (seg.freed || recognizerDisposed) return { text: "" };
954
+ seg.stream.acceptWaveform(rec.config.featConfig.sampleRate, inc);
955
+ seg.fed = offset + samples.length;
956
+ if (seg.fed <= rec.config.featConfig.sampleRate * 60) seg.allSamples.push(inc);
957
+ {
958
+ let n = 0;
959
+ while (!seg.freed && !recognizerDisposed && rec.isReady(seg.stream)) {
960
+ rec.decode(seg.stream);
961
+ if (++n % DECODE_YIELD_EVERY === 0) await yieldToLoop();
769
962
  }
770
- vad.acceptWaveform(inc);
771
- isSpeech = vad.isDetected();
772
- if (!vad.isEmpty()) {
773
- let spokenMs = 0;
774
- while (!vad.isEmpty()) {
775
- const sp = vad.front();
776
- spokenMs = sp.samples.length / 16e3 * 1e3;
777
- vad.pop();
963
+ }
964
+ if (seg.freed || recognizerDisposed) return { text: "" };
965
+ text = rec.getResult(seg.stream).text;
966
+ seg.lastText = text;
967
+ if (!final) {
968
+ const vad = await ensureSessionVad(seg);
969
+ if (seg.freed || recognizerDisposed) return { text: "" };
970
+ if (vad) {
971
+ if (seg.pendingEndpoint) {
972
+ const now = Date.now();
973
+ const rms = rmsOf(inc);
974
+ if (rms > VAD_CONTINUE_RMS) {
975
+ seg.pendingEndpoint = null;
976
+ } else if (now - seg.pendingEndpoint.at >= seg.pendingEndpoint.confirmMs) {
977
+ seg.pendingEndpoint = null;
978
+ endpoint = true;
979
+ }
778
980
  }
779
- const confirmMs = endpointConfirmMs(seg.lastText, spokenMs);
780
- if (confirmMs <= 0) {
781
- endpoint = true;
782
- } else {
783
- seg.pendingEndpoint = { at: Date.now(), confirmMs, textAtPending: seg.lastText };
981
+ vad.acceptWaveform(inc);
982
+ isSpeech = vad.isDetected();
983
+ if (!vad.isEmpty()) {
984
+ let spokenMs = 0;
985
+ while (!vad.isEmpty()) {
986
+ const sp = vad.front();
987
+ spokenMs = sp.samples.length / 16e3 * 1e3;
988
+ vad.pop();
989
+ }
990
+ const confirmMs = endpointConfirmMs(seg.lastText, spokenMs);
991
+ if (confirmMs <= 0) {
992
+ endpoint = true;
993
+ } else {
994
+ seg.pendingEndpoint = { at: Date.now(), confirmMs, textAtPending: seg.lastText };
995
+ }
784
996
  }
785
997
  }
786
998
  }
787
999
  }
788
- }
789
- if (!final) return { text, endpoint, isSpeech };
790
- const inflightMap = finalizing.get(sessionId);
791
- const inflightP = inflightMap?.get(epoch);
792
- if (inflightP) return { text: await inflightP };
793
- sessSegs.delete(epoch);
794
- if (sessSegs.size === 0) segments.delete(sessionId);
795
- const finalizeP = (async () => {
796
- const all = seg.allSamples;
797
- let senseTimer = null;
798
- const senseP = all.length > 0 ? Promise.race([
799
- senseTranscribe(all),
800
- new Promise((resolve) => {
801
- senseTimer = setTimeout(() => resolve(null), 2e4);
802
- })
803
- ]).finally(() => {
804
- if (senseTimer) clearTimeout(senseTimer);
805
- }) : Promise.resolve(null);
806
- const pad = new Float32Array(rec.config.featConfig.sampleRate / 2);
807
- seg.stream.acceptWaveform(rec.config.featConfig.sampleRate, pad);
808
- while (rec.isReady(seg.stream)) rec.decode(seg.stream);
809
- const settled = rec.getResult(seg.stream).text;
810
- try {
811
- seg.vad?.free?.();
812
- } catch {
813
- }
814
- seg.stream.free();
815
- const sense = await senseP;
816
- return (sense && sense.trim() ? sense : settled) || "";
817
- })().then((finalText) => {
818
- if ((resetGen.get(sessionId) ?? 0) !== myGen) return finalText;
819
- let fm = finalized.get(sessionId);
820
- if (!fm) {
821
- fm = /* @__PURE__ */ new Map();
822
- finalized.set(sessionId, fm);
823
- }
824
- fm.set(epoch, finalText);
825
- if (fm.size > 32) {
826
- const first = fm.keys().next().value;
827
- if (first !== void 0) fm.delete(first);
1000
+ if (!final) return { text, endpoint, isSpeech };
1001
+ if (seg.freed || recognizerDisposed) return { text: "" };
1002
+ const inflightMap = finalizing.get(sessionId);
1003
+ const inflightP = inflightMap?.get(epoch);
1004
+ if (inflightP) return { text: await inflightP };
1005
+ sessSegs.delete(epoch);
1006
+ if (sessSegs.size === 0) segments.delete(sessionId);
1007
+ const evictWedgedSenseWorker = () => {
1008
+ const wedged = senseWorker;
1009
+ if (wedged) {
1010
+ senseWorker = null;
1011
+ senseWorkerSyncing = null;
1012
+ void wedged.terminate().catch(() => void 0);
1013
+ }
1014
+ };
1015
+ const finalizeP = (async () => {
1016
+ const all = seg.allSamples;
1017
+ let senseTimer = null;
1018
+ const senseP = all.length > 0 ? Promise.race([
1019
+ senseTranscribe(all),
1020
+ new Promise((resolve) => {
1021
+ senseTimer = setTimeout(() => {
1022
+ evictWedgedSenseWorker();
1023
+ resolve(null);
1024
+ }, 2e4);
1025
+ })
1026
+ ]).finally(() => {
1027
+ if (senseTimer) clearTimeout(senseTimer);
1028
+ }) : Promise.resolve(null);
1029
+ let settled = seg.lastText;
1030
+ try {
1031
+ if (!seg.freed && !recognizerDisposed) {
1032
+ const pad = new Float32Array(rec.config.featConfig.sampleRate / 2);
1033
+ seg.stream.acceptWaveform(rec.config.featConfig.sampleRate, pad);
1034
+ let n = 0;
1035
+ while (!seg.freed && !recognizerDisposed && rec.isReady(seg.stream)) {
1036
+ rec.decode(seg.stream);
1037
+ if (++n % DECODE_YIELD_EVERY === 0) await yieldToLoop();
1038
+ }
1039
+ if (!seg.freed && !recognizerDisposed) {
1040
+ settled = rec.getResult(seg.stream).text;
1041
+ }
1042
+ }
1043
+ } finally {
1044
+ freeSegment(seg);
1045
+ }
1046
+ const sense = await senseP;
1047
+ return (sense && sense.trim() ? sense : settled) || "";
1048
+ })().then((finalText) => {
1049
+ if ((resetGen.get(sessionId) ?? 0) !== myGen) return finalText;
1050
+ let fm = finalized.get(sessionId);
1051
+ if (!fm) {
1052
+ fm = /* @__PURE__ */ new Map();
1053
+ finalized.set(sessionId, fm);
1054
+ }
1055
+ fm.set(epoch, finalText);
1056
+ if (fm.size > 32) {
1057
+ const busy = finalizing.get(sessionId);
1058
+ for (const [k] of fm) {
1059
+ if (busy?.has(k)) continue;
1060
+ fm.delete(k);
1061
+ break;
1062
+ }
1063
+ }
1064
+ const ff = finalizing.get(sessionId);
1065
+ ff?.delete(epoch);
1066
+ if (ff && ff.size === 0) finalizing.delete(sessionId);
1067
+ return finalText;
1068
+ }).catch((e) => {
1069
+ if ((resetGen.get(sessionId) ?? 0) !== myGen) return "";
1070
+ const ff = finalizing.get(sessionId);
1071
+ ff?.delete(epoch);
1072
+ if (ff && ff.size === 0) finalizing.delete(sessionId);
1073
+ console.warn("[dsh-voice-mode] finalize failed: " + redactSecrets(e));
1074
+ return "";
1075
+ });
1076
+ if (!inflightMap) {
1077
+ finalizing.set(sessionId, /* @__PURE__ */ new Map());
828
1078
  }
829
- const ff = finalizing.get(sessionId);
830
- ff?.delete(epoch);
831
- if (ff && ff.size === 0) finalizing.delete(sessionId);
832
- return finalText;
833
- }).catch((e) => {
834
- const ff = finalizing.get(sessionId);
835
- ff?.delete(epoch);
836
- if (ff && ff.size === 0) finalizing.delete(sessionId);
837
- console.warn("[dsh-voice-mode] finalize failed: " + String(e));
838
- return "";
1079
+ finalizing.get(sessionId).set(epoch, finalizeP);
1080
+ return { text: await finalizeP };
839
1081
  });
840
- if (!inflightMap) {
841
- finalizing.set(sessionId, /* @__PURE__ */ new Map());
842
- }
843
- finalizing.get(sessionId).set(epoch, finalizeP);
844
- return { text: await finalizeP };
845
1082
  };
846
1083
  const sweep = () => {
847
1084
  const now = Date.now();
848
1085
  for (const [sid, sessSegs] of segments) {
849
1086
  for (const [epoch, s] of sessSegs) {
850
1087
  if (now - s.lastActivity > SEGMENT_IDLE_MS) {
851
- try {
852
- s.vad?.free?.();
853
- } catch {
854
- }
855
- try {
856
- s.stream.free();
857
- } catch {
858
- }
1088
+ freeSegment(s);
859
1089
  sessSegs.delete(epoch);
860
1090
  }
861
1091
  }
@@ -867,11 +1097,6 @@ function createAsrRuntime(options) {
867
1097
  for (const sid of finalized.keys()) {
868
1098
  if (segments.has(sid) || finalizing.has(sid)) continue;
869
1099
  finalized.delete(sid);
870
- resetGen.delete(sid);
871
- }
872
- for (const sid of resetGen.keys()) {
873
- if (segments.has(sid) || finalizing.has(sid)) continue;
874
- resetGen.delete(sid);
875
1100
  }
876
1101
  for (const [sid, at] of detectVadLastUse) {
877
1102
  if (now - at > SEGMENT_IDLE_MS) {
@@ -885,6 +1110,11 @@ function createAsrRuntime(options) {
885
1110
  }
886
1111
  };
887
1112
  const sweepTimer = setInterval(sweep, 3e4);
1113
+ const feed = async (...args) => {
1114
+ const out = await feedRaw(...args);
1115
+ const isFinal = Boolean(args[2]);
1116
+ return options.replaceText && out.text ? { ...out, text: options.replaceText(out.text, isFinal) } : out;
1117
+ };
888
1118
  return {
889
1119
  feed,
890
1120
  detect: async (sessionId, samples) => {
@@ -900,14 +1130,7 @@ function createAsrRuntime(options) {
900
1130
  const sessSegs = segments.get(sessionId);
901
1131
  if (sessSegs) {
902
1132
  for (const [, s] of sessSegs) {
903
- try {
904
- s.vad?.free?.();
905
- } catch {
906
- }
907
- try {
908
- s.stream.free();
909
- } catch {
910
- }
1133
+ freeSegment(s);
911
1134
  }
912
1135
  segments.delete(sessionId);
913
1136
  }
@@ -926,6 +1149,7 @@ function createAsrRuntime(options) {
926
1149
  },
927
1150
  dispose: () => {
928
1151
  clearInterval(sweepTimer);
1152
+ dlAbort.abort(new Error("asr runtime disposed"));
929
1153
  senseDisposed = true;
930
1154
  recognizerDisposed = true;
931
1155
  let w = senseWorker;
@@ -934,14 +1158,7 @@ function createAsrRuntime(options) {
934
1158
  if (w) void w.terminate();
935
1159
  for (const [, sessSegs] of segments) {
936
1160
  for (const [, s] of sessSegs) {
937
- try {
938
- s.vad?.free?.();
939
- } catch {
940
- }
941
- try {
942
- s.stream.free();
943
- } catch {
944
- }
1161
+ freeSegment(s);
945
1162
  }
946
1163
  }
947
1164
  segments.clear();
@@ -986,6 +1203,7 @@ function createAsrRuntime(options) {
986
1203
  // (getSenseWorker:396-401)下次自然触发重建。
987
1204
  markStale: () => {
988
1205
  senseWorkerLangKey = "";
1206
+ senseWorkerFailAt = 0;
989
1207
  },
990
1208
  modelStatus: () => {
991
1209
  const asrFiles = MODEL_FILES.map((n) => ({
@@ -1019,6 +1237,14 @@ function createAsrRuntime(options) {
1019
1237
  return 0;
1020
1238
  }
1021
1239
  })();
1240
+ const senseAllExist = SENSE_FILES.every((f) => {
1241
+ try {
1242
+ const st = statSync(join2(senseDir, f.file));
1243
+ return st.isFile() && st.size > 0;
1244
+ } catch {
1245
+ return false;
1246
+ }
1247
+ });
1022
1248
  return {
1023
1249
  // ready 语义 = 文件可用(exists),而非进程内是否已实例化——
1024
1250
  // 重启后文件齐全却显示「未下载」会误导用户(体验修复)。
@@ -1036,9 +1262,9 @@ function createAsrRuntime(options) {
1036
1262
  },
1037
1263
  sense: {
1038
1264
  repo: SENSE_REPO,
1039
- ready: senseSize > 0,
1265
+ ready: senseAllExist,
1040
1266
  size: senseSize,
1041
- failLatchMs: Math.max(0, senseFailAt - Date.now()),
1267
+ failLatchMs: Math.max(0, Math.max(senseFailAt, senseWorkerFailAt) - Date.now()),
1042
1268
  enabled: senseVoice()
1043
1269
  },
1044
1270
  progress: lastProgress
@@ -1052,6 +1278,7 @@ function createAsrRuntime(options) {
1052
1278
  if (kind === "sense") {
1053
1279
  if (!senseVoice()) return false;
1054
1280
  senseFailAt = 0;
1281
+ senseWorkerFailAt = 0;
1055
1282
  return !!await ensureSenseModel();
1056
1283
  }
1057
1284
  if (modelsReady) return true;
@@ -1061,6 +1288,7 @@ function createAsrRuntime(options) {
1061
1288
  };
1062
1289
  }
1063
1290
  var respondJson = (res, status, payload) => {
1291
+ if (res.writableEnded || res.destroyed) return;
1064
1292
  res.writeHead(status, { "content-type": "application/json" });
1065
1293
  res.end(JSON.stringify(payload));
1066
1294
  };
@@ -1068,19 +1296,30 @@ function handleAsrRequest(asr, activeSessionId, req, res) {
1068
1296
  const chunks = [];
1069
1297
  let received = 0;
1070
1298
  let tooLarge = false;
1299
+ req.on("error", () => {
1300
+ if (!res.writableEnded && !res.destroyed) res.destroy();
1301
+ });
1071
1302
  req.on("data", (c) => {
1072
1303
  if (tooLarge) return;
1073
1304
  received += c.length;
1074
1305
  if (received > MAX_ASR_BYTES) {
1075
1306
  tooLarge = true;
1307
+ req.pause?.();
1076
1308
  respondJson(res, 413, { code: "payload_too_large", error: "pcm payload too large" });
1309
+ req.resume?.();
1077
1310
  return;
1078
1311
  }
1079
1312
  chunks.push(c);
1080
1313
  });
1081
1314
  req.on("end", () => {
1082
1315
  if (tooLarge) return;
1083
- const url = new URL(req.url ?? "/", "http://localhost");
1316
+ let url;
1317
+ try {
1318
+ url = new URL(req.url ?? "/", "http://localhost");
1319
+ } catch {
1320
+ respondJson(res, 400, { code: "bad_request", error: "invalid url" });
1321
+ return;
1322
+ }
1084
1323
  const sessionId = url.searchParams.get("sessionId") ?? "";
1085
1324
  const final = url.searchParams.get("final") === "1";
1086
1325
  const reset = url.searchParams.get("reset") === "1";
@@ -1118,7 +1357,7 @@ function handleAsrRequest(asr, activeSessionId, req, res) {
1118
1357
  void asr.detect(sessionId, samples).then((out) => {
1119
1358
  respondJson(res, 200, { isSpeech: out.isSpeech });
1120
1359
  }).catch((e) => {
1121
- console.warn(`[dsh-voice-mode] asr detect failed: ${String(e)}`);
1360
+ console.warn(`[dsh-voice-mode] asr detect failed: ${redactSecrets(e)}`);
1122
1361
  respondJson(res, 500, { code: "internal", error: "internal error" });
1123
1362
  });
1124
1363
  return;
@@ -1133,12 +1372,75 @@ function handleAsrRequest(asr, activeSessionId, req, res) {
1133
1372
  if (out.isSpeech !== void 0) body.isSpeech = out.isSpeech;
1134
1373
  respondJson(res, 200, body);
1135
1374
  }).catch((e) => {
1136
- console.warn(`[dsh-voice-mode] asr decode failed: ${String(e)}`);
1375
+ console.warn(`[dsh-voice-mode] asr decode failed: ${redactSecrets(e)}`);
1137
1376
  respondJson(res, 500, { code: "internal", error: "internal error" });
1138
1377
  });
1139
1378
  });
1140
1379
  }
1141
1380
 
1381
+ // src/asr-replacements.ts
1382
+ import z from "@deepseek-ai/schemastery";
1383
+ var AsrReplacementSchema = z.object({
1384
+ from: z.array(z.string()).description('Spellings the recognizer produces, e.g. ["sakeena"]; case-insensitive, whitespace between Latin and CJK text ignored.'),
1385
+ to: z.string().description('The spelling you want, e.g. "Sakina".')
1386
+ });
1387
+ var ASCII_WORD = /[A-Za-z0-9]/;
1388
+ var escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1389
+ function patternOf(heard) {
1390
+ const chars = [...heard.replace(/\s+/g, " ").trim()];
1391
+ if (chars.length === 0) return null;
1392
+ let body = "";
1393
+ let prev = "";
1394
+ let spaced = false;
1395
+ for (const ch of chars) {
1396
+ if (ch === " ") {
1397
+ spaced = true;
1398
+ continue;
1399
+ }
1400
+ if (prev && (spaced || ASCII_WORD.test(prev) !== ASCII_WORD.test(ch))) body += "\\s*";
1401
+ body += escapeRegExp(ch);
1402
+ prev = ch;
1403
+ spaced = false;
1404
+ }
1405
+ const first = [...heard.trim()][0];
1406
+ const trimmed = [...heard.trim()];
1407
+ const last = trimmed[trimmed.length - 1];
1408
+ const head = ASCII_WORD.test(first) ? "(?<![A-Za-z0-9])" : "";
1409
+ const tail = ASCII_WORD.test(last) ? "(?![A-Za-z0-9])" : "";
1410
+ return `${head}${body}${tail}`;
1411
+ }
1412
+ function createAsrReplacer(rules, onHit) {
1413
+ const entries = [];
1414
+ rules.forEach((rule, ruleIndex) => {
1415
+ if (!rule.to) return;
1416
+ for (const heard of rule.from) {
1417
+ const pattern = patternOf(heard);
1418
+ if (!pattern) continue;
1419
+ entries.push({
1420
+ pattern,
1421
+ key: heard.replace(/\s+/g, "").toLowerCase(),
1422
+ to: rule.to,
1423
+ length: heard.replace(/\s+/g, "").length,
1424
+ ruleIndex
1425
+ });
1426
+ }
1427
+ });
1428
+ if (entries.length === 0) return (text) => text;
1429
+ entries.sort((a, b) => b.length - a.length);
1430
+ const targets = /* @__PURE__ */ new Map();
1431
+ for (const e of entries) if (!targets.has(e.key)) targets.set(e.key, { to: e.to, ruleIndex: e.ruleIndex });
1432
+ const regex = new RegExp(entries.map((e) => `(?:${e.pattern})`).join("|"), "giu");
1433
+ return (text, countHit = true) => {
1434
+ if (!text) return text;
1435
+ return text.replace(regex, (match) => {
1436
+ const hit = targets.get(match.replace(/\s+/g, "").toLowerCase());
1437
+ if (!hit) return match;
1438
+ if (onHit && countHit) onHit(hit.ruleIndex);
1439
+ return hit.to;
1440
+ });
1441
+ };
1442
+ }
1443
+
1142
1444
  // src/segmenter.ts
1143
1445
  var SKIP_PREFIX = /^[\s.,,、::;;!?!?)\])"'”’〉》】]+$/;
1144
1446
  function plainText(text) {
@@ -1284,14 +1586,27 @@ var STRIP_RE = new RegExp(EMOTION_TAG_PATTERN, "gi");
1284
1586
  function stripEmotionTags(raw) {
1285
1587
  return raw.replace(STRIP_RE, " ");
1286
1588
  }
1589
+ var MAX_BREAK_MS = 5e3;
1590
+ var MAX_TOTAL_BREAK_MS = 1e4;
1287
1591
  function parseEmotionTags(raw) {
1288
1592
  const out = [];
1289
1593
  let buf = "";
1290
1594
  let whisper = false;
1291
1595
  let pendingBreakMs = 0;
1596
+ let totalBreakMs = 0;
1597
+ let sawInlineTag = false;
1598
+ const appendText = (chunk) => {
1599
+ if (chunk.length === 0) return;
1600
+ if (sawInlineTag && /[A-Za-z0-9]$/.test(buf) && /^[A-Za-z0-9]/.test(chunk)) {
1601
+ buf += " ";
1602
+ }
1603
+ sawInlineTag = false;
1604
+ buf += chunk;
1605
+ };
1292
1606
  const flush = () => {
1293
1607
  const t = buf.trim();
1294
1608
  buf = "";
1609
+ sawInlineTag = false;
1295
1610
  if (t.length === 0) return;
1296
1611
  const seg = { text: t, whisper };
1297
1612
  out.push(seg);
@@ -1299,12 +1614,19 @@ function parseEmotionTags(raw) {
1299
1614
  let lastEnd = 0;
1300
1615
  for (const m of raw.matchAll(TAG_RE)) {
1301
1616
  const idx = m.index ?? 0;
1302
- buf += raw.slice(lastEnd, idx);
1617
+ appendText(raw.slice(lastEnd, idx));
1303
1618
  lastEnd = idx + m[0].length;
1304
1619
  const tag = (m[1] ?? "").toLowerCase().trim();
1305
1620
  if (tag.startsWith("break")) {
1306
- const ms = Number(m.groups?.ms ?? 0);
1307
- if (!Number.isFinite(ms) || ms <= 0) continue;
1621
+ const rawMs = Number(m.groups?.ms ?? 0);
1622
+ if (!Number.isFinite(rawMs) || rawMs <= 0) continue;
1623
+ const remaining = Math.max(0, MAX_TOTAL_BREAK_MS - totalBreakMs);
1624
+ const ms = Math.min(rawMs, MAX_BREAK_MS, remaining);
1625
+ if (ms <= 0) {
1626
+ if (buf.trim().length > 0) flush();
1627
+ continue;
1628
+ }
1629
+ totalBreakMs += ms;
1308
1630
  if (buf.trim().length > 0) {
1309
1631
  flush();
1310
1632
  }
@@ -1322,9 +1644,10 @@ function parseEmotionTags(raw) {
1322
1644
  flush();
1323
1645
  whisper = false;
1324
1646
  } else {
1647
+ sawInlineTag = true;
1325
1648
  }
1326
1649
  }
1327
- buf += raw.slice(lastEnd);
1650
+ appendText(raw.slice(lastEnd));
1328
1651
  flush();
1329
1652
  if (pendingBreakMs > 0) {
1330
1653
  const last = out[out.length - 1];
@@ -1365,9 +1688,29 @@ function isEmptyAudio(buf) {
1365
1688
  var EdgeTtsEngine = class {
1366
1689
  voice;
1367
1690
  rate;
1368
- constructor(voice = "zh-CN-XiaoxiaoNeural", rate) {
1691
+ /** 在途连接→每调用独立中止态:并发试听与朗读不互相清零 aborted,interrupt/close 即时生效(I9)。 */
1692
+ active = /* @__PURE__ */ new Map();
1693
+ /** 便于单测注入打桩(默认真实 msedge-tts)。 */
1694
+ createTts;
1695
+ constructor(voice = "zh-CN-XiaoxiaoNeural", rate, createTts) {
1369
1696
  this.voice = voice;
1370
1697
  this.rate = rate;
1698
+ this.createTts = createTts ?? (() => new MsEdgeTTS());
1699
+ }
1700
+ /**
1701
+ * 立刻中止在途合成:关闭底层连接并置位每调用中止标志 → audioStream 结束 → synthesize 必以错误返回。
1702
+ * 此前该引擎没有 interrupt,cancel 只能等库超时(连接 10s / 合成无活动 60s),
1703
+ * 「停止朗读」后最长 60s 仍在合成。
1704
+ */
1705
+ interrupt() {
1706
+ for (const [t, state] of this.active) {
1707
+ state.aborted = true;
1708
+ try {
1709
+ void t.close();
1710
+ } catch {
1711
+ }
1712
+ }
1713
+ this.active.clear();
1371
1714
  }
1372
1715
  mime = "audio/mpeg";
1373
1716
  updateVoice(voice, rate) {
@@ -1377,20 +1720,28 @@ var EdgeTtsEngine = class {
1377
1720
  async synthesize(text, options = {}) {
1378
1721
  const spoken = escapeXmlText(stripEmotionTags(text));
1379
1722
  if (spoken.trim() === "") return Buffer.alloc(0);
1380
- const tts = new MsEdgeTTS();
1723
+ const tts = this.createTts();
1724
+ const state = { aborted: false };
1725
+ this.active.set(tts, state);
1381
1726
  try {
1382
1727
  await tts.setMetadata(
1383
1728
  options.voice ?? this.voice,
1384
1729
  OUTPUT_FORMAT.AUDIO_24KHZ_48KBITRATE_MONO_MP3,
1385
1730
  TTS_METADATA
1386
1731
  );
1732
+ if (state.aborted) throw new Error("tts interrupted");
1387
1733
  const { audioStream } = tts.toStream(spoken, prosodyFromRate(options.rate ?? this.rate));
1388
1734
  const chunks = [];
1389
- for await (const chunk of audioStream) chunks.push(chunk);
1735
+ for await (const chunk of audioStream) {
1736
+ if (state.aborted) throw new Error("tts interrupted");
1737
+ chunks.push(chunk);
1738
+ }
1739
+ if (state.aborted) throw new Error("tts interrupted");
1390
1740
  const buf = Buffer.concat(chunks);
1391
1741
  if (!isValidMp3(buf)) throw new Error("empty or invalid audio");
1392
1742
  return buf;
1393
1743
  } finally {
1744
+ this.active.delete(tts);
1394
1745
  try {
1395
1746
  await tts.close();
1396
1747
  } catch {
@@ -1398,6 +1749,7 @@ var EdgeTtsEngine = class {
1398
1749
  }
1399
1750
  }
1400
1751
  async close() {
1752
+ this.interrupt();
1401
1753
  }
1402
1754
  };
1403
1755
  var edgeVoicesCache = null;
@@ -1465,12 +1817,11 @@ var TtsQueue = class {
1465
1817
  engine;
1466
1818
  /** TTS 全体不可达通知(每会话去重,成功后复位)。 */
1467
1819
  onError;
1468
- /** 单句合成重试耗尽被跳过通知(每句一次;此前是静默丢句——真机「回复偶尔不朗读」根因之一)。 */
1820
+ /** 单句合成重试耗尽被跳过通知;onRetry 为单句重试进度通知,synthBudgetMs 为单句重试总预算。 */
1469
1821
  onSkip;
1470
- /** 某会话队列跑空(无在途、无积压):「说完就关」据此判定朗读真正结束——客户端只能看到
1471
- * 句间的播放空档,分不清「后面还有句子在合成」与「已全部读完」。
1472
- *
1473
- * R15(Issue #15 Important-2):本回调的口径取决于 awaitTurnEnd,见下方 openTurns。 */
1822
+ onRetry;
1823
+ synthBudgetMs;
1824
+ /** 某会话队列跑空(无在途、无积压):「说完就关」据此判定朗读真正结束;口径见 openTurns。 */
1474
1825
  onIdle;
1475
1826
  /**
1476
1827
  * R15(Issue #15 Important-2):回合闸门——「队列排空」≠「回合结束」。
@@ -1517,21 +1868,33 @@ var TtsQueue = class {
1517
1868
  * 前三处:asr-host senseP、listEdgeVoices、warmupSense;第四处 backoffTimers)。
1518
1869
  */
1519
1870
  retryTimers = /* @__PURE__ */ new Set();
1520
- /** R13:可取消的重试 sleep——句柄入集供 close() 取消;落定即自摘。 */
1871
+ clearBackoff(q) {
1872
+ if (q.backoffTimer !== void 0) {
1873
+ clearTimeout(q.backoffTimer);
1874
+ this.backoffTimers.delete(q.backoffTimer);
1875
+ q.backoffTimer = void 0;
1876
+ }
1877
+ }
1878
+ /** R13 + I8:可取消的重试 sleep——句柄入集供 close() 取消并立刻 resolve,防止 pump 永久挂死。 */
1521
1879
  retrySleep(ms) {
1522
1880
  if (this.closed) return Promise.resolve();
1523
1881
  return new Promise((resolve) => {
1524
- const timer = setTimeout(() => {
1525
- this.retryTimers.delete(timer);
1526
- resolve();
1527
- }, ms);
1528
- this.retryTimers.add(timer);
1882
+ const entry = {
1883
+ timer: setTimeout(() => {
1884
+ this.retryTimers.delete(entry);
1885
+ resolve();
1886
+ }, ms),
1887
+ resolve
1888
+ };
1889
+ this.retryTimers.add(entry);
1529
1890
  });
1530
1891
  }
1531
1892
  constructor(options) {
1532
1893
  this.engine = options.engine;
1533
1894
  this.onError = options.onError;
1534
1895
  this.onSkip = options.onSkip;
1896
+ this.onRetry = options.onRetry;
1897
+ this.synthBudgetMs = options.synthBudgetMs ?? 6e3;
1535
1898
  this.onIdle = options.onIdle;
1536
1899
  this.awaitTurnEnd = options.awaitTurnEnd === true;
1537
1900
  }
@@ -1547,8 +1910,8 @@ var TtsQueue = class {
1547
1910
  noteTurnEnd(sessionId) {
1548
1911
  if (this.closed) return;
1549
1912
  this.openTurns.delete(sessionId);
1550
- if (!this.awaitTurnEnd) return;
1551
- if (!this.isIdle(sessionId)) return;
1913
+ if (this.isIdle(sessionId)) this.queues.delete(sessionId);
1914
+ if (!this.awaitTurnEnd || !this.isIdle(sessionId)) return;
1552
1915
  try {
1553
1916
  this.onIdle?.(sessionId);
1554
1917
  } catch {
@@ -1585,6 +1948,7 @@ var TtsQueue = class {
1585
1948
  */
1586
1949
  abandonTurn(sessionId) {
1587
1950
  this.openTurns.delete(sessionId);
1951
+ if (this.isIdle(sessionId)) this.queues.delete(sessionId);
1588
1952
  }
1589
1953
  /** 当前引擎音频 MIME(/preview 的 Content-Type 也用它)。 */
1590
1954
  get mime() {
@@ -1611,8 +1975,12 @@ var TtsQueue = class {
1611
1975
  const old = this.engine;
1612
1976
  this.engine = engine;
1613
1977
  for (const q of this.queues.values()) {
1978
+ this.clearBackoff(q);
1614
1979
  q.epoch++;
1615
1980
  q.pending.length = 0;
1981
+ q.failStreak = 0;
1982
+ q.errorNotified = false;
1983
+ q.backoff = 0;
1616
1984
  }
1617
1985
  void old.close().catch(() => {
1618
1986
  });
@@ -1640,6 +2008,17 @@ var TtsQueue = class {
1640
2008
  if (this.closed) throw new Error("tts queue closed");
1641
2009
  return this.engine.synthesize(text, options);
1642
2010
  }
2011
+ /**
2012
+ * 一次性合成并返回 MIME(试听/自测用)。
2013
+ * A2 审计 Important:不能 await 之后再读 engine.mime——引擎级「最近一次」状态在
2014
+ * 试听与朗读并发时会串味,客户端按错容器解码,整句无声。
2015
+ */
2016
+ async synthesizeWithMime(text, options = {}) {
2017
+ if (this.closed) throw new Error("tts queue closed");
2018
+ const withMime = this.engine.synthesizeWithMime;
2019
+ if (withMime) return withMime.call(this.engine, text, options);
2020
+ return { buf: await this.engine.synthesize(text, options), mime: this.engine.mime };
2021
+ }
1643
2022
  subscribe(listener) {
1644
2023
  this.listeners.add(listener);
1645
2024
  return () => {
@@ -1680,16 +2059,20 @@ var TtsQueue = class {
1680
2059
  */
1681
2060
  cancel(sessionId) {
1682
2061
  const q = this.queues.get(sessionId);
2062
+ const wasBusy = Boolean(q?.busy);
1683
2063
  if (q) {
2064
+ this.clearBackoff(q);
1684
2065
  q.epoch++;
1685
2066
  q.pending.length = 0;
1686
2067
  }
1687
- if (![...this.queues].some(([sid, other]) => sid !== sessionId && other.busy)) this.engine.interrupt?.();
2068
+ const othersBusy = [...this.queues].some(([sid, other]) => sid !== sessionId && other.busy);
2069
+ if (wasBusy && !othersBusy) this.engine.interrupt?.();
1688
2070
  }
1689
2071
  /** 会话退出/被抢占时彻底清理其队列(防止 Map 长期累积)。 */
1690
2072
  prune(sessionId) {
1691
2073
  const q = this.queues.get(sessionId);
1692
2074
  if (q) {
2075
+ this.clearBackoff(q);
1693
2076
  q.epoch++;
1694
2077
  q.pending.length = 0;
1695
2078
  }
@@ -1697,24 +2080,41 @@ var TtsQueue = class {
1697
2080
  this.queues.delete(sessionId);
1698
2081
  }
1699
2082
  async pump(sessionId, q) {
1700
- if (this.closed || q.busy) return;
2083
+ if (this.closed || q.busy || q.backoffTimer !== void 0) return;
1701
2084
  q.busy = true;
1702
2085
  try {
1703
2086
  while (q.pending.length > 0) {
1704
2087
  if (this.closed) break;
1705
2088
  const item = q.pending.shift();
1706
2089
  const MAX_SYNTH_ATTEMPTS = 3;
2090
+ const startedAt = Date.now();
1707
2091
  let buf = null;
2092
+ let frameMime = null;
1708
2093
  for (let attempt = 0; attempt < MAX_SYNTH_ATTEMPTS; attempt++) {
1709
2094
  if (item.epoch !== q.epoch) break;
1710
2095
  if (this.closed) break;
1711
2096
  try {
1712
- buf = await this.engine.synthesize(item.text);
2097
+ const withMime = this.engine.synthesizeWithMime;
2098
+ if (withMime) {
2099
+ const r = await withMime.call(this.engine, item.text);
2100
+ buf = r.buf;
2101
+ frameMime = r.mime;
2102
+ } else {
2103
+ buf = await this.engine.synthesize(item.text);
2104
+ }
1713
2105
  break;
1714
2106
  } catch (e) {
1715
- console.warn(`[dsh-voice-mode] synthesis failed (${attempt + 1}/${MAX_SYNTH_ATTEMPTS}): ${String(e)}`);
1716
- if (attempt < MAX_SYNTH_ATTEMPTS - 1) {
1717
- await this.retrySleep(400 * (attempt + 1));
2107
+ console.warn(`[dsh-voice-mode] synthesis failed (${attempt + 1}/${MAX_SYNTH_ATTEMPTS}): ${redactSecrets(e)}`);
2108
+ if (item.epoch !== q.epoch || this.closed) break;
2109
+ const sleepMs = 400 * (attempt + 1);
2110
+ if (attempt < MAX_SYNTH_ATTEMPTS - 1 && Date.now() - startedAt + sleepMs < this.synthBudgetMs) {
2111
+ try {
2112
+ this.onRetry?.(sessionId, attempt + 2, MAX_SYNTH_ATTEMPTS);
2113
+ } catch {
2114
+ }
2115
+ await this.retrySleep(sleepMs);
2116
+ } else {
2117
+ break;
1718
2118
  }
1719
2119
  }
1720
2120
  }
@@ -1723,6 +2123,10 @@ var TtsQueue = class {
1723
2123
  if (buf === null) {
1724
2124
  q.failStreak++;
1725
2125
  this.onSkip?.(sessionId, item.text, q.failStreak);
2126
+ if (q.failStreak >= 2) {
2127
+ q.errorNotified = true;
2128
+ break;
2129
+ }
1726
2130
  continue;
1727
2131
  }
1728
2132
  if (isEmptyAudio(buf)) continue;
@@ -1730,7 +2134,7 @@ var TtsQueue = class {
1730
2134
  q.failStreak = 0;
1731
2135
  q.backoff = 0;
1732
2136
  const sentenceId = this.seq++;
1733
- const mime = this.engine.mime;
2137
+ const mime = frameMime ?? this.engine.mime;
1734
2138
  const dataFrame = {
1735
2139
  sessionId,
1736
2140
  sentenceId,
@@ -1762,7 +2166,7 @@ var TtsQueue = class {
1762
2166
  }
1763
2167
  }
1764
2168
  } catch (e) {
1765
- console.warn(`[dsh-voice-mode] TTS unavailable: sid=${sessionId} err=${String(e)}`);
2169
+ console.warn(`[dsh-voice-mode] TTS unavailable: sid=${sessionId} err=${redactSecrets(e)}`);
1766
2170
  if (!q.errorNotified) {
1767
2171
  q.errorNotified = true;
1768
2172
  this.onError?.(sessionId);
@@ -1778,15 +2182,17 @@ var TtsQueue = class {
1778
2182
  } catch {
1779
2183
  }
1780
2184
  }
1781
- this.queues.delete(sessionId);
2185
+ if (!this.openTurns.has(sessionId)) this.queues.delete(sessionId);
1782
2186
  } else {
1783
- const delay = q.errorNotified ? q.backoff : 0;
2187
+ const delay = q.errorNotified ? Math.max(1e3, q.backoff) : 0;
1784
2188
  q.backoff = Math.min(8e3, delay + 1e3);
1785
2189
  if (delay > 0) {
1786
2190
  const timer = setTimeout(() => {
1787
2191
  this.backoffTimers.delete(timer);
2192
+ if (q.backoffTimer === timer) q.backoffTimer = void 0;
1788
2193
  void this.pump(sessionId, q);
1789
2194
  }, delay);
2195
+ q.backoffTimer = timer;
1790
2196
  this.backoffTimers.add(timer);
1791
2197
  } else void this.pump(sessionId, q);
1792
2198
  }
@@ -1795,9 +2201,13 @@ var TtsQueue = class {
1795
2201
  async close() {
1796
2202
  this.closed = true;
1797
2203
  this.openTurns.clear();
2204
+ for (const q of this.queues.values()) q.backoffTimer = void 0;
1798
2205
  for (const timer of this.backoffTimers) clearTimeout(timer);
1799
2206
  this.backoffTimers.clear();
1800
- for (const timer of this.retryTimers) clearTimeout(timer);
2207
+ for (const entry of this.retryTimers) {
2208
+ clearTimeout(entry.timer);
2209
+ entry.resolve();
2210
+ }
1801
2211
  this.retryTimers.clear();
1802
2212
  await this.engine.close();
1803
2213
  }
@@ -1851,7 +2261,7 @@ function resolveNativeRuntime(opts = {}) {
1851
2261
  }
1852
2262
  result = execPath ? { execPath, env: childEnv } : null;
1853
2263
  }
1854
- if (useCache) cached = result;
2264
+ if (useCache && result !== null) cached = result;
1855
2265
  return result;
1856
2266
  }
1857
2267
 
@@ -2110,7 +2520,9 @@ function createSherpaLocalEngine(options) {
2110
2520
  let closed = false;
2111
2521
  const dlAbort = new AbortController();
2112
2522
  let starting = false;
2113
- const respawnChild = async () => {
2523
+ let initInterrupted = false;
2524
+ const respawnChild = async (userInterrupt = false) => {
2525
+ if (starting && userInterrupt) initInterrupted = true;
2114
2526
  if (child) {
2115
2527
  child.kill();
2116
2528
  child = null;
@@ -2151,11 +2563,19 @@ function createSherpaLocalEngine(options) {
2151
2563
  p.reject(e);
2152
2564
  }
2153
2565
  };
2566
+ let initFailUntil = 0;
2567
+ let initFailError = null;
2568
+ const initCooldownMs = options.initFailureCooldownMs ?? 6e4;
2154
2569
  const ensureReady = () => {
2155
2570
  if (ready && child) return ready;
2571
+ if (ready && !child && !starting) ready = null;
2572
+ if (Date.now() < initFailUntil) {
2573
+ return Promise.reject(initFailError ?? new Error("local TTS engine is in failure cooldown"));
2574
+ }
2156
2575
  if (!ready) {
2157
2576
  ready = (async () => {
2158
2577
  starting = true;
2578
+ initInterrupted = false;
2159
2579
  engineLoading = true;
2160
2580
  engineError = void 0;
2161
2581
  engineErrorCode = void 0;
@@ -2258,6 +2678,10 @@ function createSherpaLocalEngine(options) {
2258
2678
  },
2259
2679
  (e) => {
2260
2680
  ready = null;
2681
+ if (!initInterrupted && !closed) {
2682
+ initFailUntil = Date.now() + initCooldownMs;
2683
+ initFailError = e instanceof Error ? e : new Error(String(e));
2684
+ }
2261
2685
  throw e;
2262
2686
  }
2263
2687
  );
@@ -2302,7 +2726,11 @@ function createSherpaLocalEngine(options) {
2302
2726
  };
2303
2727
  },
2304
2728
  // 设置面板「下载」按钮:无文本也触发模型下载 + 子进程初始化(与首次合成路径一致)。
2305
- prepare: () => ensureReady(),
2729
+ prepare: () => {
2730
+ initFailUntil = 0;
2731
+ initFailError = null;
2732
+ return ensureReady();
2733
+ },
2306
2734
  async synthesize(text, opts = {}) {
2307
2735
  if (closed) throw new Error("local TTS engine closed");
2308
2736
  await ensureReady();
@@ -2371,7 +2799,7 @@ function createSherpaLocalEngine(options) {
2371
2799
  ready = null;
2372
2800
  },
2373
2801
  interrupt() {
2374
- void respawnChild();
2802
+ void respawnChild(true);
2375
2803
  }
2376
2804
  };
2377
2805
  }
@@ -2389,6 +2817,8 @@ function isLoopbackRequest(req) {
2389
2817
  return LOOPBACK_ADDRESSES.has(addr);
2390
2818
  }
2391
2819
  function sameOriginRequest(req) {
2820
+ const sfs = req.headers["sec-fetch-site"];
2821
+ if (typeof sfs === "string" && sfs.toLowerCase() === "cross-site") return false;
2392
2822
  const origin = req.headers.origin;
2393
2823
  if (!origin) return true;
2394
2824
  try {
@@ -2403,6 +2833,8 @@ function sameOriginRequest(req) {
2403
2833
  }
2404
2834
  var RateLimiter = class {
2405
2835
  buckets = /* @__PURE__ */ new Map();
2836
+ /** 每个 key 的窗口(回收到期键时按桶自身窗口判断;修复短窗请求误清长窗桶,2026-11-20 复核)。 */
2837
+ windows = /* @__PURE__ */ new Map();
2406
2838
  maxKeys;
2407
2839
  constructor(maxKeys = 1e4) {
2408
2840
  this.maxKeys = maxKeys;
@@ -2413,21 +2845,27 @@ var RateLimiter = class {
2413
2845
  const cutoff = now - windowMs;
2414
2846
  let bucket = this.buckets.get(key);
2415
2847
  if (!bucket) {
2848
+ if (this.buckets.size >= this.maxKeys) this.prune(now);
2416
2849
  if (this.buckets.size >= this.maxKeys) return false;
2417
2850
  bucket = [];
2418
2851
  this.buckets.set(key, bucket);
2419
2852
  }
2853
+ const prevWindow = this.windows.get(key) ?? 0;
2854
+ if (windowMs > prevWindow) this.windows.set(key, windowMs);
2420
2855
  while (bucket.length > 0 && bucket[0] <= cutoff) bucket.shift();
2421
2856
  if (bucket.length >= maxHits) return false;
2422
2857
  bucket.push(now);
2423
2858
  return true;
2424
2859
  }
2425
- /** 定期清理(由调用方在低频路径触发即可)。 */
2426
- prune(now = Date.now(), windowMs) {
2427
- const cutoff = now - windowMs;
2860
+ /** 定期清理(由调用方在低频路径触发即可):每个桶按自身窗口判断是否全过期。 */
2861
+ prune(now = Date.now(), fallbackWindowMs = 6e4) {
2428
2862
  for (const [key, bucket] of this.buckets) {
2863
+ const cutoff = now - (this.windows.get(key) ?? fallbackWindowMs);
2429
2864
  while (bucket.length > 0 && bucket[0] <= cutoff) bucket.shift();
2430
- if (bucket.length === 0) this.buckets.delete(key);
2865
+ if (bucket.length === 0) {
2866
+ this.buckets.delete(key);
2867
+ this.windows.delete(key);
2868
+ }
2431
2869
  }
2432
2870
  }
2433
2871
  };
@@ -2438,6 +2876,7 @@ var en = {
2438
2876
  ttsNoticeFail: "Read-aloud connection failed: retrying\u2026",
2439
2877
  ttsSkipNotice: "One sentence failed to read and was skipped (resend the message to retry)",
2440
2878
  ttsUnavailableNotice: "Read-aloud keeps failing: cloud TTS is unavailable. Try again later, or switch the read-aloud engine to local VITS / Kokoro in settings",
2879
+ ttsProbeFail: "Read-aloud self-check failed: the cloud endpoint may have changed, or the network is down. Switch to local/another engine in settings, then run Self-test",
2441
2880
  enterFail: "Failed to enter voice mode",
2442
2881
  disabled: "Voice mode disabled (plugin enabled=false)",
2443
2882
  sendFailKept: "Send failed; text kept in draft",
@@ -2457,6 +2896,7 @@ var en = {
2457
2896
  voiceBtn: "Voice",
2458
2897
  ariaActive: "Voice mode active",
2459
2898
  ariaEnter: "Enter voice mode",
2899
+ ariaPendingCancelHint: "activate again to cancel",
2460
2900
  titleHold: "Voice mode \xB7 hold to talk, release to send; tap to exit; Esc/blur cancels; Ctrl+Shift+V exits",
2461
2901
  titleToggle: "Voice mode \xB7 click to exit (Ctrl+Shift+V) \xB7 hold Ctrl while speaking to send now",
2462
2902
  titleEnter: "Enter voice mode (Ctrl+Shift+V)",
@@ -2469,6 +2909,10 @@ var en = {
2469
2909
  sayWake: 'Say "{wake}" to start',
2470
2910
  reading: "Reading aloud\u2026",
2471
2911
  recognitionFail: "Recognition failed, try again",
2912
+ holdTrimmedNotice: "Hold-to-talk exceeded about 48 s: only the last part was recognised (earlier audio was dropped)",
2913
+ utteranceTooLong: "That utterance was too long (over the per-utterance limit, about a minute): skipped \u2014 please speak it again in shorter parts",
2914
+ interruptedNotice: "Playback interrupted \u2014 go ahead",
2915
+ senseDegradedNotice: "Final-pass model failed to load; temporarily using the backup recogniser (accuracy may drop slightly)",
2472
2916
  partialFail: "Live captions temporarily unavailable (recognition channel error, retrying)",
2473
2917
  detectFail: "Break-in detection temporarily unavailable (detect channel error, retrying)",
2474
2918
  sseReconnect: "State sync disconnected, reconnecting\u2026",
@@ -2481,6 +2925,7 @@ var en = {
2481
2925
  startFail: "Voice mode failed to start: {err}",
2482
2926
  holdDots: "Hold to talk\u2026",
2483
2927
  exit: "Exit",
2928
+ micMoreMenu: "Voice quick settings",
2484
2929
  configUnavailableNote: " (settings document not ready; retrying \u2014 the panel will appear when it is).",
2485
2930
  previewNameFirst: "Enter a voice ShortName first",
2486
2931
  previewDisabled: "Voice mode disabled (plugin enabled=false); preview unavailable",
@@ -2495,23 +2940,123 @@ var en = {
2495
2940
  previewBtnTitle: "Preview voice (current rate)",
2496
2941
  synthesizing: "Synthesizing\u2026",
2497
2942
  preview: "Preview",
2943
+ // E1 online presets.
2944
+ openaiPresetLabel: "Online preset",
2945
+ descOpenaiPreset: "Pick a preset to auto-fill base URL and model (usually just enter the API key); choose Custom to enter your own URL/model, or Follow config file to use profile openaiTts values. Click Test read-aloud to test inline",
2946
+ presetCustom: "Follow the config file",
2947
+ presetCustomCustom: "Custom (fill below)",
2948
+ presetCustomHint: "With this selected, configure any OpenAI-compatible service in the Endpoint / Model / API key fields below",
2949
+ openaiAdvancedShow: "Custom endpoint / fallback API key",
2950
+ openaiAdvancedHide: "Hide advanced overrides",
2951
+ voiceServerDefaultOption: "Server default voice",
2952
+ presetCosy: "SiliconFlow \xB7 CosyVoice2",
2953
+ presetFish: "SiliconFlow \xB7 Fish Speech 1.5",
2954
+ presetCosyNote: "About $7.15 per million UTF-8 bytes, ~150ms; text goes to api.siliconflow.cn",
2955
+ presetFishNote: "About $15 per million UTF-8 bytes (billed per UTF-8 byte); text goes to api.siliconflow.cn",
2956
+ presetOpenrouter: "OpenRouter \xB7 OpenAI TTS",
2957
+ presetOpenrouterNote: "Billed through the selected model; text goes to openrouter.ai; OpenAI terms require disclosing that the voice is AI-generated",
2958
+ presetOpenaiOfficial: "OpenAI official \xB7 gpt-4o-mini-tts",
2959
+ presetOpenaiOfficialNote: "Billed at OpenAI list prices; text goes to api.openai.com; OpenAI terms require disclosing that the voice is AI-generated",
2960
+ presetGroq: "Groq \xB7 PlayAI TTS",
2961
+ presetGroqNote: "Billed at Groq prices; text goes to api.groq.com; English voices such as Fritz-PlayAI",
2962
+ presetSelfKokoro: "Self-hosted \xB7 Kokoro-FastAPI",
2963
+ presetSelfKokoroNote: "Local server (default 127.0.0.1:8880); no per-call fee; text stays on your network. You must deploy it first",
2964
+ presetSelfVllm: "Self-hosted \xB7 vLLM-Omni",
2965
+ presetSelfVllmNote: "Local server (default 127.0.0.1:8000); no per-call fee; text stays on your network. You must deploy it first",
2966
+ presetKeyNote: "After picking one, fill the API Key field below (the profile openaiTts.apiKey/apiKeys still work). The key stays on the host and is never sent back to the browser",
2967
+ presetKeySaved: "Saved (panel)",
2968
+ presetKeyFromConfig: "Configured (profile)",
2969
+ presetKeyMissing: "No key",
2970
+ presetDataMissing: "Preset data not loaded (host /presets unavailable): restart the host or reload the page",
2971
+ presetReload: "Reload presets",
2972
+ // 2026-11-19: online TTS is configurable from the settings card (URL/model/key), no profile YAML edit needed.
2973
+ openaiBaseUrlLabel: "Endpoint (base URL)",
2974
+ descOpenaiBaseUrl: "OpenAI-compatible endpoint, usually ending in /v1 (the plugin appends /audio/speech). Empty = use the preset or the profile openaiTts.baseUrl",
2975
+ openaiModelLabel: "Model",
2976
+ descOpenaiModel: "TTS model on that endpoint, e.g. gpt-4o-mini-tts or FunAudioLLM/CosyVoice2-0.5B. Empty = use the preset or the profile",
2977
+ openaiApiKeyLabel: "API key",
2978
+ descOpenaiApiKey: "The key stays on the host (0600 settings file); it is never sent back to the browser and never logged. Empty = use the profile openaiTts.apiKeys[preset]/apiKey; a value here overrides it",
2979
+ openaiApiKeysLabel: "Per-preset keys (follow the preset)",
2980
+ descOpenaiApiKeys: "One key per online preset: whichever preset is selected uses its own key. Empty entries fall back to the global key above, then the profile. Host-side only",
2981
+ mimoApiKeyLabel: "MiMo API key",
2982
+ descMimoApiKey: "Xiaomi MiMo key (sent as the api-key header, not Bearer). Host-side only; empty = use the profile mimoTts.apiKey",
2983
+ secretSaved: "Saved",
2984
+ secretSaveFailed: "Save failed: the host did not accept it (check for policy restrictions)",
2985
+ secretKeep: "Saved (leave empty to keep)",
2986
+ secretClear: "Clear",
2987
+ secretClearing: "Clearing\u2026",
2988
+ secretHintBrowser: "Typed values go straight to the local host and are stored with 0600; never written to chat or logs",
2989
+ secretPlaceholderEmpty: "Paste the key (after saving only Saved is shown)",
2990
+ secretCleared: "Cleared",
2991
+ secretClearedConfigRemains: "Removed the key from settings; the config file (openaiTts/mimoTts) still has one and will keep using it",
2992
+ // P1-4 dictation-only preset.
2993
+ // P1-3 correction wordlist.
2994
+ replTitle: "Correction wordlist",
2995
+ replFromPh: "Misheard spellings, comma-separated",
2996
+ replToPh: "Wanted spelling",
2997
+ replAdd: "Add",
2998
+ replDelete: "Del",
2999
+ replEmpty: "No rules yet",
3000
+ replHits: "hits",
3001
+ replExport: "Export",
3002
+ replImport: "Import",
3003
+ replInvalid: "Invalid rule: non-empty from and to, comma-separate multiple spellings",
3004
+ replBadFile: "File is not a valid wordlist JSON (array [{from[], to}], max 200 rules)",
3005
+ replUnreadable: "The stored wordlist is unreadable or over the limit; editing is disabled to avoid overwriting it. Export a backup first, then import a new wordlist",
3006
+ replSaveFail: "Save failed (nothing was written); rules unchanged. Check whether the plugin is disabled or the settings store is read-only",
3007
+ replTooLarge: "Wordlist is too large (over ~12KB): reduce the number of rules or shorten the spellings",
3008
+ // P1-1 self-test: separate synthesis / playback verdicts.
3009
+ selftestTitle: "Test read-aloud",
3010
+ selftestHint: "Synthesize and play once: it speaks on success, and points to the engine, key or network on failure",
3011
+ selftestRun: "Test read-aloud",
3012
+ selftestRunning: "Testing\u2026",
3013
+ selftestSynth: "Synthesis",
3014
+ selftestPlay: "Playback",
3015
+ selftestOk: "OK",
3016
+ selftestFail: "Failed",
3017
+ selftestCheck: "Self-test failed: check network, engine status, or voice name",
3018
+ selftestTimeout: "Synthesis timed out: model still loading, retry self-test in a few seconds",
3019
+ selftestAutoplay: "Browser blocked autoplay \u2014 run self-test again",
3020
+ selftestRateLimited: "Preview requests are rate limited (20/min shared with Preview): wait a few seconds and run self-test again",
3021
+ selftestDisabled: "Voice mode is disabled (plugin enabled=false), so the self-test cannot run",
3022
+ switchToLocalTts: "Switch to local Kokoro (first use downloads ~109MB, then works offline)",
2498
3023
  custom: "Custom",
2499
3024
  voicePrev: "Previous voice",
2500
3025
  voiceNext: "Next voice",
2501
3026
  descVoice: "Edge cloud voices (auto-loads all Microsoft voices; common Chinese voices pinned on top; \u25C0\u25B6 or dropdown; custom ShortName allowed)",
2502
3027
  descVoiceLocal: "Local voice (vits, all 5 speakers listed; dropdown or \u25C0\u25B6; no custom needed)",
2503
- descTtsEngine: "Local VITS (Chinese only) / Local Kokoro (Chinese + English) / Edge cloud (most natural, text sent to Microsoft) / OpenAI-compatible server (self-hosted or hosted, text sent to the configured URL)",
3028
+ descTtsEngine: "Local VITS (Chinese only) / Local Kokoro (Chinese + English) / Edge cloud (most natural, text sent to Microsoft) / OpenAI-compatible server (self-hosted or hosted, text sent to the configured URL) / Xiaomi MiMo (TTS series free for a limited time, text sent to Xiaomi)",
2504
3029
  engineVits: "Local VITS",
2505
3030
  engineKokoro: "Local Kokoro",
2506
3031
  engineEdge: "Edge cloud",
2507
3032
  engineOpenai: "OpenAI-compatible",
2508
- descVoiceOpenai: "Voice name on the server (empty = openaiTts.voice from the config)",
3033
+ engineMimo: "Xiaomi MiMo",
3034
+ descVoiceOpenai: "Pick the online preset above first, then pick a voice from that service list below; for a custom endpoint, empty means the server default voice. A typed value overrides the list",
3035
+ descVoiceMimo: "MiMo preset voice id (empty = mimoTts.voice from the config, default mimo_default). Presets: mimo_default, Mia, Chloe, Milo, Dean, plus four Chinese-named voices (Bingtang/Moli/Suda/Baihua) \u2014 enter them by their native Chinese names as listed on the MiMo docs",
2509
3036
  engineRemoteDown: "server unavailable",
3037
+ errMimoKeyMissing: "MiMo API key is not configured: enter it in this settings card or set mimoTts.apiKey in the profile",
3038
+ engineUnavailableShort: "Unavailable",
3039
+ errOpenaiConfigMissing: "Endpoint is not configured yet: pick a provider under Online preset (usually only the key is needed), or choose Custom and fill the endpoint and model",
3040
+ engineMissingKey: "API key missing",
3041
+ rowInfo: "Details",
3042
+ voiceDefaultOption: "Default ({name})",
3043
+ voiceCurrentOption: "Current ({name})",
3044
+ segInput: "Voice input",
3045
+ segReadAloud: "Read aloud",
3046
+ segDisplay: "Display & interaction",
3047
+ segAdvanced: "Advanced",
3048
+ segListLabel: "Settings sections",
3049
+ segTuning: "Tuning & troubleshooting",
3050
+ segReplacements: "Corrections",
3051
+ errApiKeyMissingHint: "Read-aloud requires an API key: fill the key above and click Test read-aloud, or switch to a local engine",
3052
+ ttsKeyMissingNotice: "Online read-aloud has no API key: recognition and captions work, but speech will fail. Fill the key under Settings \u2192 Voice mode, or switch to a local engine (Edge / local VITS / Kokoro)",
3053
+ ttsProbeAuthFail: "The service rejected read-aloud (usually a missing or invalid API key): fill or update the key under Settings \u2192 Voice mode, or switch to a local engine",
3054
+ previewAuth: "The server rejected authentication: API key missing or invalid",
2510
3055
  errRemoteTts: "The TTS server is unreachable, failing or too slow; the local fallback reads aloud meanwhile if one is configured",
2511
3056
  descVoiceKokoro: "Kokoro zh-en voices (103; \u25C0\u25B6 to cycle; 48-51 named Chinese, others numbered with measured gender; mixed zh-en supported)",
2512
3057
  descRate: "Speech rate (0.5 slow \u2013 2.0 fast, 1.1 default; more compact replies)",
2513
3058
  descInterrupt: "Interrupt sensitivity (0 high \u22480.3 s confirm / 1 medium \u22480.2 s / 2 low \u22480.1 s, most responsive); lower = higher barrier = harder to interrupt",
2514
- descBargeIn: "Barge-in mode (detect: auto-probe native echo cancellation, fall back to hold-to-talk when inactive \u2014 default; auto: force interrupt by speaking \u2014 headphones/quiet; manual: for loudspeaker, no echo-triggered self-interrupt \u2014 hold mic/Ctrl to interrupt). Note: in manual mode (including detect falling back to manual on machines without native echo cancellation) audio outside a press is not recognized \u2014 in toggle mode you can long-press to speak only while the agent is playing; when idle there is no voice input, so use hold mode or switch to auto/detect",
3059
+ descBargeIn: "Barge-in mode (detect: auto-probe native echo cancellation and switch playback to hold-to-interrupt when inactive \u2014 default; auto: force interrupt by speaking \u2014 headphones/quiet; manual: recommended for speakers \u2014 speak directly or say the wake word when idle, and hold mic/Ctrl to interrupt while the agent is playing so speaker echo never self-interrupts)",
2515
3060
  bargeInDetect: "Auto-detect",
2516
3061
  bargeInAuto: "Auto",
2517
3062
  bargeInManual: "Manual",
@@ -2521,7 +3066,7 @@ var en = {
2521
3066
  aecOff: "Native AEC off",
2522
3067
  aecOffHint: "Native echo cancellation is not active (speaker echo may self-interrupt); use headphones or Manual barge-in",
2523
3068
  // 批 7O(ADR-0006):detect 模式第一级探测降级提示(英文)。
2524
- bargeInDetectFallback: "Native echo cancellation is off \u2014 switched to hold-to-talk barge-in",
3069
+ bargeInDetectFallback: "Native echo cancellation is off: speak directly when idle, hold to interrupt playback",
2525
3070
  // R1 收尾(fix-client 直连 tk() 调用):连续 3 次回声拒断的解释出口 + 快捷键非法停用提示。
2526
3071
  echoRejectHint: "Strong echo detected \u2014 barge-in is limited by echo protection. Use headphones or switch to manual barge-in",
2527
3072
  shortcutInvalid: "Invalid shortcut, disabled. Fix it in settings (e.g. Ctrl+Shift+V); leave empty to use the mic button only",
@@ -2567,9 +3112,21 @@ var en = {
2567
3112
  captionWidth70: "Medium",
2568
3113
  captionWidth90: "Wide",
2569
3114
  skipReading: "Skip this sentence",
3115
+ captionHistoryOpen: "History ({count})",
3116
+ captionHistoryHide: "Collapse",
3117
+ captionDismiss: "Close captions",
3118
+ tabSwitchFlushedNotice: "Speech before tab switch was finalized into draft",
3119
+ sessionSwitchFlushedNotice: "Speech from previous session saved; restores to draft on return",
3120
+ ttsRetryingNotice: "Retrying read-aloud ({attempt}/{max})\u2026",
3121
+ tabPreemptedNotice: "Voice mode was taken over by another tab",
3122
+ firstUseToggle: "Speak directly \u2014 pauses commit and send; speak or hold the mic to interrupt replies",
3123
+ firstUseHold: "Hold the mic button or Ctrl to speak, release to send, or slide up to cancel",
3124
+ firstUseOnce: "Speak one request \u2014 it sends after a pause and exits once the reply finishes reading",
3125
+ firstUseWake: 'Say the wake word "{wake}" to start speaking (or say it together with your request)',
2570
3126
  descBackchannelYield: 'When the user says a short answer like "mm-hmm/right" while the agent is reading aloud, yield automatically (skip the current TTS sentence + drop frames for 1.5s; if the user really wants to speak, the existing hardBreak takes over; off = no yielding, behavior matches before this change). Only triggers in hold-to-talk mode: in continuous-listening mode speech is not recognized during playback (speaking is treated as an interrupt)',
2571
3127
  // Issue #15 batch 1 / ADR-0012: barge-in speech salvage.
2572
3128
  descBargeInSalvage: "When you speak to interrupt while the agent is reading aloud, keep what you said from speech onset to break confirmation and merge it into recognition (fixes swallowed break-in speech; off = discard pre-break audio; recommended off only on speakers without echo cancellation)",
3129
+ descAsrReplacements: 'User correction wordlist (JSON array [{from:["misheard"],to:"wanted"}], rewritten after transcription; add/remove and import/export in the settings card. The number after each rule is its hit count since the last apply)',
2573
3130
  descLlmCorrect: "Before sending, run one LLM pass over the whole transcribed text (typos/homophones/punctuation only, meaning preserved; requires a default model configured in the host \u2014 otherwise the original text is sent as-is). On = one extra correction round trip per message: usually under 1 second, at most ~10 seconds; at most 10 times per minute \u2014 when voice mode is off or the limit is hit, the original text is sent. Failed or abnormal output also falls back to the original text",
2574
3131
  descYieldMs: "How long (ms) to drop frames after a yield trigger (500-3000, default 1500; within the window the existing hardBreak takes over if the user really wants to speak; auto-resume after the window expires). Hold-to-talk mode only, during playback",
2575
3132
  descMode: "Interaction mode (toggle: continuous listen + auto-send / hold: press to talk / once: one utterance, then exit after the reply is read aloud)",
@@ -2586,9 +3143,9 @@ var en = {
2586
3143
  descShowCaptions: "Show a floating caption of the current sentence while reading aloud",
2587
3144
  showStatusBarLabel: "Status bar",
2588
3145
  descShowStatusBar: "Show the voice status bar above the composer (waveform, transcript, timer, notices, exit); when off, state shows only on the mic button",
2589
- descWakeWord: 'Wake word (default off; e.g. "Hey D"): recognition starts only after you say it, to avoid accidental triggers. You may say it together with your command ("Hey D, check the weather" \u2014 the wake word is stripped and never sent); it must be repeated after each utterance split or barge-in; toggle mode only (inactive in hold / manual barge-in \u2014 and equally inactive when the detect probe fails and falls back to manual, the default on machines without native echo cancellation such as Safari); saying it while the agent is reading does not trigger (barge-in stays VAD-based). Fault-tolerant matching (homophones / leading fillers); 3-4 characters recommended; not a dedicated KWS engine \u2014 noisy environments may delay or falsely trigger',
3146
+ descWakeWord: 'Wake word (default off; e.g. "Hey D"): recognition starts only after you say it, to avoid accidental triggers. You may say it together with your command ("Hey D, check the weather" \u2014 the wake word is stripped and never sent); it must be repeated after each utterance split or barge-in; inactive in hold-to-talk mode (in manual barge-in or when detect falls back to manual, the wake word still works when idle while playback requires holding mic/Ctrl to interrupt). Fault-tolerant matching (homophones / leading fillers); 3-4 characters recommended; not a dedicated KWS engine \u2014 noisy environments may delay or falsely trigger',
2590
3147
  wakePlaceholder: "e.g. Hey D",
2591
- settingsCardDesc: "Engine / voice / rate / interrupt / barge-in / echo gate / silence / idle / model host / auto-send / read replies / status bar / caption overlay / auto-resume / mode / wake word / tool beep / ITN / caption font / caption width / yielding / yield window / barge-in salvage / LLM correction",
3148
+ settingsCardDesc: "Local recognition plus sentence-by-sentence read-aloud; speak to interrupt. Four sections: voice input, read aloud, display & interaction, advanced. Changes apply instantly.",
2592
3149
  settingsEffectiveNote: "When settings apply, in four tiers: \u2460 immediately \u2014 engine / voice / rate / Kokoro model precision (immediate when cached, else next download) / spoken format (applies to later replies) / read replies / status bar / caption overlay / model mirror (next download attempt); \u2461 next recognition \u2014 finalization re-transcription (SenseVoice) / ITN; \u2462 next utterance \u2014 silence threshold (endpoint; the send wait stays a fixed 1.2s); \u2463 next time you enter voice mode \u2014 interrupt sensitivity / barge-in mode / echo gate / shortcut / auto-send / auto-resume / interaction mode / wake word / tool beep / caption font / caption width / backchannel yielding / yield window / barge-in salvage / LLM correction / idle timeout. Items that take effect next time you enter voice mode are listed at the top of this card with their current effective values.",
2593
3150
  effectivePending: "{count} change(s) will apply next time you enter voice mode: {items}",
2594
3151
  valueOn: "On",
@@ -2618,6 +3175,7 @@ var en = {
2618
3175
  modelsRetrying: "Retrying\u2026",
2619
3176
  modelsRetryHint: "Click to retry now after switching mirror or a failure",
2620
3177
  modelsHint: "Live download state; failures auto-backoff 60s. After switching the mirror, click Retry to take effect immediately; npm run prefetch pre-downloads.",
3178
+ modelActionFailed: "Action did not take effect: the host rejected it (retry later or check host logs)",
2621
3179
  engineLoading: "loading\u2026",
2622
3180
  engineReady: "ready",
2623
3181
  engineError: "failed",
@@ -2628,7 +3186,7 @@ var en = {
2628
3186
  ttsDownloading: "Downloading\u2026",
2629
3187
  ttsDeleting: "Deleting\u2026",
2630
3188
  ttsDownloadHint: "Download this engine's local model; becomes ready immediately after",
2631
- dataFlowHint: "Data flow: ASR recognition (zipformer2+SenseVoice) is always local; TTS playback depends on engine (edge=Microsoft cloud, vits/kokoro=local)",
3189
+ dataFlowHint: "Data flow: ASR recognition (zipformer2+SenseVoice) is always local; TTS playback depends on engine (edge=Microsoft cloud, openai/mimo=third-party cloud, vits/kokoro=local)",
2632
3190
  ttsDeleteHint: "Delete local models (frees space; auto re-downloads on next use)",
2633
3191
  kokoroModelInt8: "int8 (default)",
2634
3192
  kokoroModelFp32: "fp32 (better quality)",
@@ -2758,18 +3316,30 @@ async function correctText(ctx, text, lang) {
2758
3316
  const sel = ctx?.get?.("agentDefaultModel")?.currentSelection?.();
2759
3317
  if (!llm || typeof llm.stream !== "function") return text;
2760
3318
  if (!sel?.provider || !sel?.model) return text;
2761
- const stream = llm.stream({
2762
- provider: sel.provider,
2763
- model: sel.model,
2764
- system: correctionSystem(lang),
2765
- // host 侧自弃 10s(早于客户端 12s,审查 M3):超时后流抛错→catch→回退原文,
2766
- // 客户端不必等自己的 AbortSignal.timeout 才拿到响应(省 token 与等待)。
2767
- signal: AbortSignal.timeout(1e4),
2768
- messages: [{ role: "user", content: [{ type: "text", text: trimmed }] }]
2769
- });
3319
+ const ac = new AbortController();
3320
+ const timer = setTimeout(() => ac.abort(new Error("llm correction timeout")), 1e4);
3321
+ const maxAllowed = Math.max(trimmed.length * 3, trimmed.length + 24);
2770
3322
  let out = "";
2771
- for await (const chunk of stream) {
2772
- if (chunk && chunk.type === "text-delta" && typeof chunk.text === "string") out += chunk.text;
3323
+ try {
3324
+ const stream = llm.stream({
3325
+ provider: sel.provider,
3326
+ model: sel.model,
3327
+ system: correctionSystem(lang),
3328
+ // host 侧自弃 10s(早于客户端 12s,审查 M3):超时或输出失控超长均立即 abort。
3329
+ signal: ac.signal,
3330
+ messages: [{ role: "user", content: [{ type: "text", text: trimmed }] }]
3331
+ });
3332
+ for await (const chunk of stream) {
3333
+ if (chunk && chunk.type === "text-delta" && typeof chunk.text === "string") {
3334
+ out += chunk.text;
3335
+ if (out.length > maxAllowed + 32) {
3336
+ ac.abort(new Error("llm correction output exceeded max length"));
3337
+ return text;
3338
+ }
3339
+ }
3340
+ }
3341
+ } finally {
3342
+ clearTimeout(timer);
2773
3343
  }
2774
3344
  const corrected = out.trim();
2775
3345
  if (corrected.length > Math.max(trimmed.length * 3, trimmed.length + 24)) return text;
@@ -2787,13 +3357,114 @@ async function correctText(ctx, text, lang) {
2787
3357
  if (CORRECTION_PREAMBLE_RE.test(noFiller)) return text;
2788
3358
  }
2789
3359
  return corrected || text;
2790
- } catch {
3360
+ } catch (e) {
3361
+ console.warn(`[dsh-voice-mode] llm correction failed: ${redactSecrets(e)}`);
2791
3362
  return text;
2792
3363
  }
2793
3364
  }
2794
3365
 
3366
+ // src/audio-format.ts
3367
+ function sniffAudioMime(buf, fallback) {
3368
+ if (buf.length >= 12 && buf.subarray(0, 4).toString("latin1") === "RIFF" && buf.subarray(8, 12).toString("latin1") === "WAVE") {
3369
+ return "audio/wav";
3370
+ }
3371
+ if (buf.length >= 4 && buf.subarray(0, 4).toString("latin1") === "OggS") return "audio/ogg";
3372
+ if (buf.length >= 4 && buf.subarray(0, 4).toString("latin1") === "fLaC") return "audio/flac";
3373
+ if (buf.length >= 3 && buf[0] === 73 && buf[1] === 68 && buf[2] === 51) return "audio/mpeg";
3374
+ if (buf.length >= 7 && buf[0] === 255 && (buf[1] & 246) === 240) return "audio/aac";
3375
+ if (buf.length >= 3 && buf[0] === 255 && (buf[1] & 224) === 224 && (buf[1] & 24) !== 8 && ((buf[1] & 6) === 2 || (buf[1] & 6) === 4) && (buf[2] & 240) !== 240 && (buf[2] & 12) !== 12) {
3376
+ return "audio/mpeg";
3377
+ }
3378
+ return fallback;
3379
+ }
3380
+
3381
+ // src/online-tts.ts
3382
+ var CUSTOM_PRESET_ID = "custom";
3383
+ var trim = (v) => typeof v === "string" ? v.trim() : "";
3384
+ function lookupPreset(presetId) {
3385
+ const id = trim(presetId);
3386
+ if (!id || id === CUSTOM_PRESET_ID) return null;
3387
+ return Object.hasOwn(OPENAI_PRESETS, id) ? OPENAI_PRESETS[id] : null;
3388
+ }
3389
+ function resolveOnlineTts(overrides, config) {
3390
+ const preset = lookupPreset(overrides.presetId);
3391
+ const settingBase = trim(overrides.baseUrl);
3392
+ const presetBase = trim(preset?.baseUrl);
3393
+ const configBase = trim(config.baseUrl);
3394
+ const baseUrl = settingBase || presetBase || configBase;
3395
+ const settingModel = trim(overrides.model);
3396
+ const presetModel = trim(preset?.model);
3397
+ const configModel = trim(config.model);
3398
+ const model = settingModel || presetModel || configModel;
3399
+ const settingVoice = trim(overrides.voice);
3400
+ const presetVoice = trim(preset?.voice);
3401
+ const configVoice = trim(config.voice);
3402
+ const voice = settingVoice || presetVoice || configVoice;
3403
+ const settingKey = trim(overrides.apiKey);
3404
+ const presetId = trim(overrides.presetId);
3405
+ const settingsPresetKey = preset !== null && presetId && Object.hasOwn(overrides.apiKeys ?? {}, presetId) && typeof overrides.apiKeys?.[presetId] === "string" ? trim(overrides.apiKeys?.[presetId]) : "";
3406
+ const presetKey = presetId && presetId !== "__proto__" && presetId !== "constructor" && presetId !== "prototype" && config.apiKeys && Object.hasOwn(config.apiKeys, presetId) && typeof config.apiKeys[presetId] === "string" ? trim(config.apiKeys[presetId]) : "";
3407
+ const configKey = trim(config.apiKey);
3408
+ const apiKey = settingsPresetKey || settingKey || presetKey || configKey;
3409
+ return {
3410
+ presetId,
3411
+ baseUrl,
3412
+ model,
3413
+ voice,
3414
+ apiKey,
3415
+ from: {
3416
+ baseUrl: settingBase ? "settings" : presetBase ? "preset" : configBase ? "config" : "none",
3417
+ model: settingModel ? "settings" : presetModel ? "preset" : configModel ? "config" : "none",
3418
+ voice: settingVoice ? "settings" : presetVoice ? "preset" : configVoice ? "config" : "none",
3419
+ apiKey: settingsPresetKey ? "settingsPreset" : settingKey ? "settings" : presetKey ? "presetKey" : configKey ? "configKey" : "none"
3420
+ }
3421
+ };
3422
+ }
3423
+
2795
3424
  // src/tts-openai.ts
2796
3425
  var MIME = { mp3: "audio/mpeg", wav: "audio/wav" };
3426
+ var MAX_AUDIO_BYTES = 16 * 1024 * 1024;
3427
+ var MAX_ERROR_BYTES = 8 * 1024;
3428
+ async function readResponseBytes(res, maxBytes, truncate) {
3429
+ const lenHeader = Number(res.headers.get("content-length") ?? 0);
3430
+ if (!truncate && Number.isFinite(lenHeader) && lenHeader > maxBytes) {
3431
+ await res.body?.cancel().catch(() => void 0);
3432
+ throw new OpenAiTtsError("openai_too_large", `audio response exceeds ${maxBytes} bytes`);
3433
+ }
3434
+ if (res.body && typeof res.body.getReader === "function") {
3435
+ const reader = res.body.getReader();
3436
+ const chunks = [];
3437
+ let total = 0;
3438
+ try {
3439
+ for (; ; ) {
3440
+ const { done, value } = await reader.read();
3441
+ if (done) break;
3442
+ if (!value || value.byteLength === 0) continue;
3443
+ if (total + value.byteLength > maxBytes) {
3444
+ if (truncate) {
3445
+ const take = maxBytes - total;
3446
+ if (take > 0) chunks.push(value.subarray(0, take));
3447
+ await reader.cancel().catch(() => void 0);
3448
+ break;
3449
+ }
3450
+ await reader.cancel().catch(() => void 0);
3451
+ throw new OpenAiTtsError("openai_too_large", `audio response exceeds ${maxBytes} bytes`);
3452
+ }
3453
+ chunks.push(value);
3454
+ total += value.byteLength;
3455
+ }
3456
+ } finally {
3457
+ reader.releaseLock();
3458
+ }
3459
+ return Buffer.concat(chunks);
3460
+ }
3461
+ const buf = Buffer.from(await res.arrayBuffer());
3462
+ if (buf.length > maxBytes) {
3463
+ if (truncate) return buf.subarray(0, maxBytes);
3464
+ throw new OpenAiTtsError("openai_too_large", `audio response exceeds ${maxBytes} bytes`);
3465
+ }
3466
+ return buf;
3467
+ }
2797
3468
  var OpenAiTtsError = class extends Error {
2798
3469
  code;
2799
3470
  constructor(code, message) {
@@ -2807,6 +3478,9 @@ function speechUrl(baseUrl) {
2807
3478
  if (url.protocol !== "http:" && url.protocol !== "https:") {
2808
3479
  throw new OpenAiTtsError("openai_bad_url", "baseUrl must be http(s)");
2809
3480
  }
3481
+ if (url.username || url.password) {
3482
+ throw new OpenAiTtsError("openai_bad_url", "baseUrl must not include credentials");
3483
+ }
2810
3484
  const noSlash = url.pathname.replace(/\/+$/, "");
2811
3485
  const base = noSlash.endsWith("/audio/speech") ? noSlash.slice(0, -"/audio/speech".length) : noSlash;
2812
3486
  url.pathname = `${base}/audio/speech`;
@@ -2824,6 +3498,7 @@ var OpenAiTtsEngine = class {
2824
3498
  now;
2825
3499
  fallbackEngine = null;
2826
3500
  inflight = /* @__PURE__ */ new Set();
3501
+ closed = false;
2827
3502
  downUntil = 0;
2828
3503
  lastError;
2829
3504
  lastMime;
@@ -2847,32 +3522,38 @@ var OpenAiTtsEngine = class {
2847
3522
  this.now = options.now ?? Date.now;
2848
3523
  this.lastMime = MIME[this.format];
2849
3524
  }
2850
- /** 最近一次成功合成所用格式(远程或回退引擎的 MIME 可能不同;队列在 synthesize 之后读取)。 */
3525
+ /** 最近一次成功合成所用格式(远程或回退引擎的 MIME 可能不同;并发请用 synthesizeWithMime)。 */
2851
3526
  get mime() {
2852
3527
  return this.lastMime;
2853
3528
  }
2854
3529
  updateVoice(voice, rate) {
2855
- this.voice = voice || this.options.voice;
3530
+ this.voice = voice.trim() || this.options.voice;
2856
3531
  if (rate !== void 0 && Number.isFinite(rate)) this.rate = rate;
2857
3532
  }
2858
3533
  async synthesize(text, options = {}) {
3534
+ return (await this.synthesizeWithMime(text, options)).buf;
3535
+ }
3536
+ /** 合成并**随结果返回**本句专属 MIME(B6:不从共享 this.lastMime 事后回读,并发异构容器不串味)。 */
3537
+ async synthesizeWithMime(text, options = {}) {
3538
+ if (this.closed) throw new OpenAiTtsError("openai_closed", "remote TTS engine closed");
2859
3539
  const input = stripEmotionTags(text).replace(/\s+/g, " ").trim();
2860
- if (input === "") return Buffer.alloc(0);
3540
+ if (input === "") return { buf: Buffer.alloc(0), mime: this.lastMime };
2861
3541
  if (this.now() >= this.downUntil) {
2862
3542
  try {
2863
- const buf = await this.remote(input, options);
3543
+ const res = await this.remote(input, options);
2864
3544
  this.lastError = void 0;
2865
- this.lastMime = MIME[this.format];
2866
- return buf;
3545
+ return res;
2867
3546
  } catch (e) {
3547
+ if (this.closed) throw new OpenAiTtsError("openai_closed", "remote TTS engine closed");
2868
3548
  if (e.name === "AbortError" && !(e instanceof OpenAiTtsError)) throw e;
2869
3549
  const err = e instanceof OpenAiTtsError ? e : new OpenAiTtsError("openai_unreachable", String(e));
2870
3550
  this.lastError = err;
2871
3551
  this.downUntil = this.now() + this.cooldownMs;
2872
3552
  if (!this.options.fallback) throw err;
2873
- console.warn(`[dsh-voice-mode] remote TTS failed, using the local fallback for ${this.cooldownMs} ms: ${err.message}`);
3553
+ console.warn(`[dsh-voice-mode] remote TTS failed, using the local fallback for ${this.cooldownMs} ms: ${redactSecrets(err)}`);
2874
3554
  }
2875
3555
  }
3556
+ if (this.closed) throw new OpenAiTtsError("openai_closed", "remote TTS engine closed");
2876
3557
  return this.viaFallback(text, options);
2877
3558
  }
2878
3559
  async remote(input, options) {
@@ -2880,9 +3561,10 @@ var OpenAiTtsEngine = class {
2880
3561
  const body = {
2881
3562
  model: this.options.model,
2882
3563
  input,
2883
- voice: options.voice || this.voice,
2884
3564
  response_format: this.format
2885
3565
  };
3566
+ const voice = (options.voice || this.voice || "").trim();
3567
+ if (voice) body.voice = voice;
2886
3568
  const rate = options.rate ?? this.rate;
2887
3569
  if (rate !== void 0 && rate > 0 && rate !== 1) body.speed = rate;
2888
3570
  if (this.options.instructions) body.instructions = this.options.instructions;
@@ -2896,14 +3578,36 @@ var OpenAiTtsEngine = class {
2896
3578
  }, this.timeoutMs);
2897
3579
  this.inflight.add(ac);
2898
3580
  try {
2899
- const res = await this.fetchImpl(this.url, { method: "POST", headers, body: JSON.stringify(body), signal: ac.signal });
3581
+ const res = await this.fetchImpl(this.url, {
3582
+ method: "POST",
3583
+ headers,
3584
+ body: JSON.stringify(body),
3585
+ signal: ac.signal,
3586
+ redirect: "error"
3587
+ });
2900
3588
  if (!res.ok) {
2901
- const detail = (await res.text().catch(() => "")).slice(0, 200);
3589
+ const rawErr = await readResponseBytes(res, MAX_ERROR_BYTES, true).then((b) => b.toString("utf8"), () => "");
3590
+ const detail = redactBodySnippet(rawErr);
2902
3591
  throw new OpenAiTtsError("openai_http_error", `HTTP ${res.status}${detail ? `: ${detail}` : ""}`);
2903
3592
  }
2904
- const buf = Buffer.from(await res.arrayBuffer());
3593
+ const ctype = (res.headers.get("content-type") ?? "").toLowerCase();
3594
+ const buf = await readResponseBytes(res, MAX_AUDIO_BYTES, false);
2905
3595
  if (buf.length === 0) throw new OpenAiTtsError("openai_empty_audio", "empty audio");
2906
- return buf;
3596
+ const sniffed = sniffAudioMime(buf, "");
3597
+ let mime;
3598
+ if (sniffed) {
3599
+ mime = sniffed;
3600
+ } else if (ctype.startsWith("audio/")) {
3601
+ const head = buf.subarray(0, 64).toString("utf8").trimStart();
3602
+ if (head.startsWith("<") || head.startsWith("{") || head.startsWith("[")) {
3603
+ throw new OpenAiTtsError("openai_bad_payload", "audio content-type but textual body");
3604
+ }
3605
+ mime = ctype.split(";")[0].trim();
3606
+ } else {
3607
+ throw new OpenAiTtsError("openai_bad_payload", `non-audio response (content-type: ${ctype || "none"})`);
3608
+ }
3609
+ this.lastMime = mime;
3610
+ return { buf, mime };
2907
3611
  } catch (e) {
2908
3612
  if (timedOut) throw new OpenAiTtsError("openai_timeout", `no audio within ${this.timeoutMs} ms`);
2909
3613
  throw e;
@@ -2913,13 +3617,16 @@ var OpenAiTtsEngine = class {
2913
3617
  }
2914
3618
  }
2915
3619
  async viaFallback(text, options) {
3620
+ if (this.closed) throw new OpenAiTtsError("openai_closed", "remote TTS engine closed");
2916
3621
  if (!this.options.fallback) {
2917
3622
  throw this.lastError ?? new OpenAiTtsError("openai_unreachable", "remote TTS unavailable");
2918
3623
  }
2919
3624
  this.fallbackEngine ??= this.options.fallback();
2920
- const buf = await this.fallbackEngine.synthesize(text, { rate: options.rate ?? this.rate });
2921
- this.lastMime = this.fallbackEngine.mime;
2922
- return buf;
3625
+ const fb = this.fallbackEngine;
3626
+ const rateOpt = { rate: options.rate ?? this.rate };
3627
+ const res = fb.synthesizeWithMime ? await fb.synthesizeWithMime(text, rateOpt) : { buf: await fb.synthesize(text, rateOpt), mime: fb.mime };
3628
+ this.lastMime = res.mime;
3629
+ return res;
2923
3630
  }
2924
3631
  interrupt() {
2925
3632
  for (const ac of this.inflight) ac.abort();
@@ -2935,16 +3642,203 @@ var OpenAiTtsEngine = class {
2935
3642
  ready: !fallingBack && !this.configError,
2936
3643
  loading: false,
2937
3644
  error: this.lastError?.message,
2938
- errorCode: this.lastError?.code
3645
+ errorCode: this.lastError?.code,
3646
+ // 2026-11-20 UX:只回布尔——状态卡据此提示「缺 API Key」,绝不回传 key。
3647
+ keyPresent: Boolean(this.options.apiKey && this.options.apiKey.trim().length > 0)
2939
3648
  };
2940
3649
  }
2941
3650
  async close() {
3651
+ this.closed = true;
2942
3652
  this.interrupt();
2943
3653
  const fb = this.fallbackEngine;
2944
3654
  this.fallbackEngine = null;
2945
3655
  await fb?.close();
2946
3656
  }
2947
3657
  };
3658
+ function presetRequiresKey(presetId) {
3659
+ if (!presetId) return false;
3660
+ if (!Object.prototype.hasOwnProperty.call(OPENAI_PRESETS, presetId)) return false;
3661
+ return !presetId.startsWith("selfhosted-");
3662
+ }
3663
+ var SILICONFLOW_SYSTEM_VOICES = ["alex", "benjamin", "charles", "david", "anna", "bella", "claire", "diana"];
3664
+ var OPENAI_API_VOICES = ["alloy", "ash", "ballad", "coral", "echo", "fable", "marin", "cedar", "nova", "onyx", "sage", "shimmer"];
3665
+ var OPENAI_PRESETS = {
3666
+ "siliconflow-cosyvoice2": {
3667
+ baseUrl: "https://api.siliconflow.cn/v1",
3668
+ model: "FunAudioLLM/CosyVoice2-0.5B",
3669
+ voice: "FunAudioLLM/CosyVoice2-0.5B:alex",
3670
+ voices: SILICONFLOW_SYSTEM_VOICES.map((v) => `FunAudioLLM/CosyVoice2-0.5B:${v}`)
3671
+ },
3672
+ "siliconflow-fish": {
3673
+ baseUrl: "https://api.siliconflow.cn/v1",
3674
+ model: "fishaudio/fish-speech-1.5",
3675
+ voice: "fishaudio/fish-speech-1.5:anna",
3676
+ voices: SILICONFLOW_SYSTEM_VOICES.map((v) => `fishaudio/fish-speech-1.5:${v}`)
3677
+ },
3678
+ // OpenRouter 官方 TTS 文档(2026-05-01 公告):POST /api/v1/audio/speech,
3679
+ // 示例模型 slug 为带日期的 `openai/gpt-4o-mini-tts-2025-12-15`、voice `alloy`、response_format mp3。
3680
+ // OpenRouter 透传 OpenAI 语音名,故沿用 OpenAI 全量音色表。
3681
+ "openrouter-openai": {
3682
+ baseUrl: "https://openrouter.ai/api/v1",
3683
+ model: "openai/gpt-4o-mini-tts-2025-12-15",
3684
+ voice: "alloy",
3685
+ voices: [...OPENAI_API_VOICES]
3686
+ },
3687
+ // OpenAI 官方(docs: /v1/audio/speech,模型 gpt-4o-mini-tts,官方推荐 marin/cedar 音质最佳)。
3688
+ "openai-official": {
3689
+ baseUrl: "https://api.openai.com/v1",
3690
+ model: "gpt-4o-mini-tts",
3691
+ voice: "marin",
3692
+ voices: [...OPENAI_API_VOICES]
3693
+ },
3694
+ // 自建示例(本机地址为占位;无鉴权时 key 留空即可):
3695
+ // Kokoro-FastAPI / LocalAI 的 OpenAI 兼容面,Kokoro 音色名取自本插件本地目录(zf_xiaobei 等)。
3696
+ // 仅收录命名中文音色(与本地 Kokoro 一致);其余 100+ 数字 sid 音色走「自定义手输」。
3697
+ "selfhosted-kokoro": {
3698
+ baseUrl: "http://127.0.0.1:8880/v1",
3699
+ model: "kokoro",
3700
+ voice: "zf_xiaobei",
3701
+ voices: ["zf_xiaobei", "zf_xiaoni", "zf_xiaoxiao", "zf_xiaoyi"]
3702
+ },
3703
+ // Groq 官方 API Reference「Create speech」:POST /openai/v1/audio/speech(base 为
3704
+ // https://api.groq.com/openai/v1),模型 playai-tts,音色列表形如 Fritz-PlayAI。
3705
+ // 注意(2026-11-20 核实):上游已有仓库把 playai-tts 标记为 decommissioned 并迁移到 Orpheus;
3706
+ // 此处仅保留文档示例音色 + 自定义手输,若 Groq 下线该模型,用户切 Orpheus 端点手填即可。
3707
+ "groq-playai": {
3708
+ baseUrl: "https://api.groq.com/openai/v1",
3709
+ model: "playai-tts",
3710
+ voice: "Fritz-PlayAI",
3711
+ voices: ["Fritz-PlayAI"]
3712
+ },
3713
+ // vLLM-Omni(ADR-0013 实测过 VoxCPM2 / Qwen3-TTS 部署)。音色名取决于部署的模型,保留默认 + 手输。
3714
+ "selfhosted-vllm": {
3715
+ baseUrl: "http://127.0.0.1:8000/v1",
3716
+ model: "tts-1",
3717
+ voice: "default",
3718
+ voices: ["default"]
3719
+ }
3720
+ };
3721
+
3722
+ // src/engine-rebuild.ts
3723
+ function stableApiKeys(m) {
3724
+ if (m === null || typeof m !== "object" || Array.isArray(m)) return "";
3725
+ const rec = m;
3726
+ const keys = Object.keys(rec).filter((k) => typeof rec[k] === "string").sort();
3727
+ return JSON.stringify(keys.map((k) => [k, rec[k]]));
3728
+ }
3729
+ function engineRebuildReason(prev, next, engineKind, activeKokoroModel) {
3730
+ if (next.ttsEngine !== engineKind) return "engine-switch";
3731
+ if (engineKind === "mimo" && next.mimoApiKey !== prev.mimoApiKey) return "mimo-key";
3732
+ if (engineKind === "kokoro" && next.kokoroModel !== activeKokoroModel) return "kokoro-model";
3733
+ if (engineKind === "openai" && (next.openaiPreset !== prev.openaiPreset || next.openaiBaseUrl !== prev.openaiBaseUrl || next.openaiModel !== prev.openaiModel || next.openaiApiKey !== prev.openaiApiKey || stableApiKeys(next.openaiApiKeys) !== stableApiKeys(prev.openaiApiKeys))) {
3734
+ return "openai-config";
3735
+ }
3736
+ return null;
3737
+ }
3738
+
3739
+ // src/settings-view.ts
3740
+ var SECRET_SETTING_KEYS = ["openaiApiKey", "mimoApiKey", "openaiApiKeys"];
3741
+ function publicSettingsView(vset, presence, fromConfig) {
3742
+ return {
3743
+ value: { ...vset, openaiApiKey: "", mimoApiKey: "", openaiApiKeys: {} },
3744
+ keys: { openaiApiKey: Boolean(presence.openaiApiKey), mimoApiKey: Boolean(presence.mimoApiKey), openaiApiKeys: boolMap(presence.openaiApiKeys) },
3745
+ keysFromConfig: {
3746
+ openaiApiKey: Boolean(fromConfig?.openaiApiKey),
3747
+ mimoApiKey: Boolean(fromConfig?.mimoApiKey),
3748
+ openaiApiKeys: boolMap(fromConfig?.openaiApiKeys)
3749
+ }
3750
+ };
3751
+ }
3752
+ function applyClearSecrets(patch, clearList) {
3753
+ const { clearSecrets: _ignored, ...rest } = patch;
3754
+ if (clearList !== void 0 && !Array.isArray(clearList)) {
3755
+ throw new Error("clearSecrets must be an array");
3756
+ }
3757
+ const list = clearList ?? [];
3758
+ const out = { ...rest };
3759
+ for (const item of list) {
3760
+ if (typeof item !== "string") continue;
3761
+ if (!SECRET_SETTING_KEYS.includes(item)) {
3762
+ throw new Error(`unknown secret: ${item}`);
3763
+ }
3764
+ out[item] = item === "openaiApiKeys" ? {} : "";
3765
+ }
3766
+ return out;
3767
+ }
3768
+ function mergePresetApiKeys(existing, patchMap, clearAll = false) {
3769
+ const out = {};
3770
+ if (!clearAll) {
3771
+ const base = readKeyMap(existing);
3772
+ for (const id of Object.keys(base)) {
3773
+ if (id === "__proto__" || id === "constructor" || id === "prototype") continue;
3774
+ const v = base[id];
3775
+ if (typeof v === "string" && v.trim().length > 0) out[id] = v.trim();
3776
+ }
3777
+ }
3778
+ const inc = readKeyMap(patchMap);
3779
+ for (const id of Object.keys(inc)) {
3780
+ if (id === "__proto__" || id === "constructor" || id === "prototype") continue;
3781
+ const v = inc[id];
3782
+ if (typeof v !== "string") continue;
3783
+ if (v.trim().length > 0) out[id] = v.trim();
3784
+ else delete out[id];
3785
+ }
3786
+ return out;
3787
+ }
3788
+ function hasSecret(value, ...fallbacks) {
3789
+ const nonEmpty = (v) => typeof v === "string" && v.trim().length > 0;
3790
+ return nonEmpty(value) || fallbacks.some(nonEmpty);
3791
+ }
3792
+ function boolMap(v) {
3793
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return {};
3794
+ const out = {};
3795
+ for (const k of Object.keys(v)) out[k] = Boolean(v[k]);
3796
+ return out;
3797
+ }
3798
+ function readKeyMap(v) {
3799
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return {};
3800
+ return v;
3801
+ }
3802
+ function buildPresetKeyPresence(settingsMap, configMap) {
3803
+ const s = readKeyMap(settingsMap);
3804
+ const c = readKeyMap(configMap);
3805
+ const ids = /* @__PURE__ */ new Set([...Object.keys(s), ...Object.keys(c)]);
3806
+ const presence = {};
3807
+ const fromConfig = {};
3808
+ for (const id of ids) {
3809
+ if (id === "__proto__" || id === "constructor" || id === "prototype") continue;
3810
+ presence[id] = hasSecret(s[id], c[id]);
3811
+ fromConfig[id] = hasSecret(c[id]);
3812
+ }
3813
+ return { presence, fromConfig };
3814
+ }
3815
+ function buildSettingsGetView(vset, config) {
3816
+ const cfgKey = hasSecret(config.openaiTts?.apiKey);
3817
+ const cfgMimo = hasSecret(config.mimoTts?.apiKey);
3818
+ const presetKeys = buildPresetKeyPresence(vset.openaiApiKeys, config.openaiTts?.apiKeys);
3819
+ return publicSettingsView(
3820
+ vset,
3821
+ {
3822
+ openaiApiKey: hasSecret(vset.openaiApiKey, config.openaiTts?.apiKey),
3823
+ mimoApiKey: hasSecret(vset.mimoApiKey, config.mimoTts?.apiKey),
3824
+ openaiApiKeys: presetKeys.presence
3825
+ },
3826
+ { openaiApiKey: cfgKey, mimoApiKey: cfgMimo, openaiApiKeys: presetKeys.fromConfig }
3827
+ );
3828
+ }
3829
+
3830
+ // src/engine-kind.ts
3831
+ var TTS_ENGINE_KINDS = ["vits", "kokoro", "edge", "openai", "mimo"];
3832
+ var LOCAL_ENGINE_KINDS = ["vits", "kokoro"];
3833
+ function asTtsEngineKind(value) {
3834
+ return TTS_ENGINE_KINDS.includes(value) ? value : "vits";
3835
+ }
3836
+ function isLocalEngine(value) {
3837
+ return LOCAL_ENGINE_KINDS.includes(value);
3838
+ }
3839
+ function usesBilingualSample(value) {
3840
+ return value === "kokoro" || value === "openai" || value === "mimo";
3841
+ }
2948
3842
 
2949
3843
  // src/prompts.ts
2950
3844
  var ZH = "\u3010\u8BED\u97F3\u6A21\u5F0F\u3011\u5F53\u524D\u56DE\u590D\u4F1A\u88AB\u8BED\u97F3\u6717\u8BFB\uFF0C\u8BF7\u59CB\u7EC8\u7528\u7528\u6237\u6240\u7528\u8BED\u8A00\u3001\u4EE5\u53E3\u8BED\u5316\u7684\u77ED\u53E5\u76F4\u63A5\u56DE\u7B54\uFF0C\u50CF\u9762\u5BF9\u9762\u804A\u5929\u4E00\u6837\u81EA\u7136\uFF0C\u907F\u514D\u4E66\u9762\u8BED\u548C\u957F\u96BE\u53E5\u3002\u4E0D\u8981\u4F7F\u7528\u4EFB\u4F55 Markdown \u6216\u6392\u7248\u7B26\u53F7\uFF08\u661F\u53F7\u3001\u4E0B\u5212\u7EBF\u3001\u53CD\u5F15\u53F7\u3001\u4E95\u53F7\u3001\u5217\u8868\u4E0E\u8868\u683C\u6807\u8BB0\u3001\u4EE3\u7801\u5757\u7B49\uFF09\u3002\u9700\u8981\u5206\u70B9\u8BF4\u660E\u65F6\u7528\u300C\u7B2C\u4E00\u3001\u7B2C\u4E8C\u300D\u6216\u8FDE\u8D2F\u7684\u77ED\u53E5\u8868\u8FBE\uFF1B\u9664\u975E\u7528\u6237\u660E\u786E\u8981\u6C42\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EE3\u7801\u7247\u6BB5\u3001\u5B8C\u6574 URL \u6216\u5197\u957F\u5B9A\u4E49\uFF0C\u7528\u4E00\u4E24\u53E5\u8BDD\u6982\u62EC\u542B\u4E49\u5373\u53EF\u3002\u56DE\u7B54\u7B80\u6D01\u76F4\u63A5\uFF0C\u4E0D\u8981\u91CD\u590D\u548C\u5BD2\u6684\u3002\u5982\u679C\u7528\u6237\u5728\u4F60\u6717\u8BFB\u65F6\u63D2\u8BDD\uFF08\u54EA\u6015\u53EA\u662F\u300C\u55EF/\u5BF9\u300D\u8FD9\u6837\u7684\u77ED\u5E94\u7B54\uFF09\uFF0C\u7ACB\u5373\u505C\u6B62\u5F53\u524D\u53E5\uFF0C\u628A\u8BDD\u8F6E\u8BA9\u7ED9\u7528\u6237\uFF1B\u56DE\u7B54\u540E\u7559\u51FA\u505C\u987F\uFF0C\u4E0D\u8981\u8FDE\u95EE\u4E24\u4E2A\u95EE\u9898\uFF1B\u7528\u6237\u6C89\u9ED8\u65F6\u4E0D\u8981\u4E3B\u52A8\u627E\u65B0\u8BDD\u9898\u3002";
@@ -2952,7 +3846,7 @@ var EN = '[Voice mode] Your reply will be read aloud. Always answer in the langu
2952
3846
  var spokenPrompt = (lang) => lang === "en" ? EN : ZH;
2953
3847
  function normalizePromptLang(raw) {
2954
3848
  if (typeof raw !== "string" || raw === "" || raw.length > 32) return "zh";
2955
- return /^zh\b/i.test(raw) ? "zh" : "en";
3849
+ return /^zh(?:[-_]|$)/i.test(raw) ? "zh" : "en";
2956
3850
  }
2957
3851
  var SAMPLE_ZH = "\u4F60\u597D\uFF0C\u6B22\u8FCE\u4F7F\u7528\u8BED\u97F3\u6A21\u5F0F\u3002";
2958
3852
  var SAMPLE_EN = "Hello, welcome to voice mode.";
@@ -2968,15 +3862,294 @@ var SAMPLE_BY_LANG = {
2968
3862
  it: "Ciao, benvenuto nella modalit\xE0 vocale.",
2969
3863
  ru: "\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435, \u0434\u043E\u0431\u0440\u043E \u043F\u043E\u0436\u0430\u043B\u043E\u0432\u0430\u0442\u044C \u0432 \u0433\u043E\u043B\u043E\u0441\u043E\u0432\u043E\u0439 \u0440\u0435\u0436\u0438\u043C."
2970
3864
  };
3865
+ function mimoSpeedInstruction(rate) {
3866
+ return rate > 1 ? `\u8BED\u901F\u52A0\u5FEB\u5230\u7EA6 ${rate} \u500D` : `\u8BED\u901F\u653E\u6162\u5230\u7EA6 ${rate} \u500D`;
3867
+ }
2971
3868
  function previewSample(engine, voice) {
2972
- if (engine === "kokoro" || engine === "openai") return `${SAMPLE_ZH}${SAMPLE_EN}`;
3869
+ if (usesBilingualSample(engine)) return `${SAMPLE_ZH}${SAMPLE_EN}`;
2973
3870
  if (engine === "vits") return SAMPLE_ZH;
2974
3871
  const m = /^([a-z]{2,3})-/i.exec(voice);
2975
3872
  return m && SAMPLE_BY_LANG[m[1].toLowerCase()] || SAMPLE_EN;
2976
3873
  }
2977
3874
 
3875
+ // src/tts-mimo.ts
3876
+ var MIME2 = {
3877
+ wav: "audio/wav",
3878
+ mp3: "audio/mpeg"
3879
+ };
3880
+ var MAX_JSON_BYTES = 24 * 1024 * 1024;
3881
+ var MAX_ERROR_BYTES2 = 8 * 1024;
3882
+ async function readMimoBytes(res, maxBytes, truncate) {
3883
+ const lenHeader = Number(res.headers.get("content-length") ?? 0);
3884
+ if (!truncate && Number.isFinite(lenHeader) && lenHeader > maxBytes) {
3885
+ await res.body?.cancel().catch(() => void 0);
3886
+ throw new MimoTtsError("mimo_too_large", `response exceeds ${maxBytes} bytes`);
3887
+ }
3888
+ if (res.body && typeof res.body.getReader === "function") {
3889
+ const reader = res.body.getReader();
3890
+ const chunks = [];
3891
+ let total = 0;
3892
+ try {
3893
+ for (; ; ) {
3894
+ const { done, value } = await reader.read();
3895
+ if (done) break;
3896
+ if (!value || value.byteLength === 0) continue;
3897
+ if (total + value.byteLength > maxBytes) {
3898
+ if (truncate) {
3899
+ const take = maxBytes - total;
3900
+ if (take > 0) chunks.push(value.subarray(0, take));
3901
+ await reader.cancel().catch(() => void 0);
3902
+ break;
3903
+ }
3904
+ await reader.cancel().catch(() => void 0);
3905
+ throw new MimoTtsError("mimo_too_large", `response exceeds ${maxBytes} bytes`);
3906
+ }
3907
+ chunks.push(value);
3908
+ total += value.byteLength;
3909
+ }
3910
+ } finally {
3911
+ reader.releaseLock();
3912
+ }
3913
+ return Buffer.concat(chunks);
3914
+ }
3915
+ const buf = Buffer.from(await res.arrayBuffer());
3916
+ if (buf.length > maxBytes) {
3917
+ if (truncate) return buf.subarray(0, maxBytes);
3918
+ throw new MimoTtsError("mimo_too_large", `response exceeds ${maxBytes} bytes`);
3919
+ }
3920
+ return buf;
3921
+ }
3922
+ var MimoTtsError = class extends Error {
3923
+ code;
3924
+ constructor(code, message) {
3925
+ super(message);
3926
+ this.name = "MimoTtsError";
3927
+ this.code = code;
3928
+ }
3929
+ };
3930
+ var MIMO_DEFAULT_BASE_URL = "https://api.xiaomimimo.com/v1";
3931
+ var MIMO_DEFAULT_MODEL = "mimo-v2.5-tts";
3932
+ var MIMO_DEFAULT_VOICE = "mimo_default";
3933
+ function mimoChatUrl(baseUrl) {
3934
+ const url = new URL(baseUrl.trim());
3935
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
3936
+ throw new MimoTtsError("mimo_bad_url", "baseUrl must be http(s)");
3937
+ }
3938
+ if (url.username || url.password) {
3939
+ throw new MimoTtsError("mimo_bad_url", "baseUrl must not include credentials");
3940
+ }
3941
+ const suffix = "/chat/completions";
3942
+ const noSlash = url.pathname.replace(/\/+$/, "");
3943
+ const base = noSlash.endsWith(suffix) ? noSlash.slice(0, -suffix.length) : noSlash;
3944
+ url.pathname = `${base}${suffix}`;
3945
+ return url.toString();
3946
+ }
3947
+ function extractMimoAudio(body) {
3948
+ if (typeof body !== "object" || body === null) return null;
3949
+ const choices = body.choices;
3950
+ if (!Array.isArray(choices) || choices.length === 0) return null;
3951
+ const message = choices[0].message;
3952
+ if (typeof message !== "object" || message === null) return null;
3953
+ const audio = message.audio;
3954
+ if (typeof audio !== "object" || audio === null) return null;
3955
+ const data = audio.data;
3956
+ return typeof data === "string" && data.length > 0 ? data : null;
3957
+ }
3958
+ function decodeBase64Audio(data) {
3959
+ const raw = data.replace(/\s+/g, "").replace(/-/g, "+").replace(/_/g, "/");
3960
+ if (raw.length === 0 || raw.length % 4 === 1) {
3961
+ throw new MimoTtsError("mimo_bad_audio", "audio payload is not valid base64");
3962
+ }
3963
+ const padLen = raw.length % 4 === 0 ? 0 : 4 - raw.length % 4;
3964
+ const clean = padLen > 0 ? raw + "=".repeat(padLen) : raw;
3965
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(clean)) {
3966
+ throw new MimoTtsError("mimo_bad_audio", "audio payload is not valid base64");
3967
+ }
3968
+ return Buffer.from(clean, "base64");
3969
+ }
3970
+ var MimoTtsEngine = class {
3971
+ voice;
3972
+ rate;
3973
+ url;
3974
+ configError;
3975
+ format;
3976
+ timeoutMs;
3977
+ cooldownMs;
3978
+ fetchImpl;
3979
+ now;
3980
+ fallbackEngine = null;
3981
+ inflight = /* @__PURE__ */ new Set();
3982
+ closed = false;
3983
+ downUntil = 0;
3984
+ lastError;
3985
+ lastMime;
3986
+ options;
3987
+ constructor(options) {
3988
+ this.options = options;
3989
+ let url = null;
3990
+ try {
3991
+ if (!options.apiKey?.trim()) {
3992
+ throw new MimoTtsError("mimo_not_configured", "mimo apiKey is not configured");
3993
+ }
3994
+ url = mimoChatUrl(options.baseUrl?.trim() || MIMO_DEFAULT_BASE_URL);
3995
+ } catch (e) {
3996
+ this.configError = e instanceof MimoTtsError ? e : new MimoTtsError("mimo_bad_url", "bad baseUrl");
3997
+ url = null;
3998
+ }
3999
+ this.url = url;
4000
+ this.voice = (options.voice ?? "").trim() || MIMO_DEFAULT_VOICE;
4001
+ this.format = options.responseFormat ?? "wav";
4002
+ this.timeoutMs = options.timeoutMs ?? 8e3;
4003
+ this.cooldownMs = options.cooldownMs ?? 3e4;
4004
+ this.fetchImpl = options.fetchImpl ?? fetch;
4005
+ this.now = options.now ?? Date.now;
4006
+ this.lastMime = MIME2[this.format];
4007
+ }
4008
+ get mime() {
4009
+ return this.lastMime;
4010
+ }
4011
+ updateVoice(voice, rate) {
4012
+ this.voice = voice.trim() || this.options.voice?.trim() || MIMO_DEFAULT_VOICE;
4013
+ if (rate !== void 0 && Number.isFinite(rate)) this.rate = rate;
4014
+ }
4015
+ /** 合成并**随结果返回**本句专属 MIME(B6:不从共享 this.lastMime 事后回读,并发异构容器不串味)。 */
4016
+ async synthesizeWithMime(text, options = {}) {
4017
+ if (this.closed) throw new MimoTtsError("mimo_closed", "remote TTS engine closed");
4018
+ const input = stripEmotionTags(text).replace(/\s+/g, " ").trim();
4019
+ if (input === "") return { buf: Buffer.alloc(0), mime: this.lastMime };
4020
+ if (this.now() >= this.downUntil) {
4021
+ try {
4022
+ const res = await this.remote(input, options);
4023
+ this.lastError = void 0;
4024
+ return res;
4025
+ } catch (e) {
4026
+ if (this.closed) throw new MimoTtsError("mimo_closed", "remote TTS engine closed");
4027
+ if (e.name === "AbortError" && !(e instanceof MimoTtsError)) throw e;
4028
+ const err = e instanceof MimoTtsError ? e : new MimoTtsError("mimo_unreachable", String(e));
4029
+ this.lastError = err;
4030
+ this.downUntil = this.now() + this.cooldownMs;
4031
+ if (!this.options.fallback) throw err;
4032
+ console.warn(`[dsh-voice-mode] remote TTS failed, using the local fallback for ${this.cooldownMs} ms: ${redactSecrets(err)}`);
4033
+ }
4034
+ }
4035
+ if (this.closed) throw new MimoTtsError("mimo_closed", "remote TTS engine closed");
4036
+ return this.viaFallback(text, options);
4037
+ }
4038
+ async synthesize(text, options = {}) {
4039
+ return (await this.synthesizeWithMime(text, options)).buf;
4040
+ }
4041
+ /** 自然语言风格指令:配置的 instructions + 语速(MiMo 无 speed 字段,语速走风格控制)。 */
4042
+ styleInstruction(rate) {
4043
+ const parts = [];
4044
+ const base = (this.options.instructions ?? "").trim();
4045
+ if (base) parts.push(base);
4046
+ if (rate !== void 0 && Number.isFinite(rate) && rate > 0 && rate !== 1) {
4047
+ parts.push(mimoSpeedInstruction(rate));
4048
+ }
4049
+ return parts.join("; ");
4050
+ }
4051
+ async remote(input, options) {
4052
+ if (this.url === null) throw this.configError;
4053
+ const messages = [];
4054
+ const instruction = this.styleInstruction(options.rate ?? this.rate);
4055
+ if (instruction) messages.push({ role: "user", content: instruction });
4056
+ messages.push({ role: "assistant", content: input });
4057
+ const body = {
4058
+ model: (this.options.model ?? "").trim() || MIMO_DEFAULT_MODEL,
4059
+ messages,
4060
+ audio: { voice: (options.voice || this.voice).trim(), format: this.format },
4061
+ stream: false
4062
+ };
4063
+ const headers = { "content-type": "application/json" };
4064
+ headers["api-key"] = (this.options.apiKey ?? "").trim();
4065
+ const ac = new AbortController();
4066
+ let timedOut = false;
4067
+ const timer = setTimeout(() => {
4068
+ timedOut = true;
4069
+ ac.abort();
4070
+ }, this.timeoutMs);
4071
+ this.inflight.add(ac);
4072
+ try {
4073
+ const res = await this.fetchImpl(this.url, {
4074
+ method: "POST",
4075
+ headers,
4076
+ body: JSON.stringify(body),
4077
+ signal: ac.signal,
4078
+ redirect: "error"
4079
+ });
4080
+ if (!res.ok) {
4081
+ const rawErr = await readMimoBytes(res, MAX_ERROR_BYTES2, true).then((b) => b.toString("utf8"), () => "");
4082
+ const detail = redactBodySnippet(rawErr);
4083
+ throw new MimoTtsError("mimo_http_error", `HTTP ${res.status}${detail ? `: ${detail}` : ""}`);
4084
+ }
4085
+ const rawJson = (await readMimoBytes(res, MAX_JSON_BYTES, false)).toString("utf8");
4086
+ let parsed;
4087
+ try {
4088
+ parsed = JSON.parse(rawJson);
4089
+ } catch {
4090
+ throw new MimoTtsError("mimo_bad_payload", "non-JSON response from MiMo TTS");
4091
+ }
4092
+ const data = extractMimoAudio(parsed);
4093
+ if (!data) throw new MimoTtsError("mimo_empty_audio", "empty audio");
4094
+ const buf = decodeBase64Audio(data);
4095
+ if (buf.length === 0) throw new MimoTtsError("mimo_empty_audio", "empty audio");
4096
+ const ctype = (res.headers.get("content-type") ?? "").toLowerCase();
4097
+ const sniffed = sniffAudioMime(buf, "");
4098
+ let mime;
4099
+ if (sniffed) mime = sniffed;
4100
+ else if (ctype.startsWith("audio/")) mime = ctype.split(";")[0].trim();
4101
+ else throw new MimoTtsError("mimo_bad_payload", `non-audio response (content-type: ${ctype || "none"})`);
4102
+ this.lastMime = mime;
4103
+ return { buf, mime };
4104
+ } catch (e) {
4105
+ if (timedOut) throw new MimoTtsError("mimo_timeout", `no audio within ${this.timeoutMs} ms`);
4106
+ throw e;
4107
+ } finally {
4108
+ clearTimeout(timer);
4109
+ this.inflight.delete(ac);
4110
+ }
4111
+ }
4112
+ async viaFallback(text, options) {
4113
+ if (this.closed) throw new MimoTtsError("mimo_closed", "remote TTS engine closed");
4114
+ if (!this.options.fallback) {
4115
+ throw this.lastError ?? new MimoTtsError("mimo_unreachable", "remote TTS unavailable");
4116
+ }
4117
+ this.fallbackEngine ??= this.options.fallback();
4118
+ const fb = this.fallbackEngine;
4119
+ const rateOpt = { rate: options.rate ?? this.rate };
4120
+ const res = fb.synthesizeWithMime ? await fb.synthesizeWithMime(text, rateOpt) : { buf: await fb.synthesize(text, rateOpt), mime: fb.mime };
4121
+ this.lastMime = res.mime;
4122
+ return res;
4123
+ }
4124
+ interrupt() {
4125
+ for (const ac of this.inflight) ac.abort();
4126
+ this.inflight.clear();
4127
+ this.fallbackEngine?.interrupt?.();
4128
+ }
4129
+ status() {
4130
+ const err = this.lastError ?? this.configError;
4131
+ const fallingBack = this.now() < this.downUntil;
4132
+ return {
4133
+ engine: "mimo",
4134
+ // 冷却期(远程失败后走本地回退)同样视为非就绪,与 openai 引擎同口径。
4135
+ ready: !fallingBack && !this.configError,
4136
+ loading: false,
4137
+ error: err?.message,
4138
+ errorCode: err?.code,
4139
+ keyPresent: Boolean(this.options.apiKey && this.options.apiKey.trim().length > 0)
4140
+ };
4141
+ }
4142
+ async close() {
4143
+ this.closed = true;
4144
+ this.interrupt();
4145
+ const fb = this.fallbackEngine;
4146
+ this.fallbackEngine = null;
4147
+ await fb?.close();
4148
+ }
4149
+ };
4150
+
2978
4151
  // src/settings-store.ts
2979
- import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4152
+ import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2980
4153
  import { homedir } from "node:os";
2981
4154
  import { dirname, join as join4 } from "node:path";
2982
4155
  var SETTINGS_FILE_NAME = "voice-mode.settings.json";
@@ -3018,12 +4191,20 @@ function readOverrides(file, keys) {
3018
4191
  function writeOverrides(file, values) {
3019
4192
  mkdirSync(dirname(file), { recursive: true });
3020
4193
  const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
3021
- writeFileSync(tmp, JSON.stringify(values, null, 2) + "\n", { encoding: "utf8", mode: 384 });
3022
4194
  try {
3023
- chmodSync(tmp, 384);
3024
- } catch {
4195
+ writeFileSync(tmp, JSON.stringify(values, null, 2) + "\n", { encoding: "utf8", mode: 384 });
4196
+ try {
4197
+ chmodSync(tmp, 384);
4198
+ } catch {
4199
+ }
4200
+ renameSync(tmp, file);
4201
+ } catch (e) {
4202
+ try {
4203
+ unlinkSync(tmp);
4204
+ } catch {
4205
+ }
4206
+ throw e;
3025
4207
  }
3026
- renameSync(tmp, file);
3027
4208
  }
3028
4209
  function parseLegacyVoiceSection(text) {
3029
4210
  const out = {};
@@ -3076,10 +4257,12 @@ var NS_VOICE_MODE = "voice-mode";
3076
4257
  var MUTED_STREAMS_WITHOUT_TURN = 4;
3077
4258
  var BASE_PATH = "/voice-mode";
3078
4259
  var PREVIEW_NETWORK_PATTERN = /fetch failed|ECONN|ENOTFOUND|getaddrinfo|ETIMEDOUT|EAI_AGAIN|network|unreachable|socket hang up|aborted|WebSocket error/i;
3079
- var PREVIEW_ENGINE_PATTERN = /model download|model verify|init failed|child exited|tts child|local TTS|prepare|sherpa|local Kokoro/i;
3080
- var PREVIEW_TEXT_PATTERN = /empty or invalid audio|invalid audio|invalid text|too long|truncat/i;
4260
+ var PREVIEW_AUTH_PATTERN = /HTTP 401|HTTP 403|unauthorized|invalid[ _-]?api[ _-]?key|incorrect api key|authentication failed|missing api key/i;
4261
+ var PREVIEW_ENGINE_PATTERN = /model download|model verify|init failed|child exited|tts child|local TTS|prepare|sherpa|local Kokoro|closed|init cooldown/i;
4262
+ var PREVIEW_TEXT_PATTERN = /empty or invalid audio|invalid audio|invalid text|too long|truncat|exceeds \d+ bytes|bad_payload|bad_audio|invalid base64|textual body/i;
3081
4263
  function classifyPreviewError(msg) {
3082
4264
  if (PREVIEW_TEXT_PATTERN.test(msg)) return "text";
4265
+ if (PREVIEW_AUTH_PATTERN.test(msg)) return "auth";
3083
4266
  if (PREVIEW_NETWORK_PATTERN.test(msg)) return "network";
3084
4267
  if (PREVIEW_ENGINE_PATTERN.test(msg)) return "engine";
3085
4268
  return "unknown";
@@ -3088,6 +4271,7 @@ var PREVIEW_ERROR_CODES = {
3088
4271
  network: "preview_network",
3089
4272
  engine: "preview_engine",
3090
4273
  text: "preview_text",
4274
+ auth: "preview_auth",
3091
4275
  unknown: "preview_unknown"
3092
4276
  };
3093
4277
  var respondJson2 = (res, status, payload) => {
@@ -3133,6 +4317,16 @@ var VOICE_SETTINGS_DEFAULTS = {
3133
4317
  bargeInSalvage: true,
3134
4318
  // Issue #15 批 4:LLM 纠错默认关(默认开=未申报的 I10 豁免+每条多一次 RTT/token)。
3135
4319
  llmCorrect: false,
4320
+ // E1:在线预设默认空 = 手动(沿用 Config 文件值,零行为变化)。
4321
+ openaiPreset: "",
4322
+ openaiBaseUrl: "",
4323
+ openaiModel: "",
4324
+ openaiApiKey: "",
4325
+ // Q2 Key 跟预设走:面板按预设存的 key 表(空对象 = 全未配)。
4326
+ openaiApiKeys: {},
4327
+ mimoApiKey: "",
4328
+ // P1-3:纠错词表默认空(与 Config 层 asrReplacements 默认 [] 对齐)。
4329
+ asrReplacements: [],
3136
4330
  // 批 G 任务 3:让位窗口默认 1500ms(与改造前批 5 行为字节等价;用户可调 500-3000ms)。
3137
4331
  yieldMs: 1500
3138
4332
  };
@@ -3165,130 +4359,167 @@ var DESC = {
3165
4359
  backchannelYield: en.descBackchannelYield,
3166
4360
  bargeInSalvage: en.descBargeInSalvage,
3167
4361
  llmCorrect: en.descLlmCorrect,
4362
+ openaiPreset: en.descOpenaiPreset,
4363
+ openaiBaseUrl: en.descOpenaiBaseUrl,
4364
+ openaiModel: en.descOpenaiModel,
4365
+ openaiApiKey: en.descOpenaiApiKey,
4366
+ openaiApiKeys: en.descOpenaiApiKeys,
4367
+ mimoApiKey: en.descMimoApiKey,
4368
+ asrReplacements: en.descAsrReplacements,
3168
4369
  yieldMs: en.descYieldMs
3169
4370
  };
3170
4371
  function createVoiceSettingsSchema(defs) {
3171
4372
  const d = { ...VOICE_SETTINGS_DEFAULTS, ...defs };
3172
- return z.object({
3173
- ttsEngine: z.union([z.const("vits"), z.const("kokoro"), z.const("edge"), z.const("openai")]).default(d.ttsEngine).description(
4373
+ return z2.object({
4374
+ ttsEngine: z2.union(TTS_ENGINE_KINDS.map((k) => z2.const(k))).default(d.ttsEngine).description(
3174
4375
  DESC.ttsEngine
3175
4376
  ),
3176
- kokoroModel: z.union([z.const("int8"), z.const("fp32")]).default(d.kokoroModel).description(
4377
+ kokoroModel: z2.union([z2.const("int8"), z2.const("fp32")]).default(d.kokoroModel).description(
3177
4378
  DESC.kokoroModel
3178
4379
  ),
3179
- voice: z.string().default(d.voice).description(
4380
+ voice: z2.string().default(d.voice).description(
3180
4381
  DESC.voice
3181
4382
  ),
3182
- rate: z.number().min(0.5).max(2).default(d.rate).description(DESC.rate),
3183
- interruptLevel: z.union([z.const(0), z.const(1), z.const(2)]).default(d.interruptLevel).description(
4383
+ rate: z2.number().min(0.5).max(2).default(d.rate).description(DESC.rate),
4384
+ interruptLevel: z2.union([z2.const(0), z2.const(1), z2.const(2)]).default(d.interruptLevel).description(
3184
4385
  DESC.interruptLevel
3185
4386
  ),
3186
- silenceMs: z.number().min(500).max(3e4).default(d.silenceMs).description(DESC.silenceMs),
3187
- idleTimeoutMinutes: z.number().min(1).max(120).default(d.idleTimeoutMinutes).description(DESC.idleTimeoutMinutes),
3188
- modelHost: z.string().default(d.modelHost).description(DESC.modelHost),
3189
- autoSend: z.boolean().default(d.autoSend).description(DESC.autoSend),
4387
+ silenceMs: z2.number().min(500).max(3e4).default(d.silenceMs).description(DESC.silenceMs),
4388
+ idleTimeoutMinutes: z2.number().min(1).max(120).default(d.idleTimeoutMinutes).description(DESC.idleTimeoutMinutes),
4389
+ modelHost: z2.string().default(d.modelHost).description(DESC.modelHost),
4390
+ autoSend: z2.boolean().default(d.autoSend).description(DESC.autoSend),
3190
4391
  // 批 7N 重做 5/5:与 strings.ts descAutoResume 同步——明确「下次进入语音会话即生效」。
3191
- autoResume: z.boolean().default(d.autoResume).description(DESC.autoResume),
3192
- mode: z.union([z.const("toggle"), z.const("hold"), z.const("once")]).default(d.mode).description(DESC.mode),
3193
- readAloud: z.union([z.const("voice"), z.const("always"), z.const("off")]).default(d.readAloud).description(DESC.readAloud),
3194
- showCaptions: z.boolean().default(d.showCaptions).description(DESC.showCaptions),
3195
- showStatusBar: z.boolean().default(d.showStatusBar).description(DESC.showStatusBar),
3196
- composerShortcut: z.string().default(d.composerShortcut).description(DESC.composerShortcut),
3197
- bargeInMode: z.union([z.const("auto"), z.const("manual"), z.const("detect")]).default(d.bargeInMode).description(DESC.bargeInMode),
3198
- echoGateDb: z.number().min(3).max(12).default(d.echoGateDb).description(
4392
+ autoResume: z2.boolean().default(d.autoResume).description(DESC.autoResume),
4393
+ mode: z2.union([z2.const("toggle"), z2.const("hold"), z2.const("once")]).default(d.mode).description(DESC.mode),
4394
+ readAloud: z2.union([z2.const("voice"), z2.const("always"), z2.const("off")]).default(d.readAloud).description(DESC.readAloud),
4395
+ showCaptions: z2.boolean().default(d.showCaptions).description(DESC.showCaptions),
4396
+ showStatusBar: z2.boolean().default(d.showStatusBar).description(DESC.showStatusBar),
4397
+ composerShortcut: z2.string().default(d.composerShortcut).description(DESC.composerShortcut),
4398
+ bargeInMode: z2.union([z2.const("auto"), z2.const("manual"), z2.const("detect")]).default(d.bargeInMode).description(DESC.bargeInMode),
4399
+ echoGateDb: z2.number().min(3).max(12).default(d.echoGateDb).description(
3199
4400
  DESC.echoGateDb
3200
4401
  ),
3201
- shortcut: z.string().default(d.shortcut).description(DESC.shortcut),
3202
- spokenFormat: z.boolean().default(d.spokenFormat).description(DESC.spokenFormat),
3203
- senseVoice: z.boolean().default(d.senseVoice).description(DESC.senseVoice),
3204
- wakeWord: z.string().default(d.wakeWord).description(DESC.wakeWord),
3205
- toolBeep: z.boolean().default(d.toolBeep).description(DESC.toolBeep),
3206
- senseITN: z.boolean().default(d.senseITN).description(DESC.senseITN),
3207
- captionFontSize: z.union([z.const(0), z.const(1), z.const(2), z.const(3)]).default(d.captionFontSize).description(
4402
+ shortcut: z2.string().default(d.shortcut).description(DESC.shortcut),
4403
+ spokenFormat: z2.boolean().default(d.spokenFormat).description(DESC.spokenFormat),
4404
+ senseVoice: z2.boolean().default(d.senseVoice).description(DESC.senseVoice),
4405
+ wakeWord: z2.string().default(d.wakeWord).description(DESC.wakeWord),
4406
+ toolBeep: z2.boolean().default(d.toolBeep).description(DESC.toolBeep),
4407
+ senseITN: z2.boolean().default(d.senseITN).description(DESC.senseITN),
4408
+ captionFontSize: z2.union([z2.const(0), z2.const(1), z2.const(2), z2.const(3)]).default(d.captionFontSize).description(
3208
4409
  DESC.captionFontSize
3209
4410
  ),
3210
- captionMaxWidth: z.union([z.const(0), z.const(1), z.const(2)]).default(d.captionMaxWidth).description(
4411
+ captionMaxWidth: z2.union([z2.const(0), z2.const(1), z2.const(2)]).default(d.captionMaxWidth).description(
3211
4412
  DESC.captionMaxWidth
3212
4413
  ),
3213
- backchannelYield: z.boolean().default(d.backchannelYield).description(
4414
+ backchannelYield: z2.boolean().default(d.backchannelYield).description(
3214
4415
  DESC.backchannelYield
3215
4416
  ),
3216
4417
  // Issue #15 批 1 / ADR-0012:打断语音抢救(默认 true,I10 有意豁免)。
3217
- bargeInSalvage: z.boolean().default(d.bargeInSalvage).description(
4418
+ bargeInSalvage: z2.boolean().default(d.bargeInSalvage).description(
3218
4419
  DESC.bargeInSalvage
3219
4420
  ),
3220
4421
  // Issue #15 批 4:LLM 纠错(默认 false)。
3221
- llmCorrect: z.boolean().default(d.llmCorrect).description(
4422
+ llmCorrect: z2.boolean().default(d.llmCorrect).description(
3222
4423
  DESC.llmCorrect
3223
4424
  ),
3224
- yieldMs: z.number().min(500).max(3e3).default(d.yieldMs).description(
4425
+ // E1:在线预设 id('' = 手动沿用 Config 文件;已知 id 见 tts-openai.ts OPENAI_PRESETS)。
4426
+ openaiPreset: z2.string().default(d.openaiPreset).description(
4427
+ DESC.openaiPreset
4428
+ ),
4429
+ // 2026-11-19:在线 TTS 的 URL/模型/key 允许在设置卡片里填(不必改 profile YAML)。
4430
+ openaiBaseUrl: z2.string().default(d.openaiBaseUrl).description(DESC.openaiBaseUrl),
4431
+ openaiModel: z2.string().default(d.openaiModel).description(DESC.openaiModel),
4432
+ // secret:GET /settings 会把它抹成空串,只回 hasOpenaiApiKey 布尔;POST 可写。
4433
+ openaiApiKey: z2.string().role("secret").default(d.openaiApiKey).description(DESC.openaiApiKey),
4434
+ // Q2 Key 跟预设走:面板按预设存的 key 表(值须为字符串;非字符串由 zod 拒收回 400)。
4435
+ openaiApiKeys: z2.dict(z2.string()).default(d.openaiApiKeys ?? {}).description(DESC.openaiApiKeys),
4436
+ mimoApiKey: z2.string().role("secret").default(d.mimoApiKey).description(DESC.mimoApiKey),
4437
+ // P1-3:用户纠错词表(默认空;非法条目由 zod 整表拒绝,POST 回 400;上限 200 条与设置卡片一致,防超大覆盖层)。
4438
+ asrReplacements: z2.array(AsrReplacementSchema).max(200).default(d.asrReplacements).description(
4439
+ DESC.asrReplacements
4440
+ ),
4441
+ yieldMs: z2.number().min(500).max(3e3).default(d.yieldMs).description(
3225
4442
  DESC.yieldMs
3226
4443
  )
3227
4444
  });
3228
4445
  }
3229
4446
  var VoiceSettingsSchema = createVoiceSettingsSchema();
3230
- var OpenAiTtsConfig = z.object({
3231
- baseUrl: z.string().default("").description("API base URL, e.g. https://api.openai.com/v1, https://openrouter.ai/api/v1 or a self-hosted server."),
3232
- apiKey: z.string().role("secret").default("").description("Bearer key; leave empty for servers without auth."),
3233
- model: z.string().default("").description("Model name sent to the server."),
3234
- voice: z.string().default("").description("Default voice name on the server (the voice setting overrides it)."),
3235
- instructions: z.string().default("").description("Optional style instructions for models that accept them."),
3236
- responseFormat: z.union([z.const("mp3"), z.const("wav")]).default("mp3"),
3237
- timeoutMs: z.number().min(1e3).max(6e4).default(8e3).description("Per-sentence timeout; slower counts as unavailable."),
3238
- fallback: z.union([z.const("none"), z.const("vits"), z.const("kokoro")]).default("none").description("Local engine used while the server is unreachable or slow."),
3239
- fallbackVoice: z.string().default("").description("Voice for the fallback engine (empty = its default).")
4447
+ var OpenAiTtsConfig = z2.object({
4448
+ baseUrl: z2.string().default("").description("API base URL, e.g. https://api.openai.com/v1, https://openrouter.ai/api/v1 or a self-hosted server."),
4449
+ apiKey: z2.string().role("secret").default("").description("Bearer key; leave empty for servers without auth."),
4450
+ apiKeys: z2.dict(z2.string().role("secret")).role("secret").default({}).description("Per-preset key override keyed by preset id (apiKeys[id] wins over apiKey). Keeps one credential per provider without editing the single key on every switch."),
4451
+ model: z2.string().default("").description("Model name sent to the server."),
4452
+ voice: z2.string().default("").description("Default voice name on the server (the voice setting overrides it)."),
4453
+ instructions: z2.string().default("").description("Optional style instructions for models that accept them."),
4454
+ responseFormat: z2.union([z2.const("mp3"), z2.const("wav")]).default("mp3"),
4455
+ timeoutMs: z2.number().min(1e3).max(6e4).default(8e3).description("Per-sentence timeout; slower counts as unavailable."),
4456
+ fallback: z2.union([z2.const("none"), z2.const("vits"), z2.const("kokoro")]).default("none").description("Local engine used while the server is unreachable or slow."),
4457
+ fallbackVoice: z2.string().default("").description("Voice for the fallback engine (empty = its default).")
3240
4458
  });
3241
- var Config = z.object({
3242
- enabled: z.boolean().default(true),
3243
- cacheDir: z.string().default(defaultModelCacheDir()),
3244
- modelHost: z.string().default("https://huggingface.co"),
3245
- ttsEngine: z.union([z.const("edge"), z.const("vits"), z.const("kokoro"), z.const("openai")]).default("edge"),
4459
+ var MimoTtsConfig = z2.object({
4460
+ apiKey: z2.string().role("secret").default("").description("MiMo API key (sent as the api-key header; never reuse another vendor key here)."),
4461
+ baseUrl: z2.string().default("https://api.xiaomimimo.com/v1").description("MiMo API base URL; defaults to the official endpoint."),
4462
+ model: z2.string().default("mimo-v2.5-tts").description("Model id: mimo-v2.5-tts / mimo-v2.5-tts-voicedesign / mimo-v2.5-tts-voiceclone."),
4463
+ voice: z2.string().default("mimo_default").description("Preset voice id (the voice setting overrides it)."),
4464
+ instructions: z2.string().default("").description("Natural-language style instruction (emotion, dialect, pace)."),
4465
+ responseFormat: z2.union([z2.const("wav"), z2.const("mp3")]).default("wav").description("Container format; raw pcm is not supported because it cannot be labelled with a decodable MIME."),
4466
+ timeoutMs: z2.number().min(1e3).max(6e4).default(8e3).description("Per-sentence timeout; slower counts as unavailable."),
4467
+ fallback: z2.union([z2.const("none"), z2.const("vits"), z2.const("kokoro")]).default("none").description("Local engine used while the server is unreachable or slow."),
4468
+ fallbackVoice: z2.string().default("").description("Voice for the fallback engine (empty = its default).")
4469
+ });
4470
+ var Config = z2.object({
4471
+ enabled: z2.boolean().default(true),
4472
+ cacheDir: z2.string().default(defaultModelCacheDir()),
4473
+ modelHost: z2.string().default("https://huggingface.co"),
4474
+ ttsEngine: z2.union(TTS_ENGINE_KINDS.map((k) => z2.const(k))).default("edge"),
3246
4475
  openaiTts: OpenAiTtsConfig,
3247
- kokoroModel: z.union([z.const("int8"), z.const("fp32")]).default("int8"),
3248
- allowLan: z.boolean().default(false),
3249
- allowCustomModelHost: z.boolean().default(false),
3250
- voice: z.string().default("zh-CN-XiaoxiaoNeural"),
4476
+ mimoTts: MimoTtsConfig,
4477
+ kokoroModel: z2.union([z2.const("int8"), z2.const("fp32")]).default("int8"),
4478
+ allowLan: z2.boolean().default(false),
4479
+ asrReplacements: z2.array(AsrReplacementSchema).default([]),
4480
+ allowCustomModelHost: z2.boolean().default(false),
4481
+ voice: z2.string().default("zh-CN-XiaoxiaoNeural"),
3251
4482
  // I3(Issue #15 审查 Important):数值旋钮补 min/max,与 VoiceSettingsValue schema
3252
4483
  // (createVoiceSettingsSchema)逐字段一致。早年 Config 层是裸 z.number()——cordis.patch.yml
3253
4484
  // 手滑写 rate:5 会得到五倍速朗读、silenceMs:10 会把每句话按音节碎切,且没有任何一层会拦。
3254
4485
  // 两层同界:Config 是 baseline、settings schema 是覆盖层,任一层失守都让非法值直达运行时。
3255
- rate: z.number().min(0.5).max(2).default(1.1),
3256
- interruptLevel: z.union([z.const(0), z.const(1), z.const(2)]).default(0),
3257
- silenceMs: z.number().min(500).max(3e4).default(1500),
3258
- idleTimeoutMinutes: z.number().min(1).max(120).default(5),
4486
+ rate: z2.number().min(0.5).max(2).default(1.1),
4487
+ interruptLevel: z2.union([z2.const(0), z2.const(1), z2.const(2)]).default(0),
4488
+ silenceMs: z2.number().min(500).max(3e4).default(1500),
4489
+ idleTimeoutMinutes: z2.number().min(1).max(120).default(5),
3259
4490
  // 设置面板字段(与 VoiceSettingsValue 一一对应;0.1.7+ 由插件自身 Config 派生读取)。
3260
4491
  // 注意:刻意不标 .volatile() —— schemastery 3.18.4 的 volatile 会破坏 schema 函数
3261
4492
  // 调用形态(sv({}) → {field:{}}),而 0.1.5-rc.3 起的设置分层会调用插件 Config 做
3262
4493
  // merge,{} 透过 mergeLayers 污染并触发 ValidationError(2026-09-23 实测)。
3263
4494
  // 0.1.7 功能读取走 config 直接读,不依赖 volatile(仅官方 UI 自动投影受影响,
3264
4495
  // 本插件自带 settings-form 设置面板 + /voice-mode/config,不受影响)。
3265
- autoSend: z.boolean().default(true),
3266
- autoResume: z.boolean().default(false),
3267
- mode: z.union([z.const("toggle"), z.const("hold"), z.const("once")]).default("toggle"),
3268
- readAloud: z.union([z.const("voice"), z.const("always"), z.const("off")]).default("voice"),
3269
- showCaptions: z.boolean().default(true),
3270
- showStatusBar: z.boolean().default(true),
3271
- bargeInMode: z.union([z.const("auto"), z.const("manual"), z.const("detect")]).default("detect"),
4496
+ autoSend: z2.boolean().default(true),
4497
+ autoResume: z2.boolean().default(false),
4498
+ mode: z2.union([z2.const("toggle"), z2.const("hold"), z2.const("once")]).default("toggle"),
4499
+ readAloud: z2.union([z2.const("voice"), z2.const("always"), z2.const("off")]).default("voice"),
4500
+ showCaptions: z2.boolean().default(true),
4501
+ showStatusBar: z2.boolean().default(true),
4502
+ bargeInMode: z2.union([z2.const("auto"), z2.const("manual"), z2.const("detect")]).default("detect"),
3272
4503
  // I3 + M7(zod 界):echoGateDb / yieldMs 与 settings schema 同界(3-12 dB / 500-3000ms)。
3273
4504
  // client 与 NumberField 虽会 clamp,但那只是 UI 兜底——Config 层无界时 YAML 手滑
3274
4505
  // 仍可把回声门阈设成 0(句句误打断)或让位窗口设成 60000(让位后一分钟不说话)。
3275
- echoGateDb: z.number().min(3).max(12).default(6),
3276
- shortcut: z.string().default("Ctrl+Shift+V"),
3277
- composerShortcut: z.string().default("Alt+Enter"),
3278
- spokenFormat: z.boolean().default(true),
3279
- senseVoice: z.boolean().default(true),
3280
- wakeWord: z.string().default(""),
3281
- toolBeep: z.boolean().default(false),
3282
- senseITN: z.boolean().default(true),
3283
- captionFontSize: z.union([z.const(0), z.const(1), z.const(2), z.const(3)]).default(0),
3284
- captionMaxWidth: z.union([z.const(0), z.const(1), z.const(2)]).default(1),
3285
- backchannelYield: z.boolean().default(true),
4506
+ echoGateDb: z2.number().min(3).max(12).default(6),
4507
+ shortcut: z2.string().default("Ctrl+Shift+V"),
4508
+ composerShortcut: z2.string().default("Alt+Enter"),
4509
+ spokenFormat: z2.boolean().default(true),
4510
+ senseVoice: z2.boolean().default(true),
4511
+ wakeWord: z2.string().default(""),
4512
+ toolBeep: z2.boolean().default(false),
4513
+ senseITN: z2.boolean().default(true),
4514
+ captionFontSize: z2.union([z2.const(0), z2.const(1), z2.const(2), z2.const(3)]).default(0),
4515
+ captionMaxWidth: z2.union([z2.const(0), z2.const(1), z2.const(2)]).default(1),
4516
+ backchannelYield: z2.boolean().default(true),
3286
4517
  // Issue #15 批 4:LLM 纠错默认关。
3287
- llmCorrect: z.boolean().default(false),
4518
+ llmCorrect: z2.boolean().default(false),
3288
4519
  // Issue #15 批 1 / ADR-0012:打断语音抢救(默认 true,I10 有意豁免)。
3289
- bargeInSalvage: z.boolean().default(true),
4520
+ bargeInSalvage: z2.boolean().default(true),
3290
4521
  // I3 + M7(zod 界):500-3000ms,与 settings schema 一致。
3291
- yieldMs: z.number().min(500).max(3e3).default(1500)
4522
+ yieldMs: z2.number().min(500).max(3e3).default(1500)
3292
4523
  });
3293
4524
  function displayOf(v) {
3294
4525
  return { readAloud: v.readAloud, showCaptions: v.showCaptions, showStatusBar: v.showStatusBar };
@@ -3323,7 +4554,8 @@ function voiceSettingsFromConfig(config) {
3323
4554
  backchannelYield,
3324
4555
  yieldMs,
3325
4556
  bargeInSalvage,
3326
- llmCorrect
4557
+ llmCorrect,
4558
+ asrReplacements
3327
4559
  } = config;
3328
4560
  return {
3329
4561
  ttsEngine,
@@ -3354,7 +4586,16 @@ function voiceSettingsFromConfig(config) {
3354
4586
  backchannelYield,
3355
4587
  yieldMs,
3356
4588
  bargeInSalvage,
3357
- llmCorrect
4589
+ llmCorrect,
4590
+ asrReplacements,
4591
+ // E1:预设无 Config 基线(用户覆盖层专属),默认空 = 手动。
4592
+ openaiPreset: "",
4593
+ // 在线 TTS 的 UI 覆盖默认空:未填时按预设/配置文件走(零行为变化)。
4594
+ openaiBaseUrl: "",
4595
+ openaiModel: "",
4596
+ openaiApiKey: "",
4597
+ openaiApiKeys: {},
4598
+ mimoApiKey: ""
3358
4599
  };
3359
4600
  }
3360
4601
  function apply(ctx, config) {
@@ -3388,8 +4629,9 @@ function apply(ctx, config) {
3388
4629
  if (sessionId === null || sessionId === activeVoiceSession || tapInFlight.has(sessionId)) return;
3389
4630
  dropTurnTables(sessionId);
3390
4631
  };
3391
- const stopFocusReading = (sessionId) => {
4632
+ const stopFocusReading = (sessionId, fromTabId) => {
3392
4633
  if (sessionId === null) return;
4634
+ if (sessionId === activeVoiceSession && activeTabId !== null && fromTabId !== activeTabId) return;
3393
4635
  queue.cancel(sessionId);
3394
4636
  turnGen.set(sessionId, (turnGen.get(sessionId) ?? 0) + 1);
3395
4637
  };
@@ -3460,22 +4702,32 @@ function apply(ctx, config) {
3460
4702
  NS_VOICE_MODE,
3461
4703
  createVoiceSettingsSchema(),
3462
4704
  {
3463
- base: {
3464
- ttsEngine: config.ttsEngine,
3465
- voice: config.voice,
3466
- rate: config.rate,
3467
- interruptLevel: config.interruptLevel,
3468
- silenceMs: config.silenceMs,
3469
- idleTimeoutMinutes: config.idleTimeoutMinutes,
3470
- modelHost: config.modelHost
3471
- }
4705
+ // base 用**全量** Config 映射:此前只给 7 键,其余落到 schema 默认值;旧宿主若 get() 返回
4706
+ // 全量,config 基线(如 voice/rate 之外的 openaiPreset 等)会被默认值覆盖(A3 审计 Minor)。
4707
+ base: voiceSettingsFromConfig(config)
3472
4708
  }
3473
4709
  );
3474
- vset = settingsScope.get();
4710
+ const fromScope = settingsScope.get() ?? {};
4711
+ try {
4712
+ vset = resolveSettings(fromScope);
4713
+ } catch (e) {
4714
+ console.warn(`[dsh-voice-mode] settings scope returned invalid values; keeping valid keys only: ${redactSecrets(e)}`);
4715
+ const salvaged = {};
4716
+ for (const k of SETTING_KEYS) {
4717
+ if (!(k in fromScope)) continue;
4718
+ try {
4719
+ resolveSettings({ [k]: fromScope[k] });
4720
+ salvaged[k] = fromScope[k];
4721
+ } catch {
4722
+ console.warn(`[dsh-voice-mode] ignoring invalid setting from host scope: ${k}`);
4723
+ }
4724
+ }
4725
+ vset = resolveSettings(salvaged);
4726
+ }
3475
4727
  settingsScopeRef = settingsScope;
3476
4728
  } else {
3477
4729
  const loaded = readOverrides(settingsFile, SETTING_KEYS);
3478
- if (loaded.warn) console.warn(`[dsh-voice-mode] ignoring settings overlay ${settingsFile}: ${loaded.warn}`);
4730
+ if (loaded.warn) console.warn(`[dsh-voice-mode] ignoring settings overlay ${settingsFile}: ${redactSecrets(loaded.warn)}`);
3479
4731
  let migrated = false;
3480
4732
  if (!loaded.exists) {
3481
4733
  const legacy = readLegacyVoiceSettings(dirname2(settingsFile), SETTING_KEYS);
@@ -3490,7 +4742,7 @@ function apply(ctx, config) {
3490
4742
  resolveSettings({ [k]: v });
3491
4743
  valid[k] = v;
3492
4744
  } catch (e) {
3493
- console.warn(`[dsh-voice-mode] ignoring invalid settings override "${k}" (falling back to the Config baseline): ${String(e).slice(0, 160)}`);
4745
+ console.warn(`[dsh-voice-mode] ignoring invalid settings override "${k}" (falling back to the Config baseline): ${redactSecrets(e).slice(0, 160)}`);
3494
4746
  }
3495
4747
  }
3496
4748
  try {
@@ -3501,14 +4753,25 @@ function apply(ctx, config) {
3501
4753
  writeOverrides(settingsFile, valid);
3502
4754
  console.log(`[dsh-voice-mode] migrated ${Object.keys(valid).length} setting(s) from the legacy settings.yaml to ${settingsFile}`);
3503
4755
  } catch (e) {
3504
- console.warn(`[dsh-voice-mode] legacy settings migration could not be saved (still in effect for this run): ${String(e)}`);
4756
+ console.warn(`[dsh-voice-mode] legacy settings migration could not be saved (still in effect for this run): ${redactSecrets(e)}`);
3505
4757
  }
3506
4758
  }
3507
4759
  } catch (e) {
3508
- console.warn(`[dsh-voice-mode] settings overlay failed validation as a whole; falling back to the Config baseline: ${String(e)}`);
4760
+ console.warn(`[dsh-voice-mode] settings overlay failed validation as a whole; falling back to the Config baseline: ${redactSecrets(e)}`);
3509
4761
  vset = voiceSettingsFromConfig(config);
3510
4762
  }
3511
4763
  }
4764
+ let replacementHits = [];
4765
+ let replacementRuleCount = 0;
4766
+ const replacerBox = { fn: (text) => text };
4767
+ const rebuildReplacer = (rules) => {
4768
+ replacementRuleCount = rules.length;
4769
+ replacementHits = new Array(rules.length).fill(0);
4770
+ replacerBox.fn = createAsrReplacer(rules, (i) => {
4771
+ replacementHits[i] = (replacementHits[i] ?? 0) + 1;
4772
+ });
4773
+ };
4774
+ rebuildReplacer(vset.asrReplacements ?? []);
3512
4775
  const asr = createAsrRuntime({
3513
4776
  cacheDir: config.cacheDir,
3514
4777
  modelHost: () => vset.modelHost,
@@ -3531,9 +4794,17 @@ function apply(ctx, config) {
3531
4794
  // 而 bargeInMode=detect 在原生 AEC 未生效的机器上会自动落到 manual,即默认路径就可能命中。
3532
4795
  // 待机态 push-to-talk 属产品决策(要改的是客户端手势开放条件),PM 已登记待用户拍板,
3533
4796
  // 此处不加功能;host 侧只保证「manual 时非按压帧不入流」这一既有语义不被悄悄扩大。
3534
- bargeInMode: () => vset.bargeInMode
4797
+ bargeInMode: () => vset.bargeInMode,
4798
+ replaceText: (text, isFinal) => replacerBox.fn(text, isFinal !== false)
4799
+ });
4800
+ let pluginDisposed = false;
4801
+ let toggleGen = 0;
4802
+ const enteringToggles = /* @__PURE__ */ new Set();
4803
+ ctx.effect(() => () => {
4804
+ pluginDisposed = true;
4805
+ toggleGen++;
4806
+ asr.dispose();
3535
4807
  });
3536
- ctx.effect(() => () => asr.dispose());
3537
4808
  const warmupAsrIfCached = () => {
3538
4809
  if (!config.enabled) return;
3539
4810
  const st = asr.modelStatus();
@@ -3543,15 +4814,46 @@ function apply(ctx, config) {
3543
4814
  };
3544
4815
  warmupAsrIfCached();
3545
4816
  const makeEngine = (kind) => {
3546
- if (kind === "edge") return new EdgeTtsEngine(config.voice, config.rate);
4817
+ if (kind === "edge") return new EdgeTtsEngine(vset.voice, vset.rate);
4818
+ if (kind === "mimo") {
4819
+ const m = config.mimoTts;
4820
+ const fb = m.fallback;
4821
+ return new MimoTtsEngine({
4822
+ // 设置卡片里填的 key 优先(留空则回落到配置文件 mimoTts.apiKey);key 只在宿主侧。
4823
+ apiKey: (vset.mimoApiKey ?? "").trim() || m.apiKey,
4824
+ baseUrl: m.baseUrl,
4825
+ model: m.model,
4826
+ voice: m.voice,
4827
+ instructions: m.instructions,
4828
+ responseFormat: m.responseFormat,
4829
+ timeoutMs: m.timeoutMs,
4830
+ fallback: fb === "none" ? void 0 : () => {
4831
+ const engine = makeEngine(fb === "vits" ? "vits" : "kokoro");
4832
+ if (m.fallbackVoice) engine.updateVoice(m.fallbackVoice, vset.rate);
4833
+ return engine;
4834
+ }
4835
+ });
4836
+ }
3547
4837
  if (kind === "openai") {
3548
4838
  const o = config.openaiTts;
3549
4839
  const fallbackKind = o.fallback;
4840
+ const resolved = resolveOnlineTts(
4841
+ {
4842
+ presetId: vset.openaiPreset ?? "",
4843
+ baseUrl: vset.openaiBaseUrl ?? "",
4844
+ model: vset.openaiModel ?? "",
4845
+ apiKey: vset.openaiApiKey ?? "",
4846
+ apiKeys: vset.openaiApiKeys ?? {},
4847
+ voice: ""
4848
+ },
4849
+ { baseUrl: o.baseUrl, model: o.model, voice: o.voice, apiKey: o.apiKey, apiKeys: o.apiKeys }
4850
+ );
3550
4851
  return new OpenAiTtsEngine({
3551
- baseUrl: o.baseUrl,
3552
- apiKey: o.apiKey || void 0,
3553
- model: o.model,
3554
- voice: o.voice,
4852
+ baseUrl: resolved.baseUrl,
4853
+ // E1 多 key:预设专属 key 优先(换服务商不必再手改单个 key)。key 始终只在宿主侧。
4854
+ apiKey: resolved.apiKey || void 0,
4855
+ model: resolved.model,
4856
+ voice: resolved.voice,
3555
4857
  instructions: o.instructions || void 0,
3556
4858
  responseFormat: o.responseFormat,
3557
4859
  timeoutMs: o.timeoutMs,
@@ -3578,7 +4880,7 @@ function apply(ctx, config) {
3578
4880
  broadcast
3579
4881
  });
3580
4882
  };
3581
- let engineKind = vset.ttsEngine ?? config.ttsEngine;
4883
+ let engineKind = asTtsEngineKind(vset.ttsEngine ?? config.ttsEngine);
3582
4884
  let activeKokoroModel = vset.kokoroModel;
3583
4885
  const queue = new TtsQueue({
3584
4886
  engine: makeEngine(engineKind),
@@ -3586,6 +4888,7 @@ function apply(ctx, config) {
3586
4888
  // 单句重试耗尽被跳过:显式下行(客户端提示 + 诊断),不再静默丢句。
3587
4889
  // streak = 连续被跳过的句数:客户端据此区分偶发抖动与「云端整体不可用」(如服务端拒绝握手)。
3588
4890
  onSkip: (sessionId, text, streak) => broadcast("tts-skip", { sessionId, text: text.slice(0, 80), streak }),
4891
+ onRetry: (sessionId, attempt, maxAttempts) => broadcast("tts-retry", { sessionId, attempt, maxAttempts }),
3589
4892
  onIdle: (sessionId) => broadcast("tts-idle", { sessionId, turn: turnOfSession.get(sessionId)?.turn }),
3590
4893
  // R15(Issue #15 Important-2 host 侧接线):onIdle 降级为「候选空闲」——「队列排空」不等于
3591
4894
  // 「回合结束」。带工具调用的回合会在工具执行期间把队列排空一次,据此发 tts-idle 会让
@@ -3593,34 +4896,78 @@ function apply(ctx, config) {
3593
4896
  // 只在 host 经 `agent/turn-stopping` 确认回合真正结束后才发(见下方钩子)。
3594
4897
  awaitTurnEnd: true
3595
4898
  });
4899
+ const ttsKeyState = () => {
4900
+ const st = queue.status();
4901
+ if (st.engine === "mimo") return { keyRequired: true, keyPresent: st.keyPresent === true };
4902
+ if (st.engine === "openai") return { keyRequired: presetRequiresKey(vset.openaiPreset), keyPresent: st.keyPresent === true };
4903
+ return { keyRequired: false, keyPresent: false };
4904
+ };
3596
4905
  queue.updateVoice(vset.voice, vset.rate);
3597
4906
  const unsubscribe = queue.subscribe((frame) => broadcast("audio", frame));
3598
4907
  ctx.effect(() => unsubscribe);
3599
4908
  ctx.effect(() => () => void queue.close());
3600
- const applyVset = (next) => {
4909
+ const checkRemoteConfig = (kind) => {
4910
+ if (kind === "mimo" && !((vset.mimoApiKey ?? "").trim() || config.mimoTts?.apiKey)) {
4911
+ console.warn("[dsh-voice-mode] tts engine is mimo but no key is configured (settings or mimoTts.apiKey): synthesis will fail (falls back to local if configured)");
4912
+ } else if (kind === "openai") {
4913
+ const o = config.openaiTts;
4914
+ const r = resolveOnlineTts(
4915
+ { presetId: vset.openaiPreset ?? "", baseUrl: vset.openaiBaseUrl ?? "", model: vset.openaiModel ?? "", apiKey: vset.openaiApiKey ?? "", apiKeys: vset.openaiApiKeys ?? {}, voice: vset.voice },
4916
+ { baseUrl: o.baseUrl, model: o.model, voice: o.voice, apiKey: o.apiKey, apiKeys: o.apiKeys }
4917
+ );
4918
+ if (!r.baseUrl || !r.model) {
4919
+ console.warn("[dsh-voice-mode] tts engine is openai-compatible but baseUrl/model is missing: fill them in the settings card or the profile openaiTts block");
4920
+ } else if (!r.voice) {
4921
+ console.warn("[dsh-voice-mode] tts engine is openai-compatible but no voice is set: the server default voice will be used (set one in the settings card or via a preset)");
4922
+ }
4923
+ }
4924
+ };
4925
+ const applyVset = (incoming) => {
3601
4926
  const prev = vset;
4927
+ let next;
4928
+ try {
4929
+ next = resolveSettings(incoming);
4930
+ } catch (e) {
4931
+ console.warn(`[dsh-voice-mode] settings update rejected by schema; keeping previous values: ${redactSecrets(e)}`);
4932
+ return;
4933
+ }
3602
4934
  vset = next;
3603
4935
  broadcast("display", displayOf(next));
3604
- if (next.ttsEngine !== engineKind) {
4936
+ const reason = engineRebuildReason(prev, next, engineKind, activeKokoroModel);
4937
+ if (reason === "engine-switch") {
3605
4938
  engineKind = next.ttsEngine;
4939
+ if (engineKind === "kokoro") activeKokoroModel = next.kokoroModel;
4940
+ checkRemoteConfig(engineKind);
3606
4941
  queue.setEngine(makeEngine(engineKind));
3607
- } else if (engineKind === "kokoro" && next.kokoroModel !== activeKokoroModel) {
4942
+ } else if (reason === "mimo-key") {
4943
+ checkRemoteConfig("mimo");
4944
+ queue.setEngine(makeEngine("mimo"));
4945
+ } else if (reason === "kokoro-model") {
3608
4946
  activeKokoroModel = next.kokoroModel;
3609
4947
  queue.setEngine(makeEngine("kokoro"));
4948
+ } else if (reason === "openai-config") {
4949
+ checkRemoteConfig("openai");
4950
+ queue.setEngine(makeEngine("openai"));
3610
4951
  }
3611
4952
  queue.updateVoice(next.voice, next.rate);
3612
4953
  if (next.senseITN !== prev.senseITN || next.senseVoice !== prev.senseVoice) {
3613
4954
  asr.markStale();
3614
4955
  }
4956
+ if (JSON.stringify(next.asrReplacements ?? []) !== JSON.stringify(prev.asrReplacements ?? [])) {
4957
+ rebuildReplacer(next.asrReplacements ?? []);
4958
+ }
3615
4959
  };
3616
4960
  if (settingsScopeRef) {
3617
4961
  const scopeRef = settingsScopeRef;
3618
4962
  ctx.effect(() => scopeRef.watch(applyVset));
3619
4963
  }
3620
4964
  let settingsWriteChain = Promise.resolve();
3621
- const persistSettings = (patch) => {
4965
+ const persistSettings = (patch, clearAllPresetKeys = false) => {
3622
4966
  const run = async () => {
3623
4967
  const candidate = { ...overrides, ...patch };
4968
+ if ("openaiApiKeys" in patch || clearAllPresetKeys) {
4969
+ candidate.openaiApiKeys = mergePresetApiKeys(overrides.openaiApiKeys, patch.openaiApiKeys, clearAllPresetKeys);
4970
+ }
3624
4971
  const next = resolveSettings(candidate);
3625
4972
  writeOverrides(settingsFile, candidate);
3626
4973
  overrides = candidate;
@@ -3635,6 +4982,7 @@ function apply(ctx, config) {
3635
4982
  const currentRate = () => vset.rate;
3636
4983
  const currentInterrupt = () => vset.interruptLevel;
3637
4984
  const currentEngine = () => engineKind;
4985
+ checkRemoteConfig(engineKind);
3638
4986
  const yieldActiveSession = (expectedSid) => {
3639
4987
  ownerYieldTimer = null;
3640
4988
  const sid = activeVoiceSession;
@@ -3718,16 +5066,30 @@ function apply(ctx, config) {
3718
5066
  }
3719
5067
  })
3720
5068
  );
5069
+ ctx.effect(
5070
+ () => ctx.webServer.register({
5071
+ kind: "exact",
5072
+ path: `${base}/presets`,
5073
+ handler: (req, res) => {
5074
+ if (denyNonLoopback(req, res)) return;
5075
+ respondJson2(res, 200, { presets: OPENAI_PRESETS });
5076
+ }
5077
+ })
5078
+ );
3721
5079
  ctx.effect(
3722
5080
  () => ctx.webServer.register({
3723
5081
  kind: "exact",
3724
5082
  path: `${base}/config`,
3725
5083
  handler: (req, res) => {
3726
5084
  if (denyNonLoopback(req, res)) return;
5085
+ const keyState = ttsKeyState();
3727
5086
  respondJson2(res, 200, {
3728
5087
  basePath: base,
3729
5088
  rate: currentRate(),
3730
5089
  voice: currentVoice(),
5090
+ // P1-2:入口探针还要判「预设音色」。ttsEngine 本就在下方载荷里;
5091
+ // 此前探针只能读设置卡快照——0.1.7+ 只有首个订阅者才触发加载,未开过设置的用户
5092
+ // 快照恒 loading,探针从未生效(T5 审计 B①)。这里补 openaiPreset 即可闭环。
3731
5093
  senseVoice: vset.senseVoice,
3732
5094
  interruptLevel: currentInterrupt(),
3733
5095
  silenceMs: vset.silenceMs,
@@ -3737,6 +5099,9 @@ function apply(ctx, config) {
3737
5099
  autoResume: vset.autoResume,
3738
5100
  mode: vset.mode,
3739
5101
  readAloud: vset.readAloud,
5102
+ // 2026-11-20 UX:进模式前即可判断「云朗读缺 Key」,客户端据此常驻提示。
5103
+ ttsNeedsKey: keyState.keyRequired,
5104
+ ttsKeyPresent: keyState.keyPresent,
3740
5105
  showCaptions: vset.showCaptions,
3741
5106
  showStatusBar: vset.showStatusBar,
3742
5107
  bargeInMode: vset.bargeInMode,
@@ -3754,6 +5119,7 @@ function apply(ctx, config) {
3754
5119
  senseITN: vset.senseITN,
3755
5120
  cacheDir: config.cacheDir,
3756
5121
  ttsEngine: currentEngine(),
5122
+ openaiPreset: vset.openaiPreset,
3757
5123
  audioMime: queue.mime,
3758
5124
  allowLan: config.allowLan
3759
5125
  });
@@ -3791,7 +5157,7 @@ function apply(ctx, config) {
3791
5157
  respondJson2(res, 400, { code: "bad_request", error: "voice too long" });
3792
5158
  return;
3793
5159
  }
3794
- if (!voice) {
5160
+ if (!voice && currentEngine() !== "openai") {
3795
5161
  respondJson2(res, 400, { code: "bad_request", error: "voice required" });
3796
5162
  return;
3797
5163
  }
@@ -3801,8 +5167,11 @@ function apply(ctx, config) {
3801
5167
  }
3802
5168
  const sample = previewSample(currentEngine(), voice);
3803
5169
  let buf;
5170
+ let mime = queue.mime;
3804
5171
  try {
3805
- buf = await queue.synthesize(sample, { voice, rate });
5172
+ const r = await queue.synthesizeWithMime(sample, { voice, rate });
5173
+ buf = r.buf;
5174
+ mime = r.mime;
3806
5175
  } catch (e) {
3807
5176
  const errMsg = e instanceof Error ? e.message : String(e);
3808
5177
  const category = classifyPreviewError(errMsg);
@@ -3810,12 +5179,12 @@ function apply(ctx, config) {
3810
5179
  const engineStatus = queue.status();
3811
5180
  const sampleLen = sample.length;
3812
5181
  console.warn(
3813
- `[dsh-voice-mode] preview synthesis failed: category=${category} engine=${engineName} engineReady=${engineStatus.ready} sampleLen=${sampleLen} attempt=1 voice=${voice} err=${errMsg}`
5182
+ `[dsh-voice-mode] preview synthesis failed: category=${category} engine=${engineName} engineReady=${engineStatus.ready} sampleLen=${sampleLen} attempt=1 voice=${redactSecrets(voice)} err=${redactSecrets(errMsg)}`
3814
5183
  );
3815
5184
  respondJson2(res, 502, { code: PREVIEW_ERROR_CODES[category], error: `preview failed (${category})` });
3816
5185
  return;
3817
5186
  }
3818
- res.writeHead(200, { "content-type": queue.mime, "cache-control": "no-store" });
5187
+ res.writeHead(200, { "content-type": mime, "cache-control": "no-store" });
3819
5188
  res.end(buf);
3820
5189
  });
3821
5190
  }
@@ -3826,6 +5195,10 @@ function apply(ctx, config) {
3826
5195
  kind: "exact",
3827
5196
  path: `${base}/correct`,
3828
5197
  handler: (req, res) => {
5198
+ if (req.method !== "POST" && req.method !== "GET") {
5199
+ respondJson2(res, 405, { code: "method_not_allowed", error: "method not allowed" });
5200
+ return;
5201
+ }
3829
5202
  if (denyNonLoopback(req, res)) return;
3830
5203
  if (denyCrossOrigin(req, res)) return;
3831
5204
  collectBody(req, res, MAX_JSON_BODY, (body) => {
@@ -3862,6 +5235,10 @@ function apply(ctx, config) {
3862
5235
  kind: "exact",
3863
5236
  path: `${base}/toggle`,
3864
5237
  handler: (req, res) => {
5238
+ if (req.method !== "POST" && req.method !== "GET") {
5239
+ respondJson2(res, 405, { code: "method_not_allowed", error: "method not allowed" });
5240
+ return;
5241
+ }
3865
5242
  if (denyNonLoopback(req, res)) return;
3866
5243
  if (denyCrossOrigin(req, res)) return;
3867
5244
  collectBody(req, res, MAX_JSON_BODY, async (body) => {
@@ -3877,7 +5254,7 @@ function apply(ctx, config) {
3877
5254
  tabId = typeof parsed.tabId === "string" && parsed.tabId.length <= 64 ? parsed.tabId : void 0;
3878
5255
  } catch {
3879
5256
  }
3880
- if (!sessionId) {
5257
+ if (typeof sessionId !== "string" || !sessionId || sessionId.length > 128) {
3881
5258
  respondJson2(res, 400, { code: "bad_request", error: "sessionId required" });
3882
5259
  return;
3883
5260
  }
@@ -3902,7 +5279,15 @@ function apply(ctx, config) {
3902
5279
  respondJson2(res, 403, { code: "unknown_session", error: "unknown session" });
3903
5280
  return;
3904
5281
  }
5282
+ const myToggleGen = ++toggleGen;
5283
+ enteringToggles.add(sessionId);
3905
5284
  await asr.warmupSense();
5285
+ const enterStale = pluginDisposed || myToggleGen !== toggleGen;
5286
+ enteringToggles.delete(sessionId);
5287
+ if (enterStale) {
5288
+ respondJson2(res, 200, { active: activeVoiceSession, stale: true });
5289
+ return;
5290
+ }
3906
5291
  asr.reset(sessionId);
3907
5292
  queue.cancel(sessionId);
3908
5293
  const previous = activeVoiceSession;
@@ -3920,6 +5305,7 @@ function apply(ctx, config) {
3920
5305
  }
3921
5306
  broadcast("mode", { active: activeVoiceSession, ownerTabId: activeTabId });
3922
5307
  } else {
5308
+ if (activeVoiceSession === sessionId || enteringToggles.has(sessionId)) toggleGen++;
3923
5309
  if (activeVoiceSession === sessionId) {
3924
5310
  activeVoiceSession = null;
3925
5311
  activeTabId = null;
@@ -3944,7 +5330,12 @@ function apply(ctx, config) {
3944
5330
  path: `${base}/models/status`,
3945
5331
  handler: (req, res) => {
3946
5332
  if (denyNonLoopback(req, res)) return;
3947
- respondJson2(res, 200, { ...asr.modelStatus(), tts: queue.status() });
5333
+ respondJson2(res, 200, {
5334
+ ...asr.modelStatus(),
5335
+ tts: { ...queue.status(), ...ttsKeyState() },
5336
+ // P1-3:词表规则数与命中计数(本次生效以来;设置变更重建即清零)。
5337
+ replacements: { rules: replacementRuleCount, hits: [...replacementHits] }
5338
+ });
3948
5339
  }
3949
5340
  })
3950
5341
  );
@@ -3960,6 +5351,14 @@ function apply(ctx, config) {
3960
5351
  return;
3961
5352
  }
3962
5353
  if (denyCrossOrigin(req, res)) return;
5354
+ if (!isLoopbackRequest(req)) {
5355
+ respondJson2(res, 403, { code: "forbidden", error: "model cache writes are loopback-only" });
5356
+ return;
5357
+ }
5358
+ if (!limiter.hit(`models-retry:${clientKey(req)}`, 6, 6e4)) {
5359
+ respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
5360
+ return;
5361
+ }
3963
5362
  if (!config.enabled) {
3964
5363
  respondJson2(res, 403, { code: "voice_disabled", error: "voice mode disabled" });
3965
5364
  return;
@@ -3982,7 +5381,7 @@ function apply(ctx, config) {
3982
5381
  void asr.retryModel(kind).then((done) => {
3983
5382
  respondJson2(res, 200, { ok: done, kind });
3984
5383
  }).catch((e) => {
3985
- console.warn(`[dsh-voice-mode] model retry failed: ${String(e)}`);
5384
+ console.warn(`[dsh-voice-mode] model retry failed: ${redactSecrets(e)}`);
3986
5385
  respondJson2(res, 500, { code: "internal", error: "model retry failed" });
3987
5386
  });
3988
5387
  });
@@ -3995,7 +5394,20 @@ function apply(ctx, config) {
3995
5394
  path: `${base}/models/clean`,
3996
5395
  handler: (req, res) => {
3997
5396
  if (denyNonLoopback(req, res)) return;
5397
+ if (req.method !== "POST") {
5398
+ res.setHeader("allow", "POST");
5399
+ respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
5400
+ return;
5401
+ }
3998
5402
  if (denyCrossOrigin(req, res)) return;
5403
+ if (!isLoopbackRequest(req)) {
5404
+ respondJson2(res, 403, { code: "forbidden", error: "model cache writes are loopback-only" });
5405
+ return;
5406
+ }
5407
+ if (!limiter.hit(`models-clean:${clientKey(req)}`, 6, 6e4)) {
5408
+ respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
5409
+ return;
5410
+ }
3999
5411
  if (!config.enabled) {
4000
5412
  respondJson2(res, 403, { code: "voice_disabled", error: "voice mode disabled" });
4001
5413
  return;
@@ -4004,7 +5416,7 @@ function apply(ctx, config) {
4004
5416
  let engine = "vits";
4005
5417
  try {
4006
5418
  const p = JSON.parse(body || "{}");
4007
- if (p.engine === "kokoro" || p.engine === "vits") engine = p.engine;
5419
+ if (isLocalEngine(p.engine)) engine = p.engine;
4008
5420
  else {
4009
5421
  respondJson2(res, 400, { code: "bad_request", error: "invalid engine" });
4010
5422
  return;
@@ -4021,7 +5433,7 @@ function apply(ctx, config) {
4021
5433
  }
4022
5434
  respondJson2(res, 200, { ok: true, engine });
4023
5435
  }).catch((e) => {
4024
- console.warn(`[dsh-voice-mode] models/download failed: ${String(e)}`);
5436
+ console.warn(`[dsh-voice-mode] models/clean failed: ${redactSecrets(e)}`);
4025
5437
  respondJson2(res, 500, { code: "internal", error: "internal error" });
4026
5438
  });
4027
5439
  });
@@ -4034,7 +5446,20 @@ function apply(ctx, config) {
4034
5446
  path: `${base}/models/download`,
4035
5447
  handler: (req, res) => {
4036
5448
  if (denyNonLoopback(req, res)) return;
5449
+ if (req.method !== "POST") {
5450
+ res.setHeader("allow", "POST");
5451
+ respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
5452
+ return;
5453
+ }
4037
5454
  if (denyCrossOrigin(req, res)) return;
5455
+ if (!isLoopbackRequest(req)) {
5456
+ respondJson2(res, 403, { code: "forbidden", error: "model cache writes are loopback-only" });
5457
+ return;
5458
+ }
5459
+ if (!limiter.hit(`models-download:${clientKey(req)}`, 6, 6e4)) {
5460
+ respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
5461
+ return;
5462
+ }
4038
5463
  if (!config.enabled) {
4039
5464
  respondJson2(res, 403, { code: "voice_disabled", error: "voice mode disabled" });
4040
5465
  return;
@@ -4043,7 +5468,7 @@ function apply(ctx, config) {
4043
5468
  let engine = "vits";
4044
5469
  try {
4045
5470
  const p = JSON.parse(body || "{}");
4046
- if (p.engine === "kokoro" || p.engine === "vits") engine = p.engine;
5471
+ if (isLocalEngine(p.engine)) engine = p.engine;
4047
5472
  else {
4048
5473
  respondJson2(res, 400, { code: "bad_request", error: "invalid engine" });
4049
5474
  return;
@@ -4057,7 +5482,7 @@ function apply(ctx, config) {
4057
5482
  return;
4058
5483
  }
4059
5484
  void queue.prepare().then(() => respondJson2(res, 200, { ok: true, engine })).catch((e) => {
4060
- console.warn(`[dsh-voice-mode] model download failed: ${String(e)}`);
5485
+ console.warn(`[dsh-voice-mode] model download failed: ${redactSecrets(e)}`);
4061
5486
  respondJson2(res, 502, { code: "model_download_failed", error: "model download failed" });
4062
5487
  });
4063
5488
  });
@@ -4069,13 +5494,21 @@ function apply(ctx, config) {
4069
5494
  kind: "exact",
4070
5495
  path: `${base}/voices`,
4071
5496
  handler: async (req, res) => {
5497
+ if (req.method !== "POST" && req.method !== "GET") {
5498
+ respondJson2(res, 405, { code: "method_not_allowed", error: "method not allowed" });
5499
+ return;
5500
+ }
4072
5501
  if (denyNonLoopback(req, res)) return;
4073
5502
  if (denyCrossOrigin(req, res)) return;
5503
+ if (!limiter.hit(`voices:${clientKey(req)}`, 10, 6e4)) {
5504
+ respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
5505
+ return;
5506
+ }
4074
5507
  try {
4075
5508
  const voices = await listEdgeVoices();
4076
5509
  respondJson2(res, 200, { voices });
4077
5510
  } catch (e) {
4078
- console.warn(`[dsh-voice-mode] listing Edge voices failed: ${String(e)}`);
5511
+ console.warn(`[dsh-voice-mode] listing Edge voices failed: ${redactSecrets(e)}`);
4079
5512
  respondJson2(res, 502, { code: "internal", error: "voice list unavailable" });
4080
5513
  }
4081
5514
  }
@@ -4106,7 +5539,9 @@ function apply(ctx, config) {
4106
5539
  if (sid && sid === activeVoiceSession) {
4107
5540
  try {
4108
5541
  const url = new URL(req.url ?? "/", "http://localhost");
4109
- setTurn(sid, url.searchParams.get("final") === "1" ? "finalizing" : "listening");
5542
+ if (url.searchParams.get("vadOnly") !== "1" && url.searchParams.get("reset") !== "1") {
5543
+ setTurn(sid, url.searchParams.get("final") === "1" ? "finalizing" : "listening");
5544
+ }
4110
5545
  } catch {
4111
5546
  }
4112
5547
  }
@@ -4119,6 +5554,10 @@ function apply(ctx, config) {
4119
5554
  kind: "exact",
4120
5555
  path: `${base}/cancel`,
4121
5556
  handler: (req, res) => {
5557
+ if (req.method !== "POST" && req.method !== "GET") {
5558
+ respondJson2(res, 405, { code: "method_not_allowed", error: "method not allowed" });
5559
+ return;
5560
+ }
4122
5561
  if (denyNonLoopback(req, res)) return;
4123
5562
  if (denyCrossOrigin(req, res)) return;
4124
5563
  collectBody(req, res, MAX_JSON_BODY, (body) => {
@@ -4154,7 +5593,8 @@ function apply(ctx, config) {
4154
5593
  handler: (req, res) => {
4155
5594
  if (denyNonLoopback(req, res)) return;
4156
5595
  if (req.method === "GET") {
4157
- respondJson2(res, 200, { managedBy: settingsScopeRef ? "dsh" : "plugin", value: vset });
5596
+ const view = buildSettingsGetView(vset, config);
5597
+ respondJson2(res, 200, { managedBy: settingsScopeRef ? "dsh" : "plugin", ...view });
4158
5598
  return;
4159
5599
  }
4160
5600
  if (req.method !== "POST") {
@@ -4167,6 +5607,14 @@ function apply(ctx, config) {
4167
5607
  respondJson2(res, 409, { code: "settings_managed", error: "settings are managed by dsh on this host" });
4168
5608
  return;
4169
5609
  }
5610
+ if (!isLoopbackRequest(req)) {
5611
+ respondJson2(res, 403, { code: "forbidden", error: "settings writes are loopback-only" });
5612
+ return;
5613
+ }
5614
+ if (!limiter.hit(`settings:${clientKey(req)}`, 30, 6e4)) {
5615
+ respondJson2(res, 429, { code: "rate_limited", error: "too many settings updates, retry in a minute" });
5616
+ return;
5617
+ }
4170
5618
  collectBody(req, res, MAX_JSON_BODY, async (body) => {
4171
5619
  let patch;
4172
5620
  try {
@@ -4179,17 +5627,28 @@ function apply(ctx, config) {
4179
5627
  respondJson2(res, 400, { code: "bad_request", error: "body must be a JSON object" });
4180
5628
  return;
4181
5629
  }
4182
- const unknown = unknownKeys(patch, SETTING_KEYS);
5630
+ const rawClear = patch.clearSecrets;
5631
+ let cleared;
5632
+ try {
5633
+ cleared = applyClearSecrets(patch, rawClear);
5634
+ } catch (e) {
5635
+ respondJson2(res, 400, { code: "bad_request", error: String(e.message).slice(0, 120) });
5636
+ return;
5637
+ }
5638
+ const unknown = unknownKeys(cleared, SETTING_KEYS);
4183
5639
  if (unknown.length > 0) {
4184
5640
  respondJson2(res, 400, { code: "bad_request", error: `unknown settings: ${unknown.slice(0, 5).join(", ")}` });
4185
5641
  return;
4186
5642
  }
5643
+ const rest = { ...pickKnownKeys(cleared, SETTING_KEYS) };
5644
+ const clearAllMap = Array.isArray(rawClear) && rawClear.includes("openaiApiKeys");
4187
5645
  try {
4188
- const next = await persistSettings(pickKnownKeys(patch, SETTING_KEYS));
4189
- respondJson2(res, 200, { ok: true, managedBy: "plugin", value: next });
5646
+ const next = await persistSettings(rest, clearAllMap);
5647
+ const out = { ...next, openaiApiKey: "", mimoApiKey: "", openaiApiKeys: {} };
5648
+ respondJson2(res, 200, { ok: true, managedBy: "plugin", value: out });
4190
5649
  } catch (e) {
4191
5650
  const isValidation = e instanceof Error && e.name === "ValidationError";
4192
- console.warn(`[dsh-voice-mode] settings update failed: ${String(e)}`);
5651
+ console.warn(`[dsh-voice-mode] settings update failed: ${redactSecrets(e)}`);
4193
5652
  respondJson2(res, isValidation ? 400 : 500, {
4194
5653
  code: isValidation ? "bad_request" : "internal",
4195
5654
  error: isValidation ? `invalid value: ${e.message.slice(0, 200)}` : "settings update failed"
@@ -4205,7 +5664,20 @@ function apply(ctx, config) {
4205
5664
  path: `${base}/mode`,
4206
5665
  handler: (req, res) => {
4207
5666
  if (denyNonLoopback(req, res)) return;
5667
+ if (req.method !== "POST") {
5668
+ res.setHeader("allow", "POST");
5669
+ respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
5670
+ return;
5671
+ }
4208
5672
  if (denyCrossOrigin(req, res)) return;
5673
+ if (!isLoopbackRequest(req)) {
5674
+ respondJson2(res, 403, { code: "forbidden", error: "settings writes are loopback-only" });
5675
+ return;
5676
+ }
5677
+ if (!limiter.hit(`mode:${clientKey(req)}`, 30, 6e4)) {
5678
+ respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
5679
+ return;
5680
+ }
4209
5681
  collectBody(req, res, MAX_JSON_BODY, (body) => {
4210
5682
  let mode;
4211
5683
  try {
@@ -4221,7 +5693,7 @@ function apply(ctx, config) {
4221
5693
  void persistMode.then(() => {
4222
5694
  respondJson2(res, 200, { ok: true, mode });
4223
5695
  }).catch((e) => {
4224
- console.warn(`[dsh-voice-mode] mode update failed: ${String(e)}`);
5696
+ console.warn(`[dsh-voice-mode] mode update failed: ${redactSecrets(e)}`);
4225
5697
  respondJson2(res, 500, { code: "internal", error: "mode update failed" });
4226
5698
  });
4227
5699
  });
@@ -4260,7 +5732,7 @@ function apply(ctx, config) {
4260
5732
  focusedSessionId = null;
4261
5733
  focusedTabId = null;
4262
5734
  }
4263
- if (prevFocus !== null && prevFocus !== focusedSessionId) stopFocusReading(prevFocus);
5735
+ if (prevFocus !== null && prevFocus !== focusedSessionId) stopFocusReading(prevFocus, tabId);
4264
5736
  if (prevFocus !== null && prevFocus !== focusedSessionId) reclaimFocusState(prevFocus);
4265
5737
  broadcast("focus", { sessionId: focusedSessionId, tabId: focusedTabId });
4266
5738
  respondJson2(res, 200, { ok: true, sessionId: focusedSessionId, tabId: focusedTabId });
@@ -4275,6 +5747,11 @@ function apply(ctx, config) {
4275
5747
  handler: (req, res) => {
4276
5748
  if (denyNonLoopback(req, res)) return;
4277
5749
  if (denyCrossOrigin(req, res)) return;
5750
+ if (req.method && req.method !== "GET") {
5751
+ res.setHeader("allow", "GET");
5752
+ respondJson2(res, 405, { code: "method_not_allowed", error: "GET required" });
5753
+ return;
5754
+ }
4278
5755
  let tabId = null;
4279
5756
  try {
4280
5757
  const u = new URL(req.url ?? "/", "http://localhost");
@@ -4313,7 +5790,13 @@ data: ${JSON.stringify(payload)}
4313
5790
  res.destroy();
4314
5791
  }
4315
5792
  };
5793
+ let heartbeat = null;
4316
5794
  const end = () => {
5795
+ if (heartbeat) {
5796
+ clearInterval(heartbeat);
5797
+ heartbeat = null;
5798
+ }
5799
+ sseClients.delete(client);
4317
5800
  try {
4318
5801
  res.end();
4319
5802
  } catch {
@@ -4329,7 +5812,7 @@ data: ${JSON.stringify(payload)}
4329
5812
  send("mode", { active: activeVoiceSession, ownerTabId: activeTabId });
4330
5813
  send("focus", { sessionId: focusedSessionId, tabId: focusedTabId });
4331
5814
  send("display", displayOf(vset));
4332
- const heartbeat = setInterval(() => {
5815
+ heartbeat = setInterval(() => {
4333
5816
  try {
4334
5817
  res.write(": hb\n");
4335
5818
  } catch {
@@ -4340,7 +5823,10 @@ data: ${JSON.stringify(payload)}
4340
5823
  const cleanup = () => {
4341
5824
  if (cleaned) return;
4342
5825
  cleaned = true;
4343
- clearInterval(heartbeat);
5826
+ if (heartbeat) {
5827
+ clearInterval(heartbeat);
5828
+ heartbeat = null;
5829
+ }
4344
5830
  sseClients.delete(client);
4345
5831
  if (tabId !== null && latestConnByTab.get(tabId) === client) {
4346
5832
  latestConnByTab.delete(tabId);
@@ -4438,6 +5924,7 @@ async function* tapActiveStream(sessionId, inner, queue, broadcast, onTurn, spea
4438
5924
  }
4439
5925
  export {
4440
5926
  Config,
5927
+ MimoTtsConfig,
4441
5928
  OpenAiTtsConfig,
4442
5929
  VoiceSettingsSchema,
4443
5930
  apply,