dsh-voice-mode 0.7.39 → 0.7.41
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/README.en.md +70 -44
- package/README.md +112 -39
- package/SECURITY.md +20 -16
- package/lib/client.js +4700 -914
- package/lib/index.js +1912 -402
- package/lib/sense-worker.mjs +5 -1
- package/lib/tts-vits-worker.cjs +21 -6
- package/package.json +5 -3
- package/scripts/check-anchors.mjs +12 -1
- package/scripts/prefetch.mjs +66 -26
package/lib/index.js
CHANGED
|
@@ -1,11 +1,56 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import
|
|
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.
|
|
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
|
-
|
|
241
|
+
let stopped = false;
|
|
242
|
+
const stop = () => {
|
|
243
|
+
stopped = true;
|
|
244
|
+
clearTimeout(t);
|
|
245
|
+
t = void 0;
|
|
246
|
+
};
|
|
193
247
|
const kick = () => {
|
|
194
|
-
|
|
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))
|
|
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)
|
|
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
|
-
|
|
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) =>
|
|
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
|
-
|
|
302
|
-
|
|
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))
|
|
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
|
-
|
|
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
|
|
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))
|
|
397
|
-
|
|
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
|
-
|
|
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) =>
|
|
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
|
-
|
|
421
|
-
|
|
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
|
-
|
|
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 (
|
|
659
|
-
senseWorkerSyncing
|
|
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:
|
|
865
|
+
useITN: myLangKey.endsWith("1") ? 1 : 0
|
|
671
866
|
}
|
|
672
867
|
});
|
|
673
868
|
const client = createSenseWorkerClient(w);
|
|
674
869
|
client.onDeath(() => {
|
|
675
|
-
senseWorker
|
|
676
|
-
|
|
677
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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: " +
|
|
912
|
+
console.warn("[dsh-voice-mode] SenseVoice re-transcribe failed: " + redactSecrets(e));
|
|
713
913
|
return null;
|
|
714
914
|
}
|
|
715
915
|
};
|
|
716
|
-
const
|
|
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
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
sessSegs.
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
if (
|
|
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
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
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
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
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
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
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
|
-
|
|
830
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
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: ${
|
|
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: ${
|
|
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
|
-
|
|
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
|
|
1307
|
-
if (!Number.isFinite(
|
|
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
|
-
|
|
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
|
-
|
|
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 =
|
|
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)
|
|
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
|
-
|
|
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
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
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 (
|
|
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
|
-
|
|
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
|
-
|
|
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}): ${
|
|
1716
|
-
if (
|
|
1717
|
-
|
|
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=${
|
|
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
|
|
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
|
-
|
|
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: () =>
|
|
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(),
|
|
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)
|
|
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,18 +2896,34 @@ var en = {
|
|
|
2457
2896
|
voiceBtn: "Voice",
|
|
2458
2897
|
ariaActive: "Voice mode active",
|
|
2459
2898
|
ariaEnter: "Enter voice mode",
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2899
|
+
ariaPendingCancelHint: "activate again to cancel",
|
|
2900
|
+
titleHold: "Hold-to-talk mode \xB7 hold mic or Ctrl to speak, release to send; Esc cancels, double-Esc exits",
|
|
2901
|
+
titleHoldMac: "Hold-to-talk mode \xB7 hold mic or \u2303 Control to speak, release to send; Esc cancels, double-Esc exits",
|
|
2902
|
+
titleToggle: "Continuous listening \xB7 hold and release Ctrl while speaking to send now; Esc stops playback, click or double-Esc exits",
|
|
2903
|
+
titleToggleMac: "Continuous listening \xB7 hold and release \u2303 Control while speaking to send now; Esc stops playback, click or double-Esc exits",
|
|
2904
|
+
titleOnce: "One-shot mode \xB7 speak once to auto-send, exits after the reply finishes reading; click or double-Esc to exit",
|
|
2905
|
+
titleEnter: "Enter voice mode",
|
|
2906
|
+
titleEnterHold: "Hold to talk: press and hold the mic directly to speak (release to send), or use the shortcut to enter",
|
|
2907
|
+
titleShortcutSuffix: " (shortcut: {keys})",
|
|
2908
|
+
titleShortcutComposerSuffix: " (shortcut: {keys}; in composer: {composerKeys})",
|
|
2463
2909
|
loadingModel: "Loading model\u2026",
|
|
2464
2910
|
listening: "Listening\u2026",
|
|
2465
2911
|
thinking: "Thinking\u2026",
|
|
2466
|
-
barHold: "
|
|
2912
|
+
barHold: "Hold to talk \xB7 hold the mic button or Ctrl to speak, release to send (Esc cancels)",
|
|
2913
|
+
barHoldMac: "Hold to talk \xB7 hold the mic button or \u2303 Control to speak, release to send (Esc cancels)",
|
|
2914
|
+
barHolding: "Recording \u2014 release to send (slide up or press Esc to cancel)",
|
|
2915
|
+
barOnce: "One-shot \xB7 speak your request; sends on pause and exits after reading",
|
|
2467
2916
|
barListening: "Voice mode \xB7 listening\u2026",
|
|
2468
2917
|
wakeWord: "Wake word",
|
|
2469
2918
|
sayWake: 'Say "{wake}" to start',
|
|
2470
2919
|
reading: "Reading aloud\u2026",
|
|
2920
|
+
readingManual: "Reading aloud \xB7 hold mic or Ctrl to interrupt",
|
|
2921
|
+
readingManualMac: "Reading aloud \xB7 hold mic or \u2303 Control to interrupt",
|
|
2471
2922
|
recognitionFail: "Recognition failed, try again",
|
|
2923
|
+
holdTrimmedNotice: "Hold-to-talk exceeded about 48 s: only the last part was recognised (earlier audio was dropped)",
|
|
2924
|
+
utteranceTooLong: "That utterance was too long (over the per-utterance limit, about a minute): skipped \u2014 please speak it again in shorter parts",
|
|
2925
|
+
interruptedNotice: "Playback interrupted \u2014 go ahead",
|
|
2926
|
+
senseDegradedNotice: "Final-pass model failed to load; temporarily using the backup recogniser (accuracy may drop slightly)",
|
|
2472
2927
|
partialFail: "Live captions temporarily unavailable (recognition channel error, retrying)",
|
|
2473
2928
|
detectFail: "Break-in detection temporarily unavailable (detect channel error, retrying)",
|
|
2474
2929
|
sseReconnect: "State sync disconnected, reconnecting\u2026",
|
|
@@ -2481,6 +2936,7 @@ var en = {
|
|
|
2481
2936
|
startFail: "Voice mode failed to start: {err}",
|
|
2482
2937
|
holdDots: "Hold to talk\u2026",
|
|
2483
2938
|
exit: "Exit",
|
|
2939
|
+
micMoreMenu: "Voice quick settings",
|
|
2484
2940
|
configUnavailableNote: " (settings document not ready; retrying \u2014 the panel will appear when it is).",
|
|
2485
2941
|
previewNameFirst: "Enter a voice ShortName first",
|
|
2486
2942
|
previewDisabled: "Voice mode disabled (plugin enabled=false); preview unavailable",
|
|
@@ -2495,23 +2951,123 @@ var en = {
|
|
|
2495
2951
|
previewBtnTitle: "Preview voice (current rate)",
|
|
2496
2952
|
synthesizing: "Synthesizing\u2026",
|
|
2497
2953
|
preview: "Preview",
|
|
2954
|
+
// E1 online presets.
|
|
2955
|
+
openaiPresetLabel: "Online preset",
|
|
2956
|
+
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",
|
|
2957
|
+
presetCustom: "Follow the config file",
|
|
2958
|
+
presetCustomCustom: "Custom (fill below)",
|
|
2959
|
+
presetCustomHint: "With this selected, configure any OpenAI-compatible service in the Endpoint / Model / API key fields below",
|
|
2960
|
+
openaiAdvancedShow: "Custom endpoint / fallback API key",
|
|
2961
|
+
openaiAdvancedHide: "Hide advanced overrides",
|
|
2962
|
+
voiceServerDefaultOption: "Server default voice",
|
|
2963
|
+
presetCosy: "SiliconFlow \xB7 CosyVoice2",
|
|
2964
|
+
presetFish: "SiliconFlow \xB7 Fish Speech 1.5",
|
|
2965
|
+
presetCosyNote: "About $7.15 per million UTF-8 bytes, ~150ms; text goes to api.siliconflow.cn",
|
|
2966
|
+
presetFishNote: "About $15 per million UTF-8 bytes (billed per UTF-8 byte); text goes to api.siliconflow.cn",
|
|
2967
|
+
presetOpenrouter: "OpenRouter \xB7 OpenAI TTS",
|
|
2968
|
+
presetOpenrouterNote: "Billed through the selected model; text goes to openrouter.ai; OpenAI terms require disclosing that the voice is AI-generated",
|
|
2969
|
+
presetOpenaiOfficial: "OpenAI official \xB7 gpt-4o-mini-tts",
|
|
2970
|
+
presetOpenaiOfficialNote: "Billed at OpenAI list prices; text goes to api.openai.com; OpenAI terms require disclosing that the voice is AI-generated",
|
|
2971
|
+
presetGroq: "Groq \xB7 PlayAI TTS",
|
|
2972
|
+
presetGroqNote: "Billed at Groq prices; text goes to api.groq.com; English voices such as Fritz-PlayAI",
|
|
2973
|
+
presetSelfKokoro: "Self-hosted \xB7 Kokoro-FastAPI",
|
|
2974
|
+
presetSelfKokoroNote: "Local server (default 127.0.0.1:8880); no per-call fee; text stays on your network. You must deploy it first",
|
|
2975
|
+
presetSelfVllm: "Self-hosted \xB7 vLLM-Omni",
|
|
2976
|
+
presetSelfVllmNote: "Local server (default 127.0.0.1:8000); no per-call fee; text stays on your network. You must deploy it first",
|
|
2977
|
+
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",
|
|
2978
|
+
presetKeySaved: "Saved (panel)",
|
|
2979
|
+
presetKeyFromConfig: "Configured (profile)",
|
|
2980
|
+
presetKeyMissing: "No key",
|
|
2981
|
+
presetDataMissing: "Preset data not loaded (host /presets unavailable): restart the host or reload the page",
|
|
2982
|
+
presetReload: "Reload presets",
|
|
2983
|
+
// 2026-11-19: online TTS is configurable from the settings card (URL/model/key), no profile YAML edit needed.
|
|
2984
|
+
openaiBaseUrlLabel: "Endpoint (base URL)",
|
|
2985
|
+
descOpenaiBaseUrl: "OpenAI-compatible endpoint, usually ending in /v1 (the plugin appends /audio/speech). Empty = use the preset or the profile openaiTts.baseUrl",
|
|
2986
|
+
openaiModelLabel: "Model",
|
|
2987
|
+
descOpenaiModel: "TTS model on that endpoint, e.g. gpt-4o-mini-tts or FunAudioLLM/CosyVoice2-0.5B. Empty = use the preset or the profile",
|
|
2988
|
+
openaiApiKeyLabel: "API key",
|
|
2989
|
+
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",
|
|
2990
|
+
openaiApiKeysLabel: "Per-preset keys (follow the preset)",
|
|
2991
|
+
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",
|
|
2992
|
+
mimoApiKeyLabel: "MiMo API key",
|
|
2993
|
+
descMimoApiKey: "Xiaomi MiMo key (sent as the api-key header, not Bearer). Host-side only; empty = use the profile mimoTts.apiKey",
|
|
2994
|
+
secretSaved: "Saved",
|
|
2995
|
+
secretSaveFailed: "Save failed: the host did not accept it (check for policy restrictions)",
|
|
2996
|
+
secretKeep: "Saved (leave empty to keep)",
|
|
2997
|
+
secretClear: "Clear",
|
|
2998
|
+
secretClearing: "Clearing\u2026",
|
|
2999
|
+
secretHintBrowser: "Typed values go straight to the local host and are stored with 0600; never written to chat or logs",
|
|
3000
|
+
secretPlaceholderEmpty: "Paste the key (after saving only Saved is shown)",
|
|
3001
|
+
secretCleared: "Cleared",
|
|
3002
|
+
secretClearedConfigRemains: "Removed the key from settings; the config file (openaiTts/mimoTts) still has one and will keep using it",
|
|
3003
|
+
// P1-4 dictation-only preset.
|
|
3004
|
+
// P1-3 correction wordlist.
|
|
3005
|
+
replTitle: "Correction wordlist",
|
|
3006
|
+
replFromPh: "Misheard spellings, comma-separated",
|
|
3007
|
+
replToPh: "Wanted spelling",
|
|
3008
|
+
replAdd: "Add",
|
|
3009
|
+
replDelete: "Del",
|
|
3010
|
+
replEmpty: "No rules yet",
|
|
3011
|
+
replHits: "hits",
|
|
3012
|
+
replExport: "Export",
|
|
3013
|
+
replImport: "Import",
|
|
3014
|
+
replInvalid: "Invalid rule: non-empty from and to, comma-separate multiple spellings",
|
|
3015
|
+
replBadFile: "File is not a valid wordlist JSON (array [{from[], to}], max 200 rules)",
|
|
3016
|
+
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",
|
|
3017
|
+
replSaveFail: "Save failed (nothing was written); rules unchanged. Check whether the plugin is disabled or the settings store is read-only",
|
|
3018
|
+
replTooLarge: "Wordlist is too large (over ~12KB): reduce the number of rules or shorten the spellings",
|
|
3019
|
+
// P1-1 self-test: separate synthesis / playback verdicts.
|
|
3020
|
+
selftestTitle: "Test read-aloud",
|
|
3021
|
+
selftestHint: "Synthesize and play once: it speaks on success, and points to the engine, key or network on failure",
|
|
3022
|
+
selftestRun: "Test read-aloud",
|
|
3023
|
+
selftestRunning: "Testing\u2026",
|
|
3024
|
+
selftestSynth: "Synthesis",
|
|
3025
|
+
selftestPlay: "Playback",
|
|
3026
|
+
selftestOk: "OK",
|
|
3027
|
+
selftestFail: "Failed",
|
|
3028
|
+
selftestCheck: "Self-test failed: check network, engine status, or voice name",
|
|
3029
|
+
selftestTimeout: "Synthesis timed out: model still loading, retry self-test in a few seconds",
|
|
3030
|
+
selftestAutoplay: "Browser blocked autoplay \u2014 run self-test again",
|
|
3031
|
+
selftestRateLimited: "Preview requests are rate limited (20/min shared with Preview): wait a few seconds and run self-test again",
|
|
3032
|
+
selftestDisabled: "Voice mode is disabled (plugin enabled=false), so the self-test cannot run",
|
|
3033
|
+
switchToLocalTts: "Switch to local Kokoro (first use downloads ~109MB, then works offline)",
|
|
2498
3034
|
custom: "Custom",
|
|
2499
3035
|
voicePrev: "Previous voice",
|
|
2500
3036
|
voiceNext: "Next voice",
|
|
2501
3037
|
descVoice: "Edge cloud voices (auto-loads all Microsoft voices; common Chinese voices pinned on top; \u25C0\u25B6 or dropdown; custom ShortName allowed)",
|
|
2502
3038
|
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)",
|
|
3039
|
+
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
3040
|
engineVits: "Local VITS",
|
|
2505
3041
|
engineKokoro: "Local Kokoro",
|
|
2506
3042
|
engineEdge: "Edge cloud",
|
|
2507
3043
|
engineOpenai: "OpenAI-compatible",
|
|
2508
|
-
|
|
3044
|
+
engineMimo: "Xiaomi MiMo",
|
|
3045
|
+
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",
|
|
3046
|
+
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
3047
|
engineRemoteDown: "server unavailable",
|
|
3048
|
+
errMimoKeyMissing: "MiMo API key is not configured: enter it in this settings card or set mimoTts.apiKey in the profile",
|
|
3049
|
+
engineUnavailableShort: "Unavailable",
|
|
3050
|
+
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",
|
|
3051
|
+
engineMissingKey: "API key missing",
|
|
3052
|
+
rowInfo: "Details",
|
|
3053
|
+
voiceDefaultOption: "Default ({name})",
|
|
3054
|
+
voiceCurrentOption: "Current ({name})",
|
|
3055
|
+
segInput: "Voice input",
|
|
3056
|
+
segReadAloud: "Read aloud",
|
|
3057
|
+
segDisplay: "Display & interaction",
|
|
3058
|
+
segAdvanced: "Advanced",
|
|
3059
|
+
segListLabel: "Settings sections",
|
|
3060
|
+
segTuning: "Tuning & troubleshooting",
|
|
3061
|
+
segReplacements: "Corrections",
|
|
3062
|
+
errApiKeyMissingHint: "Read-aloud requires an API key: fill the key above and click Test read-aloud, or switch to a local engine",
|
|
3063
|
+
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)",
|
|
3064
|
+
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",
|
|
3065
|
+
previewAuth: "The server rejected authentication: API key missing or invalid",
|
|
2510
3066
|
errRemoteTts: "The TTS server is unreachable, failing or too slow; the local fallback reads aloud meanwhile if one is configured",
|
|
2511
3067
|
descVoiceKokoro: "Kokoro zh-en voices (103; \u25C0\u25B6 to cycle; 48-51 named Chinese, others numbered with measured gender; mixed zh-en supported)",
|
|
2512
3068
|
descRate: "Speech rate (0.5 slow \u2013 2.0 fast, 1.1 default; more compact replies)",
|
|
2513
3069
|
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
|
|
3070
|
+
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
3071
|
bargeInDetect: "Auto-detect",
|
|
2516
3072
|
bargeInAuto: "Auto",
|
|
2517
3073
|
bargeInManual: "Manual",
|
|
@@ -2521,7 +3077,7 @@ var en = {
|
|
|
2521
3077
|
aecOff: "Native AEC off",
|
|
2522
3078
|
aecOffHint: "Native echo cancellation is not active (speaker echo may self-interrupt); use headphones or Manual barge-in",
|
|
2523
3079
|
// 批 7O(ADR-0006):detect 模式第一级探测降级提示(英文)。
|
|
2524
|
-
bargeInDetectFallback: "Native echo cancellation is off
|
|
3080
|
+
bargeInDetectFallback: "Native echo cancellation is off: speak directly when idle, hold to interrupt playback",
|
|
2525
3081
|
// R1 收尾(fix-client 直连 tk() 调用):连续 3 次回声拒断的解释出口 + 快捷键非法停用提示。
|
|
2526
3082
|
echoRejectHint: "Strong echo detected \u2014 barge-in is limited by echo protection. Use headphones or switch to manual barge-in",
|
|
2527
3083
|
shortcutInvalid: "Invalid shortcut, disabled. Fix it in settings (e.g. Ctrl+Shift+V); leave empty to use the mic button only",
|
|
@@ -2567,9 +3123,33 @@ var en = {
|
|
|
2567
3123
|
captionWidth70: "Medium",
|
|
2568
3124
|
captionWidth90: "Wide",
|
|
2569
3125
|
skipReading: "Skip this sentence",
|
|
3126
|
+
captionHistoryOpen: "History ({count})",
|
|
3127
|
+
captionHistoryHide: "Collapse",
|
|
3128
|
+
captionDismiss: "Close captions",
|
|
3129
|
+
tabSwitchFlushedNotice: "Speech before tab switch was finalized into draft",
|
|
3130
|
+
sessionSwitchFlushedNotice: "Speech from previous session saved; restores to draft on return",
|
|
3131
|
+
ttsRetryingNotice: "Retrying read-aloud ({attempt}/{max})\u2026",
|
|
3132
|
+
tabPreemptedNotice: "Voice mode was taken over by another tab",
|
|
3133
|
+
firstUseToggle: "Speak directly \u2014 pauses commit and send; speak or hold the mic to interrupt replies",
|
|
3134
|
+
firstUseHold: "Hold the mic button or Ctrl to speak, release to send; press Esc or slide up to cancel",
|
|
3135
|
+
firstUseHoldMac: "Hold the mic button or \u2303 Control (Ctrl, not \u2318 Command) to speak, release to send; Esc cancels",
|
|
3136
|
+
firstUseOnce: "Speak one request \u2014 it sends after a pause and exits once the reply finishes reading",
|
|
3137
|
+
firstUseWake: 'Say the wake word "{wake}" to start speaking (or say it together with your request)',
|
|
3138
|
+
modeInlineToggle: "Speak directly after entering \u2014 pauses auto-send; hold and release Ctrl while speaking to send now",
|
|
3139
|
+
modeInlineToggleMac: "Speak directly after entering \u2014 pauses auto-send; hold and release \u2303 Control while speaking to send now",
|
|
3140
|
+
modeInlineHold: "Hold the mic directly from idle, or enter voice mode and hold Ctrl to speak, release to send, Esc to cancel",
|
|
3141
|
+
modeInlineHoldMac: "Hold the mic directly from idle, or enter voice mode and hold \u2303 Control (not \u2318 Command) to speak, release to send, Esc to cancel",
|
|
3142
|
+
modeInlineOnce: "Speak one request to auto-send; exits voice mode automatically once the reply finishes reading",
|
|
3143
|
+
bargeInInlineDetect: "Probes native echo cancellation: speak to interrupt when active; switches to hold-to-interrupt on open speakers",
|
|
3144
|
+
bargeInInlineAuto: "Speak directly to interrupt playback (recommended with headphones or in quiet rooms)",
|
|
3145
|
+
bargeInInlineManual: "Best for speakers: speak normally when idle; hold mic or Ctrl during playback to interrupt without echo false triggers",
|
|
3146
|
+
bargeInInlineManualMac: "Best for speakers: speak normally when idle; hold mic or \u2303 Control during playback to interrupt without echo false triggers",
|
|
3147
|
+
shortcutBuiltInNote: "Built-in keys: hold Ctrl to speak in Hold-to-talk (release sends); hold and release Ctrl in Continuous mode to send now; Esc stops playback/cancels, double-Esc exits.",
|
|
3148
|
+
shortcutBuiltInNoteMac: "Built-in keys (Mac): hold \u2303 Control (not \u2318 Command) to speak in Hold-to-talk; hold and release \u2303 Control in Continuous mode to send now; Esc stops/cancels, double-Esc exits.",
|
|
2570
3149
|
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
3150
|
// Issue #15 batch 1 / ADR-0012: barge-in speech salvage.
|
|
2572
3151
|
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)",
|
|
3152
|
+
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
3153
|
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
3154
|
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
3155
|
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 +3166,9 @@ var en = {
|
|
|
2586
3166
|
descShowCaptions: "Show a floating caption of the current sentence while reading aloud",
|
|
2587
3167
|
showStatusBarLabel: "Status bar",
|
|
2588
3168
|
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;
|
|
3169
|
+
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
3170
|
wakePlaceholder: "e.g. Hey D",
|
|
2591
|
-
settingsCardDesc: "
|
|
3171
|
+
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
3172
|
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
3173
|
effectivePending: "{count} change(s) will apply next time you enter voice mode: {items}",
|
|
2594
3174
|
valueOn: "On",
|
|
@@ -2618,6 +3198,7 @@ var en = {
|
|
|
2618
3198
|
modelsRetrying: "Retrying\u2026",
|
|
2619
3199
|
modelsRetryHint: "Click to retry now after switching mirror or a failure",
|
|
2620
3200
|
modelsHint: "Live download state; failures auto-backoff 60s. After switching the mirror, click Retry to take effect immediately; npm run prefetch pre-downloads.",
|
|
3201
|
+
modelActionFailed: "Action did not take effect: the host rejected it (retry later or check host logs)",
|
|
2621
3202
|
engineLoading: "loading\u2026",
|
|
2622
3203
|
engineReady: "ready",
|
|
2623
3204
|
engineError: "failed",
|
|
@@ -2628,7 +3209,7 @@ var en = {
|
|
|
2628
3209
|
ttsDownloading: "Downloading\u2026",
|
|
2629
3210
|
ttsDeleting: "Deleting\u2026",
|
|
2630
3211
|
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)",
|
|
3212
|
+
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
3213
|
ttsDeleteHint: "Delete local models (frees space; auto re-downloads on next use)",
|
|
2633
3214
|
kokoroModelInt8: "int8 (default)",
|
|
2634
3215
|
kokoroModelFp32: "fp32 (better quality)",
|
|
@@ -2758,18 +3339,30 @@ async function correctText(ctx, text, lang) {
|
|
|
2758
3339
|
const sel = ctx?.get?.("agentDefaultModel")?.currentSelection?.();
|
|
2759
3340
|
if (!llm || typeof llm.stream !== "function") return text;
|
|
2760
3341
|
if (!sel?.provider || !sel?.model) return text;
|
|
2761
|
-
const
|
|
2762
|
-
|
|
2763
|
-
|
|
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
|
-
});
|
|
3342
|
+
const ac = new AbortController();
|
|
3343
|
+
const timer = setTimeout(() => ac.abort(new Error("llm correction timeout")), 1e4);
|
|
3344
|
+
const maxAllowed = Math.max(trimmed.length * 3, trimmed.length + 24);
|
|
2770
3345
|
let out = "";
|
|
2771
|
-
|
|
2772
|
-
|
|
3346
|
+
try {
|
|
3347
|
+
const stream = llm.stream({
|
|
3348
|
+
provider: sel.provider,
|
|
3349
|
+
model: sel.model,
|
|
3350
|
+
system: correctionSystem(lang),
|
|
3351
|
+
// host 侧自弃 10s(早于客户端 12s,审查 M3):超时或输出失控超长均立即 abort。
|
|
3352
|
+
signal: ac.signal,
|
|
3353
|
+
messages: [{ role: "user", content: [{ type: "text", text: trimmed }] }]
|
|
3354
|
+
});
|
|
3355
|
+
for await (const chunk of stream) {
|
|
3356
|
+
if (chunk && chunk.type === "text-delta" && typeof chunk.text === "string") {
|
|
3357
|
+
out += chunk.text;
|
|
3358
|
+
if (out.length > maxAllowed + 32) {
|
|
3359
|
+
ac.abort(new Error("llm correction output exceeded max length"));
|
|
3360
|
+
return text;
|
|
3361
|
+
}
|
|
3362
|
+
}
|
|
3363
|
+
}
|
|
3364
|
+
} finally {
|
|
3365
|
+
clearTimeout(timer);
|
|
2773
3366
|
}
|
|
2774
3367
|
const corrected = out.trim();
|
|
2775
3368
|
if (corrected.length > Math.max(trimmed.length * 3, trimmed.length + 24)) return text;
|
|
@@ -2787,13 +3380,114 @@ async function correctText(ctx, text, lang) {
|
|
|
2787
3380
|
if (CORRECTION_PREAMBLE_RE.test(noFiller)) return text;
|
|
2788
3381
|
}
|
|
2789
3382
|
return corrected || text;
|
|
2790
|
-
} catch {
|
|
3383
|
+
} catch (e) {
|
|
3384
|
+
console.warn(`[dsh-voice-mode] llm correction failed: ${redactSecrets(e)}`);
|
|
2791
3385
|
return text;
|
|
2792
3386
|
}
|
|
2793
3387
|
}
|
|
2794
3388
|
|
|
3389
|
+
// src/audio-format.ts
|
|
3390
|
+
function sniffAudioMime(buf, fallback) {
|
|
3391
|
+
if (buf.length >= 12 && buf.subarray(0, 4).toString("latin1") === "RIFF" && buf.subarray(8, 12).toString("latin1") === "WAVE") {
|
|
3392
|
+
return "audio/wav";
|
|
3393
|
+
}
|
|
3394
|
+
if (buf.length >= 4 && buf.subarray(0, 4).toString("latin1") === "OggS") return "audio/ogg";
|
|
3395
|
+
if (buf.length >= 4 && buf.subarray(0, 4).toString("latin1") === "fLaC") return "audio/flac";
|
|
3396
|
+
if (buf.length >= 3 && buf[0] === 73 && buf[1] === 68 && buf[2] === 51) return "audio/mpeg";
|
|
3397
|
+
if (buf.length >= 7 && buf[0] === 255 && (buf[1] & 246) === 240) return "audio/aac";
|
|
3398
|
+
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) {
|
|
3399
|
+
return "audio/mpeg";
|
|
3400
|
+
}
|
|
3401
|
+
return fallback;
|
|
3402
|
+
}
|
|
3403
|
+
|
|
3404
|
+
// src/online-tts.ts
|
|
3405
|
+
var CUSTOM_PRESET_ID = "custom";
|
|
3406
|
+
var trim = (v) => typeof v === "string" ? v.trim() : "";
|
|
3407
|
+
function lookupPreset(presetId) {
|
|
3408
|
+
const id = trim(presetId);
|
|
3409
|
+
if (!id || id === CUSTOM_PRESET_ID) return null;
|
|
3410
|
+
return Object.hasOwn(OPENAI_PRESETS, id) ? OPENAI_PRESETS[id] : null;
|
|
3411
|
+
}
|
|
3412
|
+
function resolveOnlineTts(overrides, config) {
|
|
3413
|
+
const preset = lookupPreset(overrides.presetId);
|
|
3414
|
+
const settingBase = trim(overrides.baseUrl);
|
|
3415
|
+
const presetBase = trim(preset?.baseUrl);
|
|
3416
|
+
const configBase = trim(config.baseUrl);
|
|
3417
|
+
const baseUrl = settingBase || presetBase || configBase;
|
|
3418
|
+
const settingModel = trim(overrides.model);
|
|
3419
|
+
const presetModel = trim(preset?.model);
|
|
3420
|
+
const configModel = trim(config.model);
|
|
3421
|
+
const model = settingModel || presetModel || configModel;
|
|
3422
|
+
const settingVoice = trim(overrides.voice);
|
|
3423
|
+
const presetVoice = trim(preset?.voice);
|
|
3424
|
+
const configVoice = trim(config.voice);
|
|
3425
|
+
const voice = settingVoice || presetVoice || configVoice;
|
|
3426
|
+
const settingKey = trim(overrides.apiKey);
|
|
3427
|
+
const presetId = trim(overrides.presetId);
|
|
3428
|
+
const settingsPresetKey = preset !== null && presetId && Object.hasOwn(overrides.apiKeys ?? {}, presetId) && typeof overrides.apiKeys?.[presetId] === "string" ? trim(overrides.apiKeys?.[presetId]) : "";
|
|
3429
|
+
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]) : "";
|
|
3430
|
+
const configKey = trim(config.apiKey);
|
|
3431
|
+
const apiKey = settingsPresetKey || settingKey || presetKey || configKey;
|
|
3432
|
+
return {
|
|
3433
|
+
presetId,
|
|
3434
|
+
baseUrl,
|
|
3435
|
+
model,
|
|
3436
|
+
voice,
|
|
3437
|
+
apiKey,
|
|
3438
|
+
from: {
|
|
3439
|
+
baseUrl: settingBase ? "settings" : presetBase ? "preset" : configBase ? "config" : "none",
|
|
3440
|
+
model: settingModel ? "settings" : presetModel ? "preset" : configModel ? "config" : "none",
|
|
3441
|
+
voice: settingVoice ? "settings" : presetVoice ? "preset" : configVoice ? "config" : "none",
|
|
3442
|
+
apiKey: settingsPresetKey ? "settingsPreset" : settingKey ? "settings" : presetKey ? "presetKey" : configKey ? "configKey" : "none"
|
|
3443
|
+
}
|
|
3444
|
+
};
|
|
3445
|
+
}
|
|
3446
|
+
|
|
2795
3447
|
// src/tts-openai.ts
|
|
2796
3448
|
var MIME = { mp3: "audio/mpeg", wav: "audio/wav" };
|
|
3449
|
+
var MAX_AUDIO_BYTES = 16 * 1024 * 1024;
|
|
3450
|
+
var MAX_ERROR_BYTES = 8 * 1024;
|
|
3451
|
+
async function readResponseBytes(res, maxBytes, truncate) {
|
|
3452
|
+
const lenHeader = Number(res.headers.get("content-length") ?? 0);
|
|
3453
|
+
if (!truncate && Number.isFinite(lenHeader) && lenHeader > maxBytes) {
|
|
3454
|
+
await res.body?.cancel().catch(() => void 0);
|
|
3455
|
+
throw new OpenAiTtsError("openai_too_large", `audio response exceeds ${maxBytes} bytes`);
|
|
3456
|
+
}
|
|
3457
|
+
if (res.body && typeof res.body.getReader === "function") {
|
|
3458
|
+
const reader = res.body.getReader();
|
|
3459
|
+
const chunks = [];
|
|
3460
|
+
let total = 0;
|
|
3461
|
+
try {
|
|
3462
|
+
for (; ; ) {
|
|
3463
|
+
const { done, value } = await reader.read();
|
|
3464
|
+
if (done) break;
|
|
3465
|
+
if (!value || value.byteLength === 0) continue;
|
|
3466
|
+
if (total + value.byteLength > maxBytes) {
|
|
3467
|
+
if (truncate) {
|
|
3468
|
+
const take = maxBytes - total;
|
|
3469
|
+
if (take > 0) chunks.push(value.subarray(0, take));
|
|
3470
|
+
await reader.cancel().catch(() => void 0);
|
|
3471
|
+
break;
|
|
3472
|
+
}
|
|
3473
|
+
await reader.cancel().catch(() => void 0);
|
|
3474
|
+
throw new OpenAiTtsError("openai_too_large", `audio response exceeds ${maxBytes} bytes`);
|
|
3475
|
+
}
|
|
3476
|
+
chunks.push(value);
|
|
3477
|
+
total += value.byteLength;
|
|
3478
|
+
}
|
|
3479
|
+
} finally {
|
|
3480
|
+
reader.releaseLock();
|
|
3481
|
+
}
|
|
3482
|
+
return Buffer.concat(chunks);
|
|
3483
|
+
}
|
|
3484
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
3485
|
+
if (buf.length > maxBytes) {
|
|
3486
|
+
if (truncate) return buf.subarray(0, maxBytes);
|
|
3487
|
+
throw new OpenAiTtsError("openai_too_large", `audio response exceeds ${maxBytes} bytes`);
|
|
3488
|
+
}
|
|
3489
|
+
return buf;
|
|
3490
|
+
}
|
|
2797
3491
|
var OpenAiTtsError = class extends Error {
|
|
2798
3492
|
code;
|
|
2799
3493
|
constructor(code, message) {
|
|
@@ -2807,6 +3501,9 @@ function speechUrl(baseUrl) {
|
|
|
2807
3501
|
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
2808
3502
|
throw new OpenAiTtsError("openai_bad_url", "baseUrl must be http(s)");
|
|
2809
3503
|
}
|
|
3504
|
+
if (url.username || url.password) {
|
|
3505
|
+
throw new OpenAiTtsError("openai_bad_url", "baseUrl must not include credentials");
|
|
3506
|
+
}
|
|
2810
3507
|
const noSlash = url.pathname.replace(/\/+$/, "");
|
|
2811
3508
|
const base = noSlash.endsWith("/audio/speech") ? noSlash.slice(0, -"/audio/speech".length) : noSlash;
|
|
2812
3509
|
url.pathname = `${base}/audio/speech`;
|
|
@@ -2824,6 +3521,7 @@ var OpenAiTtsEngine = class {
|
|
|
2824
3521
|
now;
|
|
2825
3522
|
fallbackEngine = null;
|
|
2826
3523
|
inflight = /* @__PURE__ */ new Set();
|
|
3524
|
+
closed = false;
|
|
2827
3525
|
downUntil = 0;
|
|
2828
3526
|
lastError;
|
|
2829
3527
|
lastMime;
|
|
@@ -2847,32 +3545,38 @@ var OpenAiTtsEngine = class {
|
|
|
2847
3545
|
this.now = options.now ?? Date.now;
|
|
2848
3546
|
this.lastMime = MIME[this.format];
|
|
2849
3547
|
}
|
|
2850
|
-
/** 最近一次成功合成所用格式(远程或回退引擎的 MIME
|
|
3548
|
+
/** 最近一次成功合成所用格式(远程或回退引擎的 MIME 可能不同;并发请用 synthesizeWithMime)。 */
|
|
2851
3549
|
get mime() {
|
|
2852
3550
|
return this.lastMime;
|
|
2853
3551
|
}
|
|
2854
3552
|
updateVoice(voice, rate) {
|
|
2855
|
-
this.voice = voice || this.options.voice;
|
|
3553
|
+
this.voice = voice.trim() || this.options.voice;
|
|
2856
3554
|
if (rate !== void 0 && Number.isFinite(rate)) this.rate = rate;
|
|
2857
3555
|
}
|
|
2858
3556
|
async synthesize(text, options = {}) {
|
|
3557
|
+
return (await this.synthesizeWithMime(text, options)).buf;
|
|
3558
|
+
}
|
|
3559
|
+
/** 合成并**随结果返回**本句专属 MIME(B6:不从共享 this.lastMime 事后回读,并发异构容器不串味)。 */
|
|
3560
|
+
async synthesizeWithMime(text, options = {}) {
|
|
3561
|
+
if (this.closed) throw new OpenAiTtsError("openai_closed", "remote TTS engine closed");
|
|
2859
3562
|
const input = stripEmotionTags(text).replace(/\s+/g, " ").trim();
|
|
2860
|
-
if (input === "") return Buffer.alloc(0);
|
|
3563
|
+
if (input === "") return { buf: Buffer.alloc(0), mime: this.lastMime };
|
|
2861
3564
|
if (this.now() >= this.downUntil) {
|
|
2862
3565
|
try {
|
|
2863
|
-
const
|
|
3566
|
+
const res = await this.remote(input, options);
|
|
2864
3567
|
this.lastError = void 0;
|
|
2865
|
-
|
|
2866
|
-
return buf;
|
|
3568
|
+
return res;
|
|
2867
3569
|
} catch (e) {
|
|
3570
|
+
if (this.closed) throw new OpenAiTtsError("openai_closed", "remote TTS engine closed");
|
|
2868
3571
|
if (e.name === "AbortError" && !(e instanceof OpenAiTtsError)) throw e;
|
|
2869
3572
|
const err = e instanceof OpenAiTtsError ? e : new OpenAiTtsError("openai_unreachable", String(e));
|
|
2870
3573
|
this.lastError = err;
|
|
2871
3574
|
this.downUntil = this.now() + this.cooldownMs;
|
|
2872
3575
|
if (!this.options.fallback) throw err;
|
|
2873
|
-
console.warn(`[dsh-voice-mode] remote TTS failed, using the local fallback for ${this.cooldownMs} ms: ${err
|
|
3576
|
+
console.warn(`[dsh-voice-mode] remote TTS failed, using the local fallback for ${this.cooldownMs} ms: ${redactSecrets(err)}`);
|
|
2874
3577
|
}
|
|
2875
3578
|
}
|
|
3579
|
+
if (this.closed) throw new OpenAiTtsError("openai_closed", "remote TTS engine closed");
|
|
2876
3580
|
return this.viaFallback(text, options);
|
|
2877
3581
|
}
|
|
2878
3582
|
async remote(input, options) {
|
|
@@ -2880,9 +3584,10 @@ var OpenAiTtsEngine = class {
|
|
|
2880
3584
|
const body = {
|
|
2881
3585
|
model: this.options.model,
|
|
2882
3586
|
input,
|
|
2883
|
-
voice: options.voice || this.voice,
|
|
2884
3587
|
response_format: this.format
|
|
2885
3588
|
};
|
|
3589
|
+
const voice = (options.voice || this.voice || "").trim();
|
|
3590
|
+
if (voice) body.voice = voice;
|
|
2886
3591
|
const rate = options.rate ?? this.rate;
|
|
2887
3592
|
if (rate !== void 0 && rate > 0 && rate !== 1) body.speed = rate;
|
|
2888
3593
|
if (this.options.instructions) body.instructions = this.options.instructions;
|
|
@@ -2896,14 +3601,36 @@ var OpenAiTtsEngine = class {
|
|
|
2896
3601
|
}, this.timeoutMs);
|
|
2897
3602
|
this.inflight.add(ac);
|
|
2898
3603
|
try {
|
|
2899
|
-
const res = await this.fetchImpl(this.url, {
|
|
3604
|
+
const res = await this.fetchImpl(this.url, {
|
|
3605
|
+
method: "POST",
|
|
3606
|
+
headers,
|
|
3607
|
+
body: JSON.stringify(body),
|
|
3608
|
+
signal: ac.signal,
|
|
3609
|
+
redirect: "error"
|
|
3610
|
+
});
|
|
2900
3611
|
if (!res.ok) {
|
|
2901
|
-
const
|
|
3612
|
+
const rawErr = await readResponseBytes(res, MAX_ERROR_BYTES, true).then((b) => b.toString("utf8"), () => "");
|
|
3613
|
+
const detail = redactBodySnippet(rawErr);
|
|
2902
3614
|
throw new OpenAiTtsError("openai_http_error", `HTTP ${res.status}${detail ? `: ${detail}` : ""}`);
|
|
2903
3615
|
}
|
|
2904
|
-
const
|
|
3616
|
+
const ctype = (res.headers.get("content-type") ?? "").toLowerCase();
|
|
3617
|
+
const buf = await readResponseBytes(res, MAX_AUDIO_BYTES, false);
|
|
2905
3618
|
if (buf.length === 0) throw new OpenAiTtsError("openai_empty_audio", "empty audio");
|
|
2906
|
-
|
|
3619
|
+
const sniffed = sniffAudioMime(buf, "");
|
|
3620
|
+
let mime;
|
|
3621
|
+
if (sniffed) {
|
|
3622
|
+
mime = sniffed;
|
|
3623
|
+
} else if (ctype.startsWith("audio/")) {
|
|
3624
|
+
const head = buf.subarray(0, 64).toString("utf8").trimStart();
|
|
3625
|
+
if (head.startsWith("<") || head.startsWith("{") || head.startsWith("[")) {
|
|
3626
|
+
throw new OpenAiTtsError("openai_bad_payload", "audio content-type but textual body");
|
|
3627
|
+
}
|
|
3628
|
+
mime = ctype.split(";")[0].trim();
|
|
3629
|
+
} else {
|
|
3630
|
+
throw new OpenAiTtsError("openai_bad_payload", `non-audio response (content-type: ${ctype || "none"})`);
|
|
3631
|
+
}
|
|
3632
|
+
this.lastMime = mime;
|
|
3633
|
+
return { buf, mime };
|
|
2907
3634
|
} catch (e) {
|
|
2908
3635
|
if (timedOut) throw new OpenAiTtsError("openai_timeout", `no audio within ${this.timeoutMs} ms`);
|
|
2909
3636
|
throw e;
|
|
@@ -2913,13 +3640,16 @@ var OpenAiTtsEngine = class {
|
|
|
2913
3640
|
}
|
|
2914
3641
|
}
|
|
2915
3642
|
async viaFallback(text, options) {
|
|
3643
|
+
if (this.closed) throw new OpenAiTtsError("openai_closed", "remote TTS engine closed");
|
|
2916
3644
|
if (!this.options.fallback) {
|
|
2917
3645
|
throw this.lastError ?? new OpenAiTtsError("openai_unreachable", "remote TTS unavailable");
|
|
2918
3646
|
}
|
|
2919
3647
|
this.fallbackEngine ??= this.options.fallback();
|
|
2920
|
-
const
|
|
2921
|
-
|
|
2922
|
-
|
|
3648
|
+
const fb = this.fallbackEngine;
|
|
3649
|
+
const rateOpt = { rate: options.rate ?? this.rate };
|
|
3650
|
+
const res = fb.synthesizeWithMime ? await fb.synthesizeWithMime(text, rateOpt) : { buf: await fb.synthesize(text, rateOpt), mime: fb.mime };
|
|
3651
|
+
this.lastMime = res.mime;
|
|
3652
|
+
return res;
|
|
2923
3653
|
}
|
|
2924
3654
|
interrupt() {
|
|
2925
3655
|
for (const ac of this.inflight) ac.abort();
|
|
@@ -2935,16 +3665,203 @@ var OpenAiTtsEngine = class {
|
|
|
2935
3665
|
ready: !fallingBack && !this.configError,
|
|
2936
3666
|
loading: false,
|
|
2937
3667
|
error: this.lastError?.message,
|
|
2938
|
-
errorCode: this.lastError?.code
|
|
3668
|
+
errorCode: this.lastError?.code,
|
|
3669
|
+
// 2026-11-20 UX:只回布尔——状态卡据此提示「缺 API Key」,绝不回传 key。
|
|
3670
|
+
keyPresent: Boolean(this.options.apiKey && this.options.apiKey.trim().length > 0)
|
|
2939
3671
|
};
|
|
2940
3672
|
}
|
|
2941
3673
|
async close() {
|
|
3674
|
+
this.closed = true;
|
|
2942
3675
|
this.interrupt();
|
|
2943
3676
|
const fb = this.fallbackEngine;
|
|
2944
3677
|
this.fallbackEngine = null;
|
|
2945
3678
|
await fb?.close();
|
|
2946
3679
|
}
|
|
2947
3680
|
};
|
|
3681
|
+
function presetRequiresKey(presetId) {
|
|
3682
|
+
if (!presetId) return false;
|
|
3683
|
+
if (!Object.prototype.hasOwnProperty.call(OPENAI_PRESETS, presetId)) return false;
|
|
3684
|
+
return !presetId.startsWith("selfhosted-");
|
|
3685
|
+
}
|
|
3686
|
+
var SILICONFLOW_SYSTEM_VOICES = ["alex", "benjamin", "charles", "david", "anna", "bella", "claire", "diana"];
|
|
3687
|
+
var OPENAI_API_VOICES = ["alloy", "ash", "ballad", "coral", "echo", "fable", "marin", "cedar", "nova", "onyx", "sage", "shimmer"];
|
|
3688
|
+
var OPENAI_PRESETS = {
|
|
3689
|
+
"siliconflow-cosyvoice2": {
|
|
3690
|
+
baseUrl: "https://api.siliconflow.cn/v1",
|
|
3691
|
+
model: "FunAudioLLM/CosyVoice2-0.5B",
|
|
3692
|
+
voice: "FunAudioLLM/CosyVoice2-0.5B:alex",
|
|
3693
|
+
voices: SILICONFLOW_SYSTEM_VOICES.map((v) => `FunAudioLLM/CosyVoice2-0.5B:${v}`)
|
|
3694
|
+
},
|
|
3695
|
+
"siliconflow-fish": {
|
|
3696
|
+
baseUrl: "https://api.siliconflow.cn/v1",
|
|
3697
|
+
model: "fishaudio/fish-speech-1.5",
|
|
3698
|
+
voice: "fishaudio/fish-speech-1.5:anna",
|
|
3699
|
+
voices: SILICONFLOW_SYSTEM_VOICES.map((v) => `fishaudio/fish-speech-1.5:${v}`)
|
|
3700
|
+
},
|
|
3701
|
+
// OpenRouter 官方 TTS 文档(2026-05-01 公告):POST /api/v1/audio/speech,
|
|
3702
|
+
// 示例模型 slug 为带日期的 `openai/gpt-4o-mini-tts-2025-12-15`、voice `alloy`、response_format mp3。
|
|
3703
|
+
// OpenRouter 透传 OpenAI 语音名,故沿用 OpenAI 全量音色表。
|
|
3704
|
+
"openrouter-openai": {
|
|
3705
|
+
baseUrl: "https://openrouter.ai/api/v1",
|
|
3706
|
+
model: "openai/gpt-4o-mini-tts-2025-12-15",
|
|
3707
|
+
voice: "alloy",
|
|
3708
|
+
voices: [...OPENAI_API_VOICES]
|
|
3709
|
+
},
|
|
3710
|
+
// OpenAI 官方(docs: /v1/audio/speech,模型 gpt-4o-mini-tts,官方推荐 marin/cedar 音质最佳)。
|
|
3711
|
+
"openai-official": {
|
|
3712
|
+
baseUrl: "https://api.openai.com/v1",
|
|
3713
|
+
model: "gpt-4o-mini-tts",
|
|
3714
|
+
voice: "marin",
|
|
3715
|
+
voices: [...OPENAI_API_VOICES]
|
|
3716
|
+
},
|
|
3717
|
+
// 自建示例(本机地址为占位;无鉴权时 key 留空即可):
|
|
3718
|
+
// Kokoro-FastAPI / LocalAI 的 OpenAI 兼容面,Kokoro 音色名取自本插件本地目录(zf_xiaobei 等)。
|
|
3719
|
+
// 仅收录命名中文音色(与本地 Kokoro 一致);其余 100+ 数字 sid 音色走「自定义手输」。
|
|
3720
|
+
"selfhosted-kokoro": {
|
|
3721
|
+
baseUrl: "http://127.0.0.1:8880/v1",
|
|
3722
|
+
model: "kokoro",
|
|
3723
|
+
voice: "zf_xiaobei",
|
|
3724
|
+
voices: ["zf_xiaobei", "zf_xiaoni", "zf_xiaoxiao", "zf_xiaoyi"]
|
|
3725
|
+
},
|
|
3726
|
+
// Groq 官方 API Reference「Create speech」:POST /openai/v1/audio/speech(base 为
|
|
3727
|
+
// https://api.groq.com/openai/v1),模型 playai-tts,音色列表形如 Fritz-PlayAI。
|
|
3728
|
+
// 注意(2026-11-20 核实):上游已有仓库把 playai-tts 标记为 decommissioned 并迁移到 Orpheus;
|
|
3729
|
+
// 此处仅保留文档示例音色 + 自定义手输,若 Groq 下线该模型,用户切 Orpheus 端点手填即可。
|
|
3730
|
+
"groq-playai": {
|
|
3731
|
+
baseUrl: "https://api.groq.com/openai/v1",
|
|
3732
|
+
model: "playai-tts",
|
|
3733
|
+
voice: "Fritz-PlayAI",
|
|
3734
|
+
voices: ["Fritz-PlayAI"]
|
|
3735
|
+
},
|
|
3736
|
+
// vLLM-Omni(ADR-0013 实测过 VoxCPM2 / Qwen3-TTS 部署)。音色名取决于部署的模型,保留默认 + 手输。
|
|
3737
|
+
"selfhosted-vllm": {
|
|
3738
|
+
baseUrl: "http://127.0.0.1:8000/v1",
|
|
3739
|
+
model: "tts-1",
|
|
3740
|
+
voice: "default",
|
|
3741
|
+
voices: ["default"]
|
|
3742
|
+
}
|
|
3743
|
+
};
|
|
3744
|
+
|
|
3745
|
+
// src/engine-rebuild.ts
|
|
3746
|
+
function stableApiKeys(m) {
|
|
3747
|
+
if (m === null || typeof m !== "object" || Array.isArray(m)) return "";
|
|
3748
|
+
const rec = m;
|
|
3749
|
+
const keys = Object.keys(rec).filter((k) => typeof rec[k] === "string").sort();
|
|
3750
|
+
return JSON.stringify(keys.map((k) => [k, rec[k]]));
|
|
3751
|
+
}
|
|
3752
|
+
function engineRebuildReason(prev, next, engineKind, activeKokoroModel) {
|
|
3753
|
+
if (next.ttsEngine !== engineKind) return "engine-switch";
|
|
3754
|
+
if (engineKind === "mimo" && next.mimoApiKey !== prev.mimoApiKey) return "mimo-key";
|
|
3755
|
+
if (engineKind === "kokoro" && next.kokoroModel !== activeKokoroModel) return "kokoro-model";
|
|
3756
|
+
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))) {
|
|
3757
|
+
return "openai-config";
|
|
3758
|
+
}
|
|
3759
|
+
return null;
|
|
3760
|
+
}
|
|
3761
|
+
|
|
3762
|
+
// src/settings-view.ts
|
|
3763
|
+
var SECRET_SETTING_KEYS = ["openaiApiKey", "mimoApiKey", "openaiApiKeys"];
|
|
3764
|
+
function publicSettingsView(vset, presence, fromConfig) {
|
|
3765
|
+
return {
|
|
3766
|
+
value: { ...vset, openaiApiKey: "", mimoApiKey: "", openaiApiKeys: {} },
|
|
3767
|
+
keys: { openaiApiKey: Boolean(presence.openaiApiKey), mimoApiKey: Boolean(presence.mimoApiKey), openaiApiKeys: boolMap(presence.openaiApiKeys) },
|
|
3768
|
+
keysFromConfig: {
|
|
3769
|
+
openaiApiKey: Boolean(fromConfig?.openaiApiKey),
|
|
3770
|
+
mimoApiKey: Boolean(fromConfig?.mimoApiKey),
|
|
3771
|
+
openaiApiKeys: boolMap(fromConfig?.openaiApiKeys)
|
|
3772
|
+
}
|
|
3773
|
+
};
|
|
3774
|
+
}
|
|
3775
|
+
function applyClearSecrets(patch, clearList) {
|
|
3776
|
+
const { clearSecrets: _ignored, ...rest } = patch;
|
|
3777
|
+
if (clearList !== void 0 && !Array.isArray(clearList)) {
|
|
3778
|
+
throw new Error("clearSecrets must be an array");
|
|
3779
|
+
}
|
|
3780
|
+
const list = clearList ?? [];
|
|
3781
|
+
const out = { ...rest };
|
|
3782
|
+
for (const item of list) {
|
|
3783
|
+
if (typeof item !== "string") continue;
|
|
3784
|
+
if (!SECRET_SETTING_KEYS.includes(item)) {
|
|
3785
|
+
throw new Error(`unknown secret: ${item}`);
|
|
3786
|
+
}
|
|
3787
|
+
out[item] = item === "openaiApiKeys" ? {} : "";
|
|
3788
|
+
}
|
|
3789
|
+
return out;
|
|
3790
|
+
}
|
|
3791
|
+
function mergePresetApiKeys(existing, patchMap, clearAll = false) {
|
|
3792
|
+
const out = {};
|
|
3793
|
+
if (!clearAll) {
|
|
3794
|
+
const base = readKeyMap(existing);
|
|
3795
|
+
for (const id of Object.keys(base)) {
|
|
3796
|
+
if (id === "__proto__" || id === "constructor" || id === "prototype") continue;
|
|
3797
|
+
const v = base[id];
|
|
3798
|
+
if (typeof v === "string" && v.trim().length > 0) out[id] = v.trim();
|
|
3799
|
+
}
|
|
3800
|
+
}
|
|
3801
|
+
const inc = readKeyMap(patchMap);
|
|
3802
|
+
for (const id of Object.keys(inc)) {
|
|
3803
|
+
if (id === "__proto__" || id === "constructor" || id === "prototype") continue;
|
|
3804
|
+
const v = inc[id];
|
|
3805
|
+
if (typeof v !== "string") continue;
|
|
3806
|
+
if (v.trim().length > 0) out[id] = v.trim();
|
|
3807
|
+
else delete out[id];
|
|
3808
|
+
}
|
|
3809
|
+
return out;
|
|
3810
|
+
}
|
|
3811
|
+
function hasSecret(value, ...fallbacks) {
|
|
3812
|
+
const nonEmpty = (v) => typeof v === "string" && v.trim().length > 0;
|
|
3813
|
+
return nonEmpty(value) || fallbacks.some(nonEmpty);
|
|
3814
|
+
}
|
|
3815
|
+
function boolMap(v) {
|
|
3816
|
+
if (v === null || typeof v !== "object" || Array.isArray(v)) return {};
|
|
3817
|
+
const out = {};
|
|
3818
|
+
for (const k of Object.keys(v)) out[k] = Boolean(v[k]);
|
|
3819
|
+
return out;
|
|
3820
|
+
}
|
|
3821
|
+
function readKeyMap(v) {
|
|
3822
|
+
if (v === null || typeof v !== "object" || Array.isArray(v)) return {};
|
|
3823
|
+
return v;
|
|
3824
|
+
}
|
|
3825
|
+
function buildPresetKeyPresence(settingsMap, configMap) {
|
|
3826
|
+
const s = readKeyMap(settingsMap);
|
|
3827
|
+
const c = readKeyMap(configMap);
|
|
3828
|
+
const ids = /* @__PURE__ */ new Set([...Object.keys(s), ...Object.keys(c)]);
|
|
3829
|
+
const presence = {};
|
|
3830
|
+
const fromConfig = {};
|
|
3831
|
+
for (const id of ids) {
|
|
3832
|
+
if (id === "__proto__" || id === "constructor" || id === "prototype") continue;
|
|
3833
|
+
presence[id] = hasSecret(s[id], c[id]);
|
|
3834
|
+
fromConfig[id] = hasSecret(c[id]);
|
|
3835
|
+
}
|
|
3836
|
+
return { presence, fromConfig };
|
|
3837
|
+
}
|
|
3838
|
+
function buildSettingsGetView(vset, config) {
|
|
3839
|
+
const cfgKey = hasSecret(config.openaiTts?.apiKey);
|
|
3840
|
+
const cfgMimo = hasSecret(config.mimoTts?.apiKey);
|
|
3841
|
+
const presetKeys = buildPresetKeyPresence(vset.openaiApiKeys, config.openaiTts?.apiKeys);
|
|
3842
|
+
return publicSettingsView(
|
|
3843
|
+
vset,
|
|
3844
|
+
{
|
|
3845
|
+
openaiApiKey: hasSecret(vset.openaiApiKey, config.openaiTts?.apiKey),
|
|
3846
|
+
mimoApiKey: hasSecret(vset.mimoApiKey, config.mimoTts?.apiKey),
|
|
3847
|
+
openaiApiKeys: presetKeys.presence
|
|
3848
|
+
},
|
|
3849
|
+
{ openaiApiKey: cfgKey, mimoApiKey: cfgMimo, openaiApiKeys: presetKeys.fromConfig }
|
|
3850
|
+
);
|
|
3851
|
+
}
|
|
3852
|
+
|
|
3853
|
+
// src/engine-kind.ts
|
|
3854
|
+
var TTS_ENGINE_KINDS = ["vits", "kokoro", "edge", "openai", "mimo"];
|
|
3855
|
+
var LOCAL_ENGINE_KINDS = ["vits", "kokoro"];
|
|
3856
|
+
function asTtsEngineKind(value) {
|
|
3857
|
+
return TTS_ENGINE_KINDS.includes(value) ? value : "vits";
|
|
3858
|
+
}
|
|
3859
|
+
function isLocalEngine(value) {
|
|
3860
|
+
return LOCAL_ENGINE_KINDS.includes(value);
|
|
3861
|
+
}
|
|
3862
|
+
function usesBilingualSample(value) {
|
|
3863
|
+
return value === "kokoro" || value === "openai" || value === "mimo";
|
|
3864
|
+
}
|
|
2948
3865
|
|
|
2949
3866
|
// src/prompts.ts
|
|
2950
3867
|
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 +3869,7 @@ var EN = '[Voice mode] Your reply will be read aloud. Always answer in the langu
|
|
|
2952
3869
|
var spokenPrompt = (lang) => lang === "en" ? EN : ZH;
|
|
2953
3870
|
function normalizePromptLang(raw) {
|
|
2954
3871
|
if (typeof raw !== "string" || raw === "" || raw.length > 32) return "zh";
|
|
2955
|
-
return /^zh
|
|
3872
|
+
return /^zh(?:[-_]|$)/i.test(raw) ? "zh" : "en";
|
|
2956
3873
|
}
|
|
2957
3874
|
var SAMPLE_ZH = "\u4F60\u597D\uFF0C\u6B22\u8FCE\u4F7F\u7528\u8BED\u97F3\u6A21\u5F0F\u3002";
|
|
2958
3875
|
var SAMPLE_EN = "Hello, welcome to voice mode.";
|
|
@@ -2968,15 +3885,294 @@ var SAMPLE_BY_LANG = {
|
|
|
2968
3885
|
it: "Ciao, benvenuto nella modalit\xE0 vocale.",
|
|
2969
3886
|
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
3887
|
};
|
|
3888
|
+
function mimoSpeedInstruction(rate) {
|
|
3889
|
+
return rate > 1 ? `\u8BED\u901F\u52A0\u5FEB\u5230\u7EA6 ${rate} \u500D` : `\u8BED\u901F\u653E\u6162\u5230\u7EA6 ${rate} \u500D`;
|
|
3890
|
+
}
|
|
2971
3891
|
function previewSample(engine, voice) {
|
|
2972
|
-
if (engine
|
|
3892
|
+
if (usesBilingualSample(engine)) return `${SAMPLE_ZH}${SAMPLE_EN}`;
|
|
2973
3893
|
if (engine === "vits") return SAMPLE_ZH;
|
|
2974
3894
|
const m = /^([a-z]{2,3})-/i.exec(voice);
|
|
2975
3895
|
return m && SAMPLE_BY_LANG[m[1].toLowerCase()] || SAMPLE_EN;
|
|
2976
3896
|
}
|
|
2977
3897
|
|
|
3898
|
+
// src/tts-mimo.ts
|
|
3899
|
+
var MIME2 = {
|
|
3900
|
+
wav: "audio/wav",
|
|
3901
|
+
mp3: "audio/mpeg"
|
|
3902
|
+
};
|
|
3903
|
+
var MAX_JSON_BYTES = 24 * 1024 * 1024;
|
|
3904
|
+
var MAX_ERROR_BYTES2 = 8 * 1024;
|
|
3905
|
+
async function readMimoBytes(res, maxBytes, truncate) {
|
|
3906
|
+
const lenHeader = Number(res.headers.get("content-length") ?? 0);
|
|
3907
|
+
if (!truncate && Number.isFinite(lenHeader) && lenHeader > maxBytes) {
|
|
3908
|
+
await res.body?.cancel().catch(() => void 0);
|
|
3909
|
+
throw new MimoTtsError("mimo_too_large", `response exceeds ${maxBytes} bytes`);
|
|
3910
|
+
}
|
|
3911
|
+
if (res.body && typeof res.body.getReader === "function") {
|
|
3912
|
+
const reader = res.body.getReader();
|
|
3913
|
+
const chunks = [];
|
|
3914
|
+
let total = 0;
|
|
3915
|
+
try {
|
|
3916
|
+
for (; ; ) {
|
|
3917
|
+
const { done, value } = await reader.read();
|
|
3918
|
+
if (done) break;
|
|
3919
|
+
if (!value || value.byteLength === 0) continue;
|
|
3920
|
+
if (total + value.byteLength > maxBytes) {
|
|
3921
|
+
if (truncate) {
|
|
3922
|
+
const take = maxBytes - total;
|
|
3923
|
+
if (take > 0) chunks.push(value.subarray(0, take));
|
|
3924
|
+
await reader.cancel().catch(() => void 0);
|
|
3925
|
+
break;
|
|
3926
|
+
}
|
|
3927
|
+
await reader.cancel().catch(() => void 0);
|
|
3928
|
+
throw new MimoTtsError("mimo_too_large", `response exceeds ${maxBytes} bytes`);
|
|
3929
|
+
}
|
|
3930
|
+
chunks.push(value);
|
|
3931
|
+
total += value.byteLength;
|
|
3932
|
+
}
|
|
3933
|
+
} finally {
|
|
3934
|
+
reader.releaseLock();
|
|
3935
|
+
}
|
|
3936
|
+
return Buffer.concat(chunks);
|
|
3937
|
+
}
|
|
3938
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
3939
|
+
if (buf.length > maxBytes) {
|
|
3940
|
+
if (truncate) return buf.subarray(0, maxBytes);
|
|
3941
|
+
throw new MimoTtsError("mimo_too_large", `response exceeds ${maxBytes} bytes`);
|
|
3942
|
+
}
|
|
3943
|
+
return buf;
|
|
3944
|
+
}
|
|
3945
|
+
var MimoTtsError = class extends Error {
|
|
3946
|
+
code;
|
|
3947
|
+
constructor(code, message) {
|
|
3948
|
+
super(message);
|
|
3949
|
+
this.name = "MimoTtsError";
|
|
3950
|
+
this.code = code;
|
|
3951
|
+
}
|
|
3952
|
+
};
|
|
3953
|
+
var MIMO_DEFAULT_BASE_URL = "https://api.xiaomimimo.com/v1";
|
|
3954
|
+
var MIMO_DEFAULT_MODEL = "mimo-v2.5-tts";
|
|
3955
|
+
var MIMO_DEFAULT_VOICE = "mimo_default";
|
|
3956
|
+
function mimoChatUrl(baseUrl) {
|
|
3957
|
+
const url = new URL(baseUrl.trim());
|
|
3958
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
3959
|
+
throw new MimoTtsError("mimo_bad_url", "baseUrl must be http(s)");
|
|
3960
|
+
}
|
|
3961
|
+
if (url.username || url.password) {
|
|
3962
|
+
throw new MimoTtsError("mimo_bad_url", "baseUrl must not include credentials");
|
|
3963
|
+
}
|
|
3964
|
+
const suffix = "/chat/completions";
|
|
3965
|
+
const noSlash = url.pathname.replace(/\/+$/, "");
|
|
3966
|
+
const base = noSlash.endsWith(suffix) ? noSlash.slice(0, -suffix.length) : noSlash;
|
|
3967
|
+
url.pathname = `${base}${suffix}`;
|
|
3968
|
+
return url.toString();
|
|
3969
|
+
}
|
|
3970
|
+
function extractMimoAudio(body) {
|
|
3971
|
+
if (typeof body !== "object" || body === null) return null;
|
|
3972
|
+
const choices = body.choices;
|
|
3973
|
+
if (!Array.isArray(choices) || choices.length === 0) return null;
|
|
3974
|
+
const message = choices[0].message;
|
|
3975
|
+
if (typeof message !== "object" || message === null) return null;
|
|
3976
|
+
const audio = message.audio;
|
|
3977
|
+
if (typeof audio !== "object" || audio === null) return null;
|
|
3978
|
+
const data = audio.data;
|
|
3979
|
+
return typeof data === "string" && data.length > 0 ? data : null;
|
|
3980
|
+
}
|
|
3981
|
+
function decodeBase64Audio(data) {
|
|
3982
|
+
const raw = data.replace(/\s+/g, "").replace(/-/g, "+").replace(/_/g, "/");
|
|
3983
|
+
if (raw.length === 0 || raw.length % 4 === 1) {
|
|
3984
|
+
throw new MimoTtsError("mimo_bad_audio", "audio payload is not valid base64");
|
|
3985
|
+
}
|
|
3986
|
+
const padLen = raw.length % 4 === 0 ? 0 : 4 - raw.length % 4;
|
|
3987
|
+
const clean = padLen > 0 ? raw + "=".repeat(padLen) : raw;
|
|
3988
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(clean)) {
|
|
3989
|
+
throw new MimoTtsError("mimo_bad_audio", "audio payload is not valid base64");
|
|
3990
|
+
}
|
|
3991
|
+
return Buffer.from(clean, "base64");
|
|
3992
|
+
}
|
|
3993
|
+
var MimoTtsEngine = class {
|
|
3994
|
+
voice;
|
|
3995
|
+
rate;
|
|
3996
|
+
url;
|
|
3997
|
+
configError;
|
|
3998
|
+
format;
|
|
3999
|
+
timeoutMs;
|
|
4000
|
+
cooldownMs;
|
|
4001
|
+
fetchImpl;
|
|
4002
|
+
now;
|
|
4003
|
+
fallbackEngine = null;
|
|
4004
|
+
inflight = /* @__PURE__ */ new Set();
|
|
4005
|
+
closed = false;
|
|
4006
|
+
downUntil = 0;
|
|
4007
|
+
lastError;
|
|
4008
|
+
lastMime;
|
|
4009
|
+
options;
|
|
4010
|
+
constructor(options) {
|
|
4011
|
+
this.options = options;
|
|
4012
|
+
let url = null;
|
|
4013
|
+
try {
|
|
4014
|
+
if (!options.apiKey?.trim()) {
|
|
4015
|
+
throw new MimoTtsError("mimo_not_configured", "mimo apiKey is not configured");
|
|
4016
|
+
}
|
|
4017
|
+
url = mimoChatUrl(options.baseUrl?.trim() || MIMO_DEFAULT_BASE_URL);
|
|
4018
|
+
} catch (e) {
|
|
4019
|
+
this.configError = e instanceof MimoTtsError ? e : new MimoTtsError("mimo_bad_url", "bad baseUrl");
|
|
4020
|
+
url = null;
|
|
4021
|
+
}
|
|
4022
|
+
this.url = url;
|
|
4023
|
+
this.voice = (options.voice ?? "").trim() || MIMO_DEFAULT_VOICE;
|
|
4024
|
+
this.format = options.responseFormat ?? "wav";
|
|
4025
|
+
this.timeoutMs = options.timeoutMs ?? 8e3;
|
|
4026
|
+
this.cooldownMs = options.cooldownMs ?? 3e4;
|
|
4027
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
4028
|
+
this.now = options.now ?? Date.now;
|
|
4029
|
+
this.lastMime = MIME2[this.format];
|
|
4030
|
+
}
|
|
4031
|
+
get mime() {
|
|
4032
|
+
return this.lastMime;
|
|
4033
|
+
}
|
|
4034
|
+
updateVoice(voice, rate) {
|
|
4035
|
+
this.voice = voice.trim() || this.options.voice?.trim() || MIMO_DEFAULT_VOICE;
|
|
4036
|
+
if (rate !== void 0 && Number.isFinite(rate)) this.rate = rate;
|
|
4037
|
+
}
|
|
4038
|
+
/** 合成并**随结果返回**本句专属 MIME(B6:不从共享 this.lastMime 事后回读,并发异构容器不串味)。 */
|
|
4039
|
+
async synthesizeWithMime(text, options = {}) {
|
|
4040
|
+
if (this.closed) throw new MimoTtsError("mimo_closed", "remote TTS engine closed");
|
|
4041
|
+
const input = stripEmotionTags(text).replace(/\s+/g, " ").trim();
|
|
4042
|
+
if (input === "") return { buf: Buffer.alloc(0), mime: this.lastMime };
|
|
4043
|
+
if (this.now() >= this.downUntil) {
|
|
4044
|
+
try {
|
|
4045
|
+
const res = await this.remote(input, options);
|
|
4046
|
+
this.lastError = void 0;
|
|
4047
|
+
return res;
|
|
4048
|
+
} catch (e) {
|
|
4049
|
+
if (this.closed) throw new MimoTtsError("mimo_closed", "remote TTS engine closed");
|
|
4050
|
+
if (e.name === "AbortError" && !(e instanceof MimoTtsError)) throw e;
|
|
4051
|
+
const err = e instanceof MimoTtsError ? e : new MimoTtsError("mimo_unreachable", String(e));
|
|
4052
|
+
this.lastError = err;
|
|
4053
|
+
this.downUntil = this.now() + this.cooldownMs;
|
|
4054
|
+
if (!this.options.fallback) throw err;
|
|
4055
|
+
console.warn(`[dsh-voice-mode] remote TTS failed, using the local fallback for ${this.cooldownMs} ms: ${redactSecrets(err)}`);
|
|
4056
|
+
}
|
|
4057
|
+
}
|
|
4058
|
+
if (this.closed) throw new MimoTtsError("mimo_closed", "remote TTS engine closed");
|
|
4059
|
+
return this.viaFallback(text, options);
|
|
4060
|
+
}
|
|
4061
|
+
async synthesize(text, options = {}) {
|
|
4062
|
+
return (await this.synthesizeWithMime(text, options)).buf;
|
|
4063
|
+
}
|
|
4064
|
+
/** 自然语言风格指令:配置的 instructions + 语速(MiMo 无 speed 字段,语速走风格控制)。 */
|
|
4065
|
+
styleInstruction(rate) {
|
|
4066
|
+
const parts = [];
|
|
4067
|
+
const base = (this.options.instructions ?? "").trim();
|
|
4068
|
+
if (base) parts.push(base);
|
|
4069
|
+
if (rate !== void 0 && Number.isFinite(rate) && rate > 0 && rate !== 1) {
|
|
4070
|
+
parts.push(mimoSpeedInstruction(rate));
|
|
4071
|
+
}
|
|
4072
|
+
return parts.join("; ");
|
|
4073
|
+
}
|
|
4074
|
+
async remote(input, options) {
|
|
4075
|
+
if (this.url === null) throw this.configError;
|
|
4076
|
+
const messages = [];
|
|
4077
|
+
const instruction = this.styleInstruction(options.rate ?? this.rate);
|
|
4078
|
+
if (instruction) messages.push({ role: "user", content: instruction });
|
|
4079
|
+
messages.push({ role: "assistant", content: input });
|
|
4080
|
+
const body = {
|
|
4081
|
+
model: (this.options.model ?? "").trim() || MIMO_DEFAULT_MODEL,
|
|
4082
|
+
messages,
|
|
4083
|
+
audio: { voice: (options.voice || this.voice).trim(), format: this.format },
|
|
4084
|
+
stream: false
|
|
4085
|
+
};
|
|
4086
|
+
const headers = { "content-type": "application/json" };
|
|
4087
|
+
headers["api-key"] = (this.options.apiKey ?? "").trim();
|
|
4088
|
+
const ac = new AbortController();
|
|
4089
|
+
let timedOut = false;
|
|
4090
|
+
const timer = setTimeout(() => {
|
|
4091
|
+
timedOut = true;
|
|
4092
|
+
ac.abort();
|
|
4093
|
+
}, this.timeoutMs);
|
|
4094
|
+
this.inflight.add(ac);
|
|
4095
|
+
try {
|
|
4096
|
+
const res = await this.fetchImpl(this.url, {
|
|
4097
|
+
method: "POST",
|
|
4098
|
+
headers,
|
|
4099
|
+
body: JSON.stringify(body),
|
|
4100
|
+
signal: ac.signal,
|
|
4101
|
+
redirect: "error"
|
|
4102
|
+
});
|
|
4103
|
+
if (!res.ok) {
|
|
4104
|
+
const rawErr = await readMimoBytes(res, MAX_ERROR_BYTES2, true).then((b) => b.toString("utf8"), () => "");
|
|
4105
|
+
const detail = redactBodySnippet(rawErr);
|
|
4106
|
+
throw new MimoTtsError("mimo_http_error", `HTTP ${res.status}${detail ? `: ${detail}` : ""}`);
|
|
4107
|
+
}
|
|
4108
|
+
const rawJson = (await readMimoBytes(res, MAX_JSON_BYTES, false)).toString("utf8");
|
|
4109
|
+
let parsed;
|
|
4110
|
+
try {
|
|
4111
|
+
parsed = JSON.parse(rawJson);
|
|
4112
|
+
} catch {
|
|
4113
|
+
throw new MimoTtsError("mimo_bad_payload", "non-JSON response from MiMo TTS");
|
|
4114
|
+
}
|
|
4115
|
+
const data = extractMimoAudio(parsed);
|
|
4116
|
+
if (!data) throw new MimoTtsError("mimo_empty_audio", "empty audio");
|
|
4117
|
+
const buf = decodeBase64Audio(data);
|
|
4118
|
+
if (buf.length === 0) throw new MimoTtsError("mimo_empty_audio", "empty audio");
|
|
4119
|
+
const ctype = (res.headers.get("content-type") ?? "").toLowerCase();
|
|
4120
|
+
const sniffed = sniffAudioMime(buf, "");
|
|
4121
|
+
let mime;
|
|
4122
|
+
if (sniffed) mime = sniffed;
|
|
4123
|
+
else if (ctype.startsWith("audio/")) mime = ctype.split(";")[0].trim();
|
|
4124
|
+
else throw new MimoTtsError("mimo_bad_payload", `non-audio response (content-type: ${ctype || "none"})`);
|
|
4125
|
+
this.lastMime = mime;
|
|
4126
|
+
return { buf, mime };
|
|
4127
|
+
} catch (e) {
|
|
4128
|
+
if (timedOut) throw new MimoTtsError("mimo_timeout", `no audio within ${this.timeoutMs} ms`);
|
|
4129
|
+
throw e;
|
|
4130
|
+
} finally {
|
|
4131
|
+
clearTimeout(timer);
|
|
4132
|
+
this.inflight.delete(ac);
|
|
4133
|
+
}
|
|
4134
|
+
}
|
|
4135
|
+
async viaFallback(text, options) {
|
|
4136
|
+
if (this.closed) throw new MimoTtsError("mimo_closed", "remote TTS engine closed");
|
|
4137
|
+
if (!this.options.fallback) {
|
|
4138
|
+
throw this.lastError ?? new MimoTtsError("mimo_unreachable", "remote TTS unavailable");
|
|
4139
|
+
}
|
|
4140
|
+
this.fallbackEngine ??= this.options.fallback();
|
|
4141
|
+
const fb = this.fallbackEngine;
|
|
4142
|
+
const rateOpt = { rate: options.rate ?? this.rate };
|
|
4143
|
+
const res = fb.synthesizeWithMime ? await fb.synthesizeWithMime(text, rateOpt) : { buf: await fb.synthesize(text, rateOpt), mime: fb.mime };
|
|
4144
|
+
this.lastMime = res.mime;
|
|
4145
|
+
return res;
|
|
4146
|
+
}
|
|
4147
|
+
interrupt() {
|
|
4148
|
+
for (const ac of this.inflight) ac.abort();
|
|
4149
|
+
this.inflight.clear();
|
|
4150
|
+
this.fallbackEngine?.interrupt?.();
|
|
4151
|
+
}
|
|
4152
|
+
status() {
|
|
4153
|
+
const err = this.lastError ?? this.configError;
|
|
4154
|
+
const fallingBack = this.now() < this.downUntil;
|
|
4155
|
+
return {
|
|
4156
|
+
engine: "mimo",
|
|
4157
|
+
// 冷却期(远程失败后走本地回退)同样视为非就绪,与 openai 引擎同口径。
|
|
4158
|
+
ready: !fallingBack && !this.configError,
|
|
4159
|
+
loading: false,
|
|
4160
|
+
error: err?.message,
|
|
4161
|
+
errorCode: err?.code,
|
|
4162
|
+
keyPresent: Boolean(this.options.apiKey && this.options.apiKey.trim().length > 0)
|
|
4163
|
+
};
|
|
4164
|
+
}
|
|
4165
|
+
async close() {
|
|
4166
|
+
this.closed = true;
|
|
4167
|
+
this.interrupt();
|
|
4168
|
+
const fb = this.fallbackEngine;
|
|
4169
|
+
this.fallbackEngine = null;
|
|
4170
|
+
await fb?.close();
|
|
4171
|
+
}
|
|
4172
|
+
};
|
|
4173
|
+
|
|
2978
4174
|
// src/settings-store.ts
|
|
2979
|
-
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
4175
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2980
4176
|
import { homedir } from "node:os";
|
|
2981
4177
|
import { dirname, join as join4 } from "node:path";
|
|
2982
4178
|
var SETTINGS_FILE_NAME = "voice-mode.settings.json";
|
|
@@ -3018,12 +4214,20 @@ function readOverrides(file, keys) {
|
|
|
3018
4214
|
function writeOverrides(file, values) {
|
|
3019
4215
|
mkdirSync(dirname(file), { recursive: true });
|
|
3020
4216
|
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
3021
|
-
writeFileSync(tmp, JSON.stringify(values, null, 2) + "\n", { encoding: "utf8", mode: 384 });
|
|
3022
4217
|
try {
|
|
3023
|
-
|
|
3024
|
-
|
|
4218
|
+
writeFileSync(tmp, JSON.stringify(values, null, 2) + "\n", { encoding: "utf8", mode: 384 });
|
|
4219
|
+
try {
|
|
4220
|
+
chmodSync(tmp, 384);
|
|
4221
|
+
} catch {
|
|
4222
|
+
}
|
|
4223
|
+
renameSync(tmp, file);
|
|
4224
|
+
} catch (e) {
|
|
4225
|
+
try {
|
|
4226
|
+
unlinkSync(tmp);
|
|
4227
|
+
} catch {
|
|
4228
|
+
}
|
|
4229
|
+
throw e;
|
|
3025
4230
|
}
|
|
3026
|
-
renameSync(tmp, file);
|
|
3027
4231
|
}
|
|
3028
4232
|
function parseLegacyVoiceSection(text) {
|
|
3029
4233
|
const out = {};
|
|
@@ -3076,10 +4280,12 @@ var NS_VOICE_MODE = "voice-mode";
|
|
|
3076
4280
|
var MUTED_STREAMS_WITHOUT_TURN = 4;
|
|
3077
4281
|
var BASE_PATH = "/voice-mode";
|
|
3078
4282
|
var PREVIEW_NETWORK_PATTERN = /fetch failed|ECONN|ENOTFOUND|getaddrinfo|ETIMEDOUT|EAI_AGAIN|network|unreachable|socket hang up|aborted|WebSocket error/i;
|
|
3079
|
-
var
|
|
3080
|
-
var
|
|
4283
|
+
var PREVIEW_AUTH_PATTERN = /HTTP 401|HTTP 403|unauthorized|invalid[ _-]?api[ _-]?key|incorrect api key|authentication failed|missing api key/i;
|
|
4284
|
+
var PREVIEW_ENGINE_PATTERN = /model download|model verify|init failed|child exited|tts child|local TTS|prepare|sherpa|local Kokoro|closed|init cooldown/i;
|
|
4285
|
+
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
4286
|
function classifyPreviewError(msg) {
|
|
3082
4287
|
if (PREVIEW_TEXT_PATTERN.test(msg)) return "text";
|
|
4288
|
+
if (PREVIEW_AUTH_PATTERN.test(msg)) return "auth";
|
|
3083
4289
|
if (PREVIEW_NETWORK_PATTERN.test(msg)) return "network";
|
|
3084
4290
|
if (PREVIEW_ENGINE_PATTERN.test(msg)) return "engine";
|
|
3085
4291
|
return "unknown";
|
|
@@ -3088,6 +4294,7 @@ var PREVIEW_ERROR_CODES = {
|
|
|
3088
4294
|
network: "preview_network",
|
|
3089
4295
|
engine: "preview_engine",
|
|
3090
4296
|
text: "preview_text",
|
|
4297
|
+
auth: "preview_auth",
|
|
3091
4298
|
unknown: "preview_unknown"
|
|
3092
4299
|
};
|
|
3093
4300
|
var respondJson2 = (res, status, payload) => {
|
|
@@ -3133,6 +4340,16 @@ var VOICE_SETTINGS_DEFAULTS = {
|
|
|
3133
4340
|
bargeInSalvage: true,
|
|
3134
4341
|
// Issue #15 批 4:LLM 纠错默认关(默认开=未申报的 I10 豁免+每条多一次 RTT/token)。
|
|
3135
4342
|
llmCorrect: false,
|
|
4343
|
+
// E1:在线预设默认空 = 手动(沿用 Config 文件值,零行为变化)。
|
|
4344
|
+
openaiPreset: "",
|
|
4345
|
+
openaiBaseUrl: "",
|
|
4346
|
+
openaiModel: "",
|
|
4347
|
+
openaiApiKey: "",
|
|
4348
|
+
// Q2 Key 跟预设走:面板按预设存的 key 表(空对象 = 全未配)。
|
|
4349
|
+
openaiApiKeys: {},
|
|
4350
|
+
mimoApiKey: "",
|
|
4351
|
+
// P1-3:纠错词表默认空(与 Config 层 asrReplacements 默认 [] 对齐)。
|
|
4352
|
+
asrReplacements: [],
|
|
3136
4353
|
// 批 G 任务 3:让位窗口默认 1500ms(与改造前批 5 行为字节等价;用户可调 500-3000ms)。
|
|
3137
4354
|
yieldMs: 1500
|
|
3138
4355
|
};
|
|
@@ -3165,130 +4382,167 @@ var DESC = {
|
|
|
3165
4382
|
backchannelYield: en.descBackchannelYield,
|
|
3166
4383
|
bargeInSalvage: en.descBargeInSalvage,
|
|
3167
4384
|
llmCorrect: en.descLlmCorrect,
|
|
4385
|
+
openaiPreset: en.descOpenaiPreset,
|
|
4386
|
+
openaiBaseUrl: en.descOpenaiBaseUrl,
|
|
4387
|
+
openaiModel: en.descOpenaiModel,
|
|
4388
|
+
openaiApiKey: en.descOpenaiApiKey,
|
|
4389
|
+
openaiApiKeys: en.descOpenaiApiKeys,
|
|
4390
|
+
mimoApiKey: en.descMimoApiKey,
|
|
4391
|
+
asrReplacements: en.descAsrReplacements,
|
|
3168
4392
|
yieldMs: en.descYieldMs
|
|
3169
4393
|
};
|
|
3170
4394
|
function createVoiceSettingsSchema(defs) {
|
|
3171
4395
|
const d = { ...VOICE_SETTINGS_DEFAULTS, ...defs };
|
|
3172
|
-
return
|
|
3173
|
-
ttsEngine:
|
|
4396
|
+
return z2.object({
|
|
4397
|
+
ttsEngine: z2.union(TTS_ENGINE_KINDS.map((k) => z2.const(k))).default(d.ttsEngine).description(
|
|
3174
4398
|
DESC.ttsEngine
|
|
3175
4399
|
),
|
|
3176
|
-
kokoroModel:
|
|
4400
|
+
kokoroModel: z2.union([z2.const("int8"), z2.const("fp32")]).default(d.kokoroModel).description(
|
|
3177
4401
|
DESC.kokoroModel
|
|
3178
4402
|
),
|
|
3179
|
-
voice:
|
|
4403
|
+
voice: z2.string().default(d.voice).description(
|
|
3180
4404
|
DESC.voice
|
|
3181
4405
|
),
|
|
3182
|
-
rate:
|
|
3183
|
-
interruptLevel:
|
|
4406
|
+
rate: z2.number().min(0.5).max(2).default(d.rate).description(DESC.rate),
|
|
4407
|
+
interruptLevel: z2.union([z2.const(0), z2.const(1), z2.const(2)]).default(d.interruptLevel).description(
|
|
3184
4408
|
DESC.interruptLevel
|
|
3185
4409
|
),
|
|
3186
|
-
silenceMs:
|
|
3187
|
-
idleTimeoutMinutes:
|
|
3188
|
-
modelHost:
|
|
3189
|
-
autoSend:
|
|
4410
|
+
silenceMs: z2.number().min(500).max(3e4).default(d.silenceMs).description(DESC.silenceMs),
|
|
4411
|
+
idleTimeoutMinutes: z2.number().min(1).max(120).default(d.idleTimeoutMinutes).description(DESC.idleTimeoutMinutes),
|
|
4412
|
+
modelHost: z2.string().default(d.modelHost).description(DESC.modelHost),
|
|
4413
|
+
autoSend: z2.boolean().default(d.autoSend).description(DESC.autoSend),
|
|
3190
4414
|
// 批 7N 重做 5/5:与 strings.ts descAutoResume 同步——明确「下次进入语音会话即生效」。
|
|
3191
|
-
autoResume:
|
|
3192
|
-
mode:
|
|
3193
|
-
readAloud:
|
|
3194
|
-
showCaptions:
|
|
3195
|
-
showStatusBar:
|
|
3196
|
-
composerShortcut:
|
|
3197
|
-
bargeInMode:
|
|
3198
|
-
echoGateDb:
|
|
4415
|
+
autoResume: z2.boolean().default(d.autoResume).description(DESC.autoResume),
|
|
4416
|
+
mode: z2.union([z2.const("toggle"), z2.const("hold"), z2.const("once")]).default(d.mode).description(DESC.mode),
|
|
4417
|
+
readAloud: z2.union([z2.const("voice"), z2.const("always"), z2.const("off")]).default(d.readAloud).description(DESC.readAloud),
|
|
4418
|
+
showCaptions: z2.boolean().default(d.showCaptions).description(DESC.showCaptions),
|
|
4419
|
+
showStatusBar: z2.boolean().default(d.showStatusBar).description(DESC.showStatusBar),
|
|
4420
|
+
composerShortcut: z2.string().default(d.composerShortcut).description(DESC.composerShortcut),
|
|
4421
|
+
bargeInMode: z2.union([z2.const("auto"), z2.const("manual"), z2.const("detect")]).default(d.bargeInMode).description(DESC.bargeInMode),
|
|
4422
|
+
echoGateDb: z2.number().min(3).max(12).default(d.echoGateDb).description(
|
|
3199
4423
|
DESC.echoGateDb
|
|
3200
4424
|
),
|
|
3201
|
-
shortcut:
|
|
3202
|
-
spokenFormat:
|
|
3203
|
-
senseVoice:
|
|
3204
|
-
wakeWord:
|
|
3205
|
-
toolBeep:
|
|
3206
|
-
senseITN:
|
|
3207
|
-
captionFontSize:
|
|
4425
|
+
shortcut: z2.string().default(d.shortcut).description(DESC.shortcut),
|
|
4426
|
+
spokenFormat: z2.boolean().default(d.spokenFormat).description(DESC.spokenFormat),
|
|
4427
|
+
senseVoice: z2.boolean().default(d.senseVoice).description(DESC.senseVoice),
|
|
4428
|
+
wakeWord: z2.string().default(d.wakeWord).description(DESC.wakeWord),
|
|
4429
|
+
toolBeep: z2.boolean().default(d.toolBeep).description(DESC.toolBeep),
|
|
4430
|
+
senseITN: z2.boolean().default(d.senseITN).description(DESC.senseITN),
|
|
4431
|
+
captionFontSize: z2.union([z2.const(0), z2.const(1), z2.const(2), z2.const(3)]).default(d.captionFontSize).description(
|
|
3208
4432
|
DESC.captionFontSize
|
|
3209
4433
|
),
|
|
3210
|
-
captionMaxWidth:
|
|
4434
|
+
captionMaxWidth: z2.union([z2.const(0), z2.const(1), z2.const(2)]).default(d.captionMaxWidth).description(
|
|
3211
4435
|
DESC.captionMaxWidth
|
|
3212
4436
|
),
|
|
3213
|
-
backchannelYield:
|
|
4437
|
+
backchannelYield: z2.boolean().default(d.backchannelYield).description(
|
|
3214
4438
|
DESC.backchannelYield
|
|
3215
4439
|
),
|
|
3216
4440
|
// Issue #15 批 1 / ADR-0012:打断语音抢救(默认 true,I10 有意豁免)。
|
|
3217
|
-
bargeInSalvage:
|
|
4441
|
+
bargeInSalvage: z2.boolean().default(d.bargeInSalvage).description(
|
|
3218
4442
|
DESC.bargeInSalvage
|
|
3219
4443
|
),
|
|
3220
4444
|
// Issue #15 批 4:LLM 纠错(默认 false)。
|
|
3221
|
-
llmCorrect:
|
|
4445
|
+
llmCorrect: z2.boolean().default(d.llmCorrect).description(
|
|
3222
4446
|
DESC.llmCorrect
|
|
3223
4447
|
),
|
|
3224
|
-
|
|
4448
|
+
// E1:在线预设 id('' = 手动沿用 Config 文件;已知 id 见 tts-openai.ts OPENAI_PRESETS)。
|
|
4449
|
+
openaiPreset: z2.string().default(d.openaiPreset).description(
|
|
4450
|
+
DESC.openaiPreset
|
|
4451
|
+
),
|
|
4452
|
+
// 2026-11-19:在线 TTS 的 URL/模型/key 允许在设置卡片里填(不必改 profile YAML)。
|
|
4453
|
+
openaiBaseUrl: z2.string().default(d.openaiBaseUrl).description(DESC.openaiBaseUrl),
|
|
4454
|
+
openaiModel: z2.string().default(d.openaiModel).description(DESC.openaiModel),
|
|
4455
|
+
// secret:GET /settings 会把它抹成空串,只回 hasOpenaiApiKey 布尔;POST 可写。
|
|
4456
|
+
openaiApiKey: z2.string().role("secret").default(d.openaiApiKey).description(DESC.openaiApiKey),
|
|
4457
|
+
// Q2 Key 跟预设走:面板按预设存的 key 表(值须为字符串;非字符串由 zod 拒收回 400)。
|
|
4458
|
+
openaiApiKeys: z2.dict(z2.string()).default(d.openaiApiKeys ?? {}).description(DESC.openaiApiKeys),
|
|
4459
|
+
mimoApiKey: z2.string().role("secret").default(d.mimoApiKey).description(DESC.mimoApiKey),
|
|
4460
|
+
// P1-3:用户纠错词表(默认空;非法条目由 zod 整表拒绝,POST 回 400;上限 200 条与设置卡片一致,防超大覆盖层)。
|
|
4461
|
+
asrReplacements: z2.array(AsrReplacementSchema).max(200).default(d.asrReplacements).description(
|
|
4462
|
+
DESC.asrReplacements
|
|
4463
|
+
),
|
|
4464
|
+
yieldMs: z2.number().min(500).max(3e3).default(d.yieldMs).description(
|
|
3225
4465
|
DESC.yieldMs
|
|
3226
4466
|
)
|
|
3227
4467
|
});
|
|
3228
4468
|
}
|
|
3229
4469
|
var VoiceSettingsSchema = createVoiceSettingsSchema();
|
|
3230
|
-
var OpenAiTtsConfig =
|
|
3231
|
-
baseUrl:
|
|
3232
|
-
apiKey:
|
|
3233
|
-
|
|
3234
|
-
|
|
3235
|
-
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3239
|
-
|
|
4470
|
+
var OpenAiTtsConfig = z2.object({
|
|
4471
|
+
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."),
|
|
4472
|
+
apiKey: z2.string().role("secret").default("").description("Bearer key; leave empty for servers without auth."),
|
|
4473
|
+
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."),
|
|
4474
|
+
model: z2.string().default("").description("Model name sent to the server."),
|
|
4475
|
+
voice: z2.string().default("").description("Default voice name on the server (the voice setting overrides it)."),
|
|
4476
|
+
instructions: z2.string().default("").description("Optional style instructions for models that accept them."),
|
|
4477
|
+
responseFormat: z2.union([z2.const("mp3"), z2.const("wav")]).default("mp3"),
|
|
4478
|
+
timeoutMs: z2.number().min(1e3).max(6e4).default(8e3).description("Per-sentence timeout; slower counts as unavailable."),
|
|
4479
|
+
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."),
|
|
4480
|
+
fallbackVoice: z2.string().default("").description("Voice for the fallback engine (empty = its default).")
|
|
3240
4481
|
});
|
|
3241
|
-
var
|
|
3242
|
-
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
|
|
4482
|
+
var MimoTtsConfig = z2.object({
|
|
4483
|
+
apiKey: z2.string().role("secret").default("").description("MiMo API key (sent as the api-key header; never reuse another vendor key here)."),
|
|
4484
|
+
baseUrl: z2.string().default("https://api.xiaomimimo.com/v1").description("MiMo API base URL; defaults to the official endpoint."),
|
|
4485
|
+
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."),
|
|
4486
|
+
voice: z2.string().default("mimo_default").description("Preset voice id (the voice setting overrides it)."),
|
|
4487
|
+
instructions: z2.string().default("").description("Natural-language style instruction (emotion, dialect, pace)."),
|
|
4488
|
+
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."),
|
|
4489
|
+
timeoutMs: z2.number().min(1e3).max(6e4).default(8e3).description("Per-sentence timeout; slower counts as unavailable."),
|
|
4490
|
+
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."),
|
|
4491
|
+
fallbackVoice: z2.string().default("").description("Voice for the fallback engine (empty = its default).")
|
|
4492
|
+
});
|
|
4493
|
+
var Config = z2.object({
|
|
4494
|
+
enabled: z2.boolean().default(true),
|
|
4495
|
+
cacheDir: z2.string().default(defaultModelCacheDir()),
|
|
4496
|
+
modelHost: z2.string().default("https://huggingface.co"),
|
|
4497
|
+
ttsEngine: z2.union(TTS_ENGINE_KINDS.map((k) => z2.const(k))).default("edge"),
|
|
3246
4498
|
openaiTts: OpenAiTtsConfig,
|
|
3247
|
-
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
|
|
4499
|
+
mimoTts: MimoTtsConfig,
|
|
4500
|
+
kokoroModel: z2.union([z2.const("int8"), z2.const("fp32")]).default("int8"),
|
|
4501
|
+
allowLan: z2.boolean().default(false),
|
|
4502
|
+
asrReplacements: z2.array(AsrReplacementSchema).default([]),
|
|
4503
|
+
allowCustomModelHost: z2.boolean().default(false),
|
|
4504
|
+
voice: z2.string().default("zh-CN-XiaoxiaoNeural"),
|
|
3251
4505
|
// I3(Issue #15 审查 Important):数值旋钮补 min/max,与 VoiceSettingsValue schema
|
|
3252
4506
|
// (createVoiceSettingsSchema)逐字段一致。早年 Config 层是裸 z.number()——cordis.patch.yml
|
|
3253
4507
|
// 手滑写 rate:5 会得到五倍速朗读、silenceMs:10 会把每句话按音节碎切,且没有任何一层会拦。
|
|
3254
4508
|
// 两层同界:Config 是 baseline、settings schema 是覆盖层,任一层失守都让非法值直达运行时。
|
|
3255
|
-
rate:
|
|
3256
|
-
interruptLevel:
|
|
3257
|
-
silenceMs:
|
|
3258
|
-
idleTimeoutMinutes:
|
|
4509
|
+
rate: z2.number().min(0.5).max(2).default(1.1),
|
|
4510
|
+
interruptLevel: z2.union([z2.const(0), z2.const(1), z2.const(2)]).default(0),
|
|
4511
|
+
silenceMs: z2.number().min(500).max(3e4).default(1500),
|
|
4512
|
+
idleTimeoutMinutes: z2.number().min(1).max(120).default(5),
|
|
3259
4513
|
// 设置面板字段(与 VoiceSettingsValue 一一对应;0.1.7+ 由插件自身 Config 派生读取)。
|
|
3260
4514
|
// 注意:刻意不标 .volatile() —— schemastery 3.18.4 的 volatile 会破坏 schema 函数
|
|
3261
4515
|
// 调用形态(sv({}) → {field:{}}),而 0.1.5-rc.3 起的设置分层会调用插件 Config 做
|
|
3262
4516
|
// merge,{} 透过 mergeLayers 污染并触发 ValidationError(2026-09-23 实测)。
|
|
3263
4517
|
// 0.1.7 功能读取走 config 直接读,不依赖 volatile(仅官方 UI 自动投影受影响,
|
|
3264
4518
|
// 本插件自带 settings-form 设置面板 + /voice-mode/config,不受影响)。
|
|
3265
|
-
autoSend:
|
|
3266
|
-
autoResume:
|
|
3267
|
-
mode:
|
|
3268
|
-
readAloud:
|
|
3269
|
-
showCaptions:
|
|
3270
|
-
showStatusBar:
|
|
3271
|
-
bargeInMode:
|
|
4519
|
+
autoSend: z2.boolean().default(true),
|
|
4520
|
+
autoResume: z2.boolean().default(false),
|
|
4521
|
+
mode: z2.union([z2.const("toggle"), z2.const("hold"), z2.const("once")]).default("toggle"),
|
|
4522
|
+
readAloud: z2.union([z2.const("voice"), z2.const("always"), z2.const("off")]).default("voice"),
|
|
4523
|
+
showCaptions: z2.boolean().default(true),
|
|
4524
|
+
showStatusBar: z2.boolean().default(true),
|
|
4525
|
+
bargeInMode: z2.union([z2.const("auto"), z2.const("manual"), z2.const("detect")]).default("detect"),
|
|
3272
4526
|
// I3 + M7(zod 界):echoGateDb / yieldMs 与 settings schema 同界(3-12 dB / 500-3000ms)。
|
|
3273
4527
|
// client 与 NumberField 虽会 clamp,但那只是 UI 兜底——Config 层无界时 YAML 手滑
|
|
3274
4528
|
// 仍可把回声门阈设成 0(句句误打断)或让位窗口设成 60000(让位后一分钟不说话)。
|
|
3275
|
-
echoGateDb:
|
|
3276
|
-
shortcut:
|
|
3277
|
-
composerShortcut:
|
|
3278
|
-
spokenFormat:
|
|
3279
|
-
senseVoice:
|
|
3280
|
-
wakeWord:
|
|
3281
|
-
toolBeep:
|
|
3282
|
-
senseITN:
|
|
3283
|
-
captionFontSize:
|
|
3284
|
-
captionMaxWidth:
|
|
3285
|
-
backchannelYield:
|
|
4529
|
+
echoGateDb: z2.number().min(3).max(12).default(6),
|
|
4530
|
+
shortcut: z2.string().default("Ctrl+Shift+V"),
|
|
4531
|
+
composerShortcut: z2.string().default("Alt+Enter"),
|
|
4532
|
+
spokenFormat: z2.boolean().default(true),
|
|
4533
|
+
senseVoice: z2.boolean().default(true),
|
|
4534
|
+
wakeWord: z2.string().default(""),
|
|
4535
|
+
toolBeep: z2.boolean().default(false),
|
|
4536
|
+
senseITN: z2.boolean().default(true),
|
|
4537
|
+
captionFontSize: z2.union([z2.const(0), z2.const(1), z2.const(2), z2.const(3)]).default(0),
|
|
4538
|
+
captionMaxWidth: z2.union([z2.const(0), z2.const(1), z2.const(2)]).default(1),
|
|
4539
|
+
backchannelYield: z2.boolean().default(true),
|
|
3286
4540
|
// Issue #15 批 4:LLM 纠错默认关。
|
|
3287
|
-
llmCorrect:
|
|
4541
|
+
llmCorrect: z2.boolean().default(false),
|
|
3288
4542
|
// Issue #15 批 1 / ADR-0012:打断语音抢救(默认 true,I10 有意豁免)。
|
|
3289
|
-
bargeInSalvage:
|
|
4543
|
+
bargeInSalvage: z2.boolean().default(true),
|
|
3290
4544
|
// I3 + M7(zod 界):500-3000ms,与 settings schema 一致。
|
|
3291
|
-
yieldMs:
|
|
4545
|
+
yieldMs: z2.number().min(500).max(3e3).default(1500)
|
|
3292
4546
|
});
|
|
3293
4547
|
function displayOf(v) {
|
|
3294
4548
|
return { readAloud: v.readAloud, showCaptions: v.showCaptions, showStatusBar: v.showStatusBar };
|
|
@@ -3323,7 +4577,8 @@ function voiceSettingsFromConfig(config) {
|
|
|
3323
4577
|
backchannelYield,
|
|
3324
4578
|
yieldMs,
|
|
3325
4579
|
bargeInSalvage,
|
|
3326
|
-
llmCorrect
|
|
4580
|
+
llmCorrect,
|
|
4581
|
+
asrReplacements
|
|
3327
4582
|
} = config;
|
|
3328
4583
|
return {
|
|
3329
4584
|
ttsEngine,
|
|
@@ -3354,7 +4609,16 @@ function voiceSettingsFromConfig(config) {
|
|
|
3354
4609
|
backchannelYield,
|
|
3355
4610
|
yieldMs,
|
|
3356
4611
|
bargeInSalvage,
|
|
3357
|
-
llmCorrect
|
|
4612
|
+
llmCorrect,
|
|
4613
|
+
asrReplacements,
|
|
4614
|
+
// E1:预设无 Config 基线(用户覆盖层专属),默认空 = 手动。
|
|
4615
|
+
openaiPreset: "",
|
|
4616
|
+
// 在线 TTS 的 UI 覆盖默认空:未填时按预设/配置文件走(零行为变化)。
|
|
4617
|
+
openaiBaseUrl: "",
|
|
4618
|
+
openaiModel: "",
|
|
4619
|
+
openaiApiKey: "",
|
|
4620
|
+
openaiApiKeys: {},
|
|
4621
|
+
mimoApiKey: ""
|
|
3358
4622
|
};
|
|
3359
4623
|
}
|
|
3360
4624
|
function apply(ctx, config) {
|
|
@@ -3388,8 +4652,9 @@ function apply(ctx, config) {
|
|
|
3388
4652
|
if (sessionId === null || sessionId === activeVoiceSession || tapInFlight.has(sessionId)) return;
|
|
3389
4653
|
dropTurnTables(sessionId);
|
|
3390
4654
|
};
|
|
3391
|
-
const stopFocusReading = (sessionId) => {
|
|
4655
|
+
const stopFocusReading = (sessionId, fromTabId) => {
|
|
3392
4656
|
if (sessionId === null) return;
|
|
4657
|
+
if (sessionId === activeVoiceSession && activeTabId !== null && fromTabId !== activeTabId) return;
|
|
3393
4658
|
queue.cancel(sessionId);
|
|
3394
4659
|
turnGen.set(sessionId, (turnGen.get(sessionId) ?? 0) + 1);
|
|
3395
4660
|
};
|
|
@@ -3460,22 +4725,32 @@ function apply(ctx, config) {
|
|
|
3460
4725
|
NS_VOICE_MODE,
|
|
3461
4726
|
createVoiceSettingsSchema(),
|
|
3462
4727
|
{
|
|
3463
|
-
base
|
|
3464
|
-
|
|
3465
|
-
|
|
3466
|
-
rate: config.rate,
|
|
3467
|
-
interruptLevel: config.interruptLevel,
|
|
3468
|
-
silenceMs: config.silenceMs,
|
|
3469
|
-
idleTimeoutMinutes: config.idleTimeoutMinutes,
|
|
3470
|
-
modelHost: config.modelHost
|
|
3471
|
-
}
|
|
4728
|
+
// base 用**全量** Config 映射:此前只给 7 键,其余落到 schema 默认值;旧宿主若 get() 返回
|
|
4729
|
+
// 全量,config 基线(如 voice/rate 之外的 openaiPreset 等)会被默认值覆盖(A3 审计 Minor)。
|
|
4730
|
+
base: voiceSettingsFromConfig(config)
|
|
3472
4731
|
}
|
|
3473
4732
|
);
|
|
3474
|
-
|
|
4733
|
+
const fromScope = settingsScope.get() ?? {};
|
|
4734
|
+
try {
|
|
4735
|
+
vset = resolveSettings(fromScope);
|
|
4736
|
+
} catch (e) {
|
|
4737
|
+
console.warn(`[dsh-voice-mode] settings scope returned invalid values; keeping valid keys only: ${redactSecrets(e)}`);
|
|
4738
|
+
const salvaged = {};
|
|
4739
|
+
for (const k of SETTING_KEYS) {
|
|
4740
|
+
if (!(k in fromScope)) continue;
|
|
4741
|
+
try {
|
|
4742
|
+
resolveSettings({ [k]: fromScope[k] });
|
|
4743
|
+
salvaged[k] = fromScope[k];
|
|
4744
|
+
} catch {
|
|
4745
|
+
console.warn(`[dsh-voice-mode] ignoring invalid setting from host scope: ${k}`);
|
|
4746
|
+
}
|
|
4747
|
+
}
|
|
4748
|
+
vset = resolveSettings(salvaged);
|
|
4749
|
+
}
|
|
3475
4750
|
settingsScopeRef = settingsScope;
|
|
3476
4751
|
} else {
|
|
3477
4752
|
const loaded = readOverrides(settingsFile, SETTING_KEYS);
|
|
3478
|
-
if (loaded.warn) console.warn(`[dsh-voice-mode] ignoring settings overlay ${settingsFile}: ${loaded.warn}`);
|
|
4753
|
+
if (loaded.warn) console.warn(`[dsh-voice-mode] ignoring settings overlay ${settingsFile}: ${redactSecrets(loaded.warn)}`);
|
|
3479
4754
|
let migrated = false;
|
|
3480
4755
|
if (!loaded.exists) {
|
|
3481
4756
|
const legacy = readLegacyVoiceSettings(dirname2(settingsFile), SETTING_KEYS);
|
|
@@ -3490,7 +4765,7 @@ function apply(ctx, config) {
|
|
|
3490
4765
|
resolveSettings({ [k]: v });
|
|
3491
4766
|
valid[k] = v;
|
|
3492
4767
|
} catch (e) {
|
|
3493
|
-
console.warn(`[dsh-voice-mode] ignoring invalid settings override "${k}" (falling back to the Config baseline): ${
|
|
4768
|
+
console.warn(`[dsh-voice-mode] ignoring invalid settings override "${k}" (falling back to the Config baseline): ${redactSecrets(e).slice(0, 160)}`);
|
|
3494
4769
|
}
|
|
3495
4770
|
}
|
|
3496
4771
|
try {
|
|
@@ -3501,14 +4776,25 @@ function apply(ctx, config) {
|
|
|
3501
4776
|
writeOverrides(settingsFile, valid);
|
|
3502
4777
|
console.log(`[dsh-voice-mode] migrated ${Object.keys(valid).length} setting(s) from the legacy settings.yaml to ${settingsFile}`);
|
|
3503
4778
|
} catch (e) {
|
|
3504
|
-
console.warn(`[dsh-voice-mode] legacy settings migration could not be saved (still in effect for this run): ${
|
|
4779
|
+
console.warn(`[dsh-voice-mode] legacy settings migration could not be saved (still in effect for this run): ${redactSecrets(e)}`);
|
|
3505
4780
|
}
|
|
3506
4781
|
}
|
|
3507
4782
|
} catch (e) {
|
|
3508
|
-
console.warn(`[dsh-voice-mode] settings overlay failed validation as a whole; falling back to the Config baseline: ${
|
|
4783
|
+
console.warn(`[dsh-voice-mode] settings overlay failed validation as a whole; falling back to the Config baseline: ${redactSecrets(e)}`);
|
|
3509
4784
|
vset = voiceSettingsFromConfig(config);
|
|
3510
4785
|
}
|
|
3511
4786
|
}
|
|
4787
|
+
let replacementHits = [];
|
|
4788
|
+
let replacementRuleCount = 0;
|
|
4789
|
+
const replacerBox = { fn: (text) => text };
|
|
4790
|
+
const rebuildReplacer = (rules) => {
|
|
4791
|
+
replacementRuleCount = rules.length;
|
|
4792
|
+
replacementHits = new Array(rules.length).fill(0);
|
|
4793
|
+
replacerBox.fn = createAsrReplacer(rules, (i) => {
|
|
4794
|
+
replacementHits[i] = (replacementHits[i] ?? 0) + 1;
|
|
4795
|
+
});
|
|
4796
|
+
};
|
|
4797
|
+
rebuildReplacer(vset.asrReplacements ?? []);
|
|
3512
4798
|
const asr = createAsrRuntime({
|
|
3513
4799
|
cacheDir: config.cacheDir,
|
|
3514
4800
|
modelHost: () => vset.modelHost,
|
|
@@ -3531,9 +4817,17 @@ function apply(ctx, config) {
|
|
|
3531
4817
|
// 而 bargeInMode=detect 在原生 AEC 未生效的机器上会自动落到 manual,即默认路径就可能命中。
|
|
3532
4818
|
// 待机态 push-to-talk 属产品决策(要改的是客户端手势开放条件),PM 已登记待用户拍板,
|
|
3533
4819
|
// 此处不加功能;host 侧只保证「manual 时非按压帧不入流」这一既有语义不被悄悄扩大。
|
|
3534
|
-
bargeInMode: () => vset.bargeInMode
|
|
4820
|
+
bargeInMode: () => vset.bargeInMode,
|
|
4821
|
+
replaceText: (text, isFinal) => replacerBox.fn(text, isFinal !== false)
|
|
4822
|
+
});
|
|
4823
|
+
let pluginDisposed = false;
|
|
4824
|
+
let toggleGen = 0;
|
|
4825
|
+
const enteringToggles = /* @__PURE__ */ new Set();
|
|
4826
|
+
ctx.effect(() => () => {
|
|
4827
|
+
pluginDisposed = true;
|
|
4828
|
+
toggleGen++;
|
|
4829
|
+
asr.dispose();
|
|
3535
4830
|
});
|
|
3536
|
-
ctx.effect(() => () => asr.dispose());
|
|
3537
4831
|
const warmupAsrIfCached = () => {
|
|
3538
4832
|
if (!config.enabled) return;
|
|
3539
4833
|
const st = asr.modelStatus();
|
|
@@ -3543,15 +4837,46 @@ function apply(ctx, config) {
|
|
|
3543
4837
|
};
|
|
3544
4838
|
warmupAsrIfCached();
|
|
3545
4839
|
const makeEngine = (kind) => {
|
|
3546
|
-
if (kind === "edge") return new EdgeTtsEngine(
|
|
4840
|
+
if (kind === "edge") return new EdgeTtsEngine(vset.voice, vset.rate);
|
|
4841
|
+
if (kind === "mimo") {
|
|
4842
|
+
const m = config.mimoTts;
|
|
4843
|
+
const fb = m.fallback;
|
|
4844
|
+
return new MimoTtsEngine({
|
|
4845
|
+
// 设置卡片里填的 key 优先(留空则回落到配置文件 mimoTts.apiKey);key 只在宿主侧。
|
|
4846
|
+
apiKey: (vset.mimoApiKey ?? "").trim() || m.apiKey,
|
|
4847
|
+
baseUrl: m.baseUrl,
|
|
4848
|
+
model: m.model,
|
|
4849
|
+
voice: m.voice,
|
|
4850
|
+
instructions: m.instructions,
|
|
4851
|
+
responseFormat: m.responseFormat,
|
|
4852
|
+
timeoutMs: m.timeoutMs,
|
|
4853
|
+
fallback: fb === "none" ? void 0 : () => {
|
|
4854
|
+
const engine = makeEngine(fb === "vits" ? "vits" : "kokoro");
|
|
4855
|
+
if (m.fallbackVoice) engine.updateVoice(m.fallbackVoice, vset.rate);
|
|
4856
|
+
return engine;
|
|
4857
|
+
}
|
|
4858
|
+
});
|
|
4859
|
+
}
|
|
3547
4860
|
if (kind === "openai") {
|
|
3548
4861
|
const o = config.openaiTts;
|
|
3549
4862
|
const fallbackKind = o.fallback;
|
|
4863
|
+
const resolved = resolveOnlineTts(
|
|
4864
|
+
{
|
|
4865
|
+
presetId: vset.openaiPreset ?? "",
|
|
4866
|
+
baseUrl: vset.openaiBaseUrl ?? "",
|
|
4867
|
+
model: vset.openaiModel ?? "",
|
|
4868
|
+
apiKey: vset.openaiApiKey ?? "",
|
|
4869
|
+
apiKeys: vset.openaiApiKeys ?? {},
|
|
4870
|
+
voice: ""
|
|
4871
|
+
},
|
|
4872
|
+
{ baseUrl: o.baseUrl, model: o.model, voice: o.voice, apiKey: o.apiKey, apiKeys: o.apiKeys }
|
|
4873
|
+
);
|
|
3550
4874
|
return new OpenAiTtsEngine({
|
|
3551
|
-
baseUrl:
|
|
3552
|
-
|
|
3553
|
-
|
|
3554
|
-
|
|
4875
|
+
baseUrl: resolved.baseUrl,
|
|
4876
|
+
// E1 多 key:预设专属 key 优先(换服务商不必再手改单个 key)。key 始终只在宿主侧。
|
|
4877
|
+
apiKey: resolved.apiKey || void 0,
|
|
4878
|
+
model: resolved.model,
|
|
4879
|
+
voice: resolved.voice,
|
|
3555
4880
|
instructions: o.instructions || void 0,
|
|
3556
4881
|
responseFormat: o.responseFormat,
|
|
3557
4882
|
timeoutMs: o.timeoutMs,
|
|
@@ -3578,7 +4903,7 @@ function apply(ctx, config) {
|
|
|
3578
4903
|
broadcast
|
|
3579
4904
|
});
|
|
3580
4905
|
};
|
|
3581
|
-
let engineKind = vset.ttsEngine ?? config.ttsEngine;
|
|
4906
|
+
let engineKind = asTtsEngineKind(vset.ttsEngine ?? config.ttsEngine);
|
|
3582
4907
|
let activeKokoroModel = vset.kokoroModel;
|
|
3583
4908
|
const queue = new TtsQueue({
|
|
3584
4909
|
engine: makeEngine(engineKind),
|
|
@@ -3586,6 +4911,7 @@ function apply(ctx, config) {
|
|
|
3586
4911
|
// 单句重试耗尽被跳过:显式下行(客户端提示 + 诊断),不再静默丢句。
|
|
3587
4912
|
// streak = 连续被跳过的句数:客户端据此区分偶发抖动与「云端整体不可用」(如服务端拒绝握手)。
|
|
3588
4913
|
onSkip: (sessionId, text, streak) => broadcast("tts-skip", { sessionId, text: text.slice(0, 80), streak }),
|
|
4914
|
+
onRetry: (sessionId, attempt, maxAttempts) => broadcast("tts-retry", { sessionId, attempt, maxAttempts }),
|
|
3589
4915
|
onIdle: (sessionId) => broadcast("tts-idle", { sessionId, turn: turnOfSession.get(sessionId)?.turn }),
|
|
3590
4916
|
// R15(Issue #15 Important-2 host 侧接线):onIdle 降级为「候选空闲」——「队列排空」不等于
|
|
3591
4917
|
// 「回合结束」。带工具调用的回合会在工具执行期间把队列排空一次,据此发 tts-idle 会让
|
|
@@ -3593,34 +4919,78 @@ function apply(ctx, config) {
|
|
|
3593
4919
|
// 只在 host 经 `agent/turn-stopping` 确认回合真正结束后才发(见下方钩子)。
|
|
3594
4920
|
awaitTurnEnd: true
|
|
3595
4921
|
});
|
|
4922
|
+
const ttsKeyState = () => {
|
|
4923
|
+
const st = queue.status();
|
|
4924
|
+
if (st.engine === "mimo") return { keyRequired: true, keyPresent: st.keyPresent === true };
|
|
4925
|
+
if (st.engine === "openai") return { keyRequired: presetRequiresKey(vset.openaiPreset), keyPresent: st.keyPresent === true };
|
|
4926
|
+
return { keyRequired: false, keyPresent: false };
|
|
4927
|
+
};
|
|
3596
4928
|
queue.updateVoice(vset.voice, vset.rate);
|
|
3597
4929
|
const unsubscribe = queue.subscribe((frame) => broadcast("audio", frame));
|
|
3598
4930
|
ctx.effect(() => unsubscribe);
|
|
3599
4931
|
ctx.effect(() => () => void queue.close());
|
|
3600
|
-
const
|
|
4932
|
+
const checkRemoteConfig = (kind) => {
|
|
4933
|
+
if (kind === "mimo" && !((vset.mimoApiKey ?? "").trim() || config.mimoTts?.apiKey)) {
|
|
4934
|
+
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)");
|
|
4935
|
+
} else if (kind === "openai") {
|
|
4936
|
+
const o = config.openaiTts;
|
|
4937
|
+
const r = resolveOnlineTts(
|
|
4938
|
+
{ presetId: vset.openaiPreset ?? "", baseUrl: vset.openaiBaseUrl ?? "", model: vset.openaiModel ?? "", apiKey: vset.openaiApiKey ?? "", apiKeys: vset.openaiApiKeys ?? {}, voice: vset.voice },
|
|
4939
|
+
{ baseUrl: o.baseUrl, model: o.model, voice: o.voice, apiKey: o.apiKey, apiKeys: o.apiKeys }
|
|
4940
|
+
);
|
|
4941
|
+
if (!r.baseUrl || !r.model) {
|
|
4942
|
+
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");
|
|
4943
|
+
} else if (!r.voice) {
|
|
4944
|
+
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)");
|
|
4945
|
+
}
|
|
4946
|
+
}
|
|
4947
|
+
};
|
|
4948
|
+
const applyVset = (incoming) => {
|
|
3601
4949
|
const prev = vset;
|
|
4950
|
+
let next;
|
|
4951
|
+
try {
|
|
4952
|
+
next = resolveSettings(incoming);
|
|
4953
|
+
} catch (e) {
|
|
4954
|
+
console.warn(`[dsh-voice-mode] settings update rejected by schema; keeping previous values: ${redactSecrets(e)}`);
|
|
4955
|
+
return;
|
|
4956
|
+
}
|
|
3602
4957
|
vset = next;
|
|
3603
4958
|
broadcast("display", displayOf(next));
|
|
3604
|
-
|
|
4959
|
+
const reason = engineRebuildReason(prev, next, engineKind, activeKokoroModel);
|
|
4960
|
+
if (reason === "engine-switch") {
|
|
3605
4961
|
engineKind = next.ttsEngine;
|
|
4962
|
+
if (engineKind === "kokoro") activeKokoroModel = next.kokoroModel;
|
|
4963
|
+
checkRemoteConfig(engineKind);
|
|
3606
4964
|
queue.setEngine(makeEngine(engineKind));
|
|
3607
|
-
} else if (
|
|
4965
|
+
} else if (reason === "mimo-key") {
|
|
4966
|
+
checkRemoteConfig("mimo");
|
|
4967
|
+
queue.setEngine(makeEngine("mimo"));
|
|
4968
|
+
} else if (reason === "kokoro-model") {
|
|
3608
4969
|
activeKokoroModel = next.kokoroModel;
|
|
3609
4970
|
queue.setEngine(makeEngine("kokoro"));
|
|
4971
|
+
} else if (reason === "openai-config") {
|
|
4972
|
+
checkRemoteConfig("openai");
|
|
4973
|
+
queue.setEngine(makeEngine("openai"));
|
|
3610
4974
|
}
|
|
3611
4975
|
queue.updateVoice(next.voice, next.rate);
|
|
3612
4976
|
if (next.senseITN !== prev.senseITN || next.senseVoice !== prev.senseVoice) {
|
|
3613
4977
|
asr.markStale();
|
|
3614
4978
|
}
|
|
4979
|
+
if (JSON.stringify(next.asrReplacements ?? []) !== JSON.stringify(prev.asrReplacements ?? [])) {
|
|
4980
|
+
rebuildReplacer(next.asrReplacements ?? []);
|
|
4981
|
+
}
|
|
3615
4982
|
};
|
|
3616
4983
|
if (settingsScopeRef) {
|
|
3617
4984
|
const scopeRef = settingsScopeRef;
|
|
3618
4985
|
ctx.effect(() => scopeRef.watch(applyVset));
|
|
3619
4986
|
}
|
|
3620
4987
|
let settingsWriteChain = Promise.resolve();
|
|
3621
|
-
const persistSettings = (patch) => {
|
|
4988
|
+
const persistSettings = (patch, clearAllPresetKeys = false) => {
|
|
3622
4989
|
const run = async () => {
|
|
3623
4990
|
const candidate = { ...overrides, ...patch };
|
|
4991
|
+
if ("openaiApiKeys" in patch || clearAllPresetKeys) {
|
|
4992
|
+
candidate.openaiApiKeys = mergePresetApiKeys(overrides.openaiApiKeys, patch.openaiApiKeys, clearAllPresetKeys);
|
|
4993
|
+
}
|
|
3624
4994
|
const next = resolveSettings(candidate);
|
|
3625
4995
|
writeOverrides(settingsFile, candidate);
|
|
3626
4996
|
overrides = candidate;
|
|
@@ -3635,6 +5005,7 @@ function apply(ctx, config) {
|
|
|
3635
5005
|
const currentRate = () => vset.rate;
|
|
3636
5006
|
const currentInterrupt = () => vset.interruptLevel;
|
|
3637
5007
|
const currentEngine = () => engineKind;
|
|
5008
|
+
checkRemoteConfig(engineKind);
|
|
3638
5009
|
const yieldActiveSession = (expectedSid) => {
|
|
3639
5010
|
ownerYieldTimer = null;
|
|
3640
5011
|
const sid = activeVoiceSession;
|
|
@@ -3718,16 +5089,30 @@ function apply(ctx, config) {
|
|
|
3718
5089
|
}
|
|
3719
5090
|
})
|
|
3720
5091
|
);
|
|
5092
|
+
ctx.effect(
|
|
5093
|
+
() => ctx.webServer.register({
|
|
5094
|
+
kind: "exact",
|
|
5095
|
+
path: `${base}/presets`,
|
|
5096
|
+
handler: (req, res) => {
|
|
5097
|
+
if (denyNonLoopback(req, res)) return;
|
|
5098
|
+
respondJson2(res, 200, { presets: OPENAI_PRESETS });
|
|
5099
|
+
}
|
|
5100
|
+
})
|
|
5101
|
+
);
|
|
3721
5102
|
ctx.effect(
|
|
3722
5103
|
() => ctx.webServer.register({
|
|
3723
5104
|
kind: "exact",
|
|
3724
5105
|
path: `${base}/config`,
|
|
3725
5106
|
handler: (req, res) => {
|
|
3726
5107
|
if (denyNonLoopback(req, res)) return;
|
|
5108
|
+
const keyState = ttsKeyState();
|
|
3727
5109
|
respondJson2(res, 200, {
|
|
3728
5110
|
basePath: base,
|
|
3729
5111
|
rate: currentRate(),
|
|
3730
5112
|
voice: currentVoice(),
|
|
5113
|
+
// P1-2:入口探针还要判「预设音色」。ttsEngine 本就在下方载荷里;
|
|
5114
|
+
// 此前探针只能读设置卡快照——0.1.7+ 只有首个订阅者才触发加载,未开过设置的用户
|
|
5115
|
+
// 快照恒 loading,探针从未生效(T5 审计 B①)。这里补 openaiPreset 即可闭环。
|
|
3731
5116
|
senseVoice: vset.senseVoice,
|
|
3732
5117
|
interruptLevel: currentInterrupt(),
|
|
3733
5118
|
silenceMs: vset.silenceMs,
|
|
@@ -3737,6 +5122,9 @@ function apply(ctx, config) {
|
|
|
3737
5122
|
autoResume: vset.autoResume,
|
|
3738
5123
|
mode: vset.mode,
|
|
3739
5124
|
readAloud: vset.readAloud,
|
|
5125
|
+
// 2026-11-20 UX:进模式前即可判断「云朗读缺 Key」,客户端据此常驻提示。
|
|
5126
|
+
ttsNeedsKey: keyState.keyRequired,
|
|
5127
|
+
ttsKeyPresent: keyState.keyPresent,
|
|
3740
5128
|
showCaptions: vset.showCaptions,
|
|
3741
5129
|
showStatusBar: vset.showStatusBar,
|
|
3742
5130
|
bargeInMode: vset.bargeInMode,
|
|
@@ -3754,6 +5142,7 @@ function apply(ctx, config) {
|
|
|
3754
5142
|
senseITN: vset.senseITN,
|
|
3755
5143
|
cacheDir: config.cacheDir,
|
|
3756
5144
|
ttsEngine: currentEngine(),
|
|
5145
|
+
openaiPreset: vset.openaiPreset,
|
|
3757
5146
|
audioMime: queue.mime,
|
|
3758
5147
|
allowLan: config.allowLan
|
|
3759
5148
|
});
|
|
@@ -3791,7 +5180,7 @@ function apply(ctx, config) {
|
|
|
3791
5180
|
respondJson2(res, 400, { code: "bad_request", error: "voice too long" });
|
|
3792
5181
|
return;
|
|
3793
5182
|
}
|
|
3794
|
-
if (!voice) {
|
|
5183
|
+
if (!voice && currentEngine() !== "openai") {
|
|
3795
5184
|
respondJson2(res, 400, { code: "bad_request", error: "voice required" });
|
|
3796
5185
|
return;
|
|
3797
5186
|
}
|
|
@@ -3801,8 +5190,11 @@ function apply(ctx, config) {
|
|
|
3801
5190
|
}
|
|
3802
5191
|
const sample = previewSample(currentEngine(), voice);
|
|
3803
5192
|
let buf;
|
|
5193
|
+
let mime = queue.mime;
|
|
3804
5194
|
try {
|
|
3805
|
-
|
|
5195
|
+
const r = await queue.synthesizeWithMime(sample, { voice, rate });
|
|
5196
|
+
buf = r.buf;
|
|
5197
|
+
mime = r.mime;
|
|
3806
5198
|
} catch (e) {
|
|
3807
5199
|
const errMsg = e instanceof Error ? e.message : String(e);
|
|
3808
5200
|
const category = classifyPreviewError(errMsg);
|
|
@@ -3810,12 +5202,12 @@ function apply(ctx, config) {
|
|
|
3810
5202
|
const engineStatus = queue.status();
|
|
3811
5203
|
const sampleLen = sample.length;
|
|
3812
5204
|
console.warn(
|
|
3813
|
-
`[dsh-voice-mode] preview synthesis failed: category=${category} engine=${engineName} engineReady=${engineStatus.ready} sampleLen=${sampleLen} attempt=1 voice=${voice} err=${errMsg}`
|
|
5205
|
+
`[dsh-voice-mode] preview synthesis failed: category=${category} engine=${engineName} engineReady=${engineStatus.ready} sampleLen=${sampleLen} attempt=1 voice=${redactSecrets(voice)} err=${redactSecrets(errMsg)}`
|
|
3814
5206
|
);
|
|
3815
5207
|
respondJson2(res, 502, { code: PREVIEW_ERROR_CODES[category], error: `preview failed (${category})` });
|
|
3816
5208
|
return;
|
|
3817
5209
|
}
|
|
3818
|
-
res.writeHead(200, { "content-type":
|
|
5210
|
+
res.writeHead(200, { "content-type": mime, "cache-control": "no-store" });
|
|
3819
5211
|
res.end(buf);
|
|
3820
5212
|
});
|
|
3821
5213
|
}
|
|
@@ -3826,6 +5218,10 @@ function apply(ctx, config) {
|
|
|
3826
5218
|
kind: "exact",
|
|
3827
5219
|
path: `${base}/correct`,
|
|
3828
5220
|
handler: (req, res) => {
|
|
5221
|
+
if (req.method !== "POST" && req.method !== "GET") {
|
|
5222
|
+
respondJson2(res, 405, { code: "method_not_allowed", error: "method not allowed" });
|
|
5223
|
+
return;
|
|
5224
|
+
}
|
|
3829
5225
|
if (denyNonLoopback(req, res)) return;
|
|
3830
5226
|
if (denyCrossOrigin(req, res)) return;
|
|
3831
5227
|
collectBody(req, res, MAX_JSON_BODY, (body) => {
|
|
@@ -3862,6 +5258,10 @@ function apply(ctx, config) {
|
|
|
3862
5258
|
kind: "exact",
|
|
3863
5259
|
path: `${base}/toggle`,
|
|
3864
5260
|
handler: (req, res) => {
|
|
5261
|
+
if (req.method !== "POST" && req.method !== "GET") {
|
|
5262
|
+
respondJson2(res, 405, { code: "method_not_allowed", error: "method not allowed" });
|
|
5263
|
+
return;
|
|
5264
|
+
}
|
|
3865
5265
|
if (denyNonLoopback(req, res)) return;
|
|
3866
5266
|
if (denyCrossOrigin(req, res)) return;
|
|
3867
5267
|
collectBody(req, res, MAX_JSON_BODY, async (body) => {
|
|
@@ -3877,7 +5277,7 @@ function apply(ctx, config) {
|
|
|
3877
5277
|
tabId = typeof parsed.tabId === "string" && parsed.tabId.length <= 64 ? parsed.tabId : void 0;
|
|
3878
5278
|
} catch {
|
|
3879
5279
|
}
|
|
3880
|
-
if (!sessionId) {
|
|
5280
|
+
if (typeof sessionId !== "string" || !sessionId || sessionId.length > 128) {
|
|
3881
5281
|
respondJson2(res, 400, { code: "bad_request", error: "sessionId required" });
|
|
3882
5282
|
return;
|
|
3883
5283
|
}
|
|
@@ -3902,7 +5302,15 @@ function apply(ctx, config) {
|
|
|
3902
5302
|
respondJson2(res, 403, { code: "unknown_session", error: "unknown session" });
|
|
3903
5303
|
return;
|
|
3904
5304
|
}
|
|
5305
|
+
const myToggleGen = ++toggleGen;
|
|
5306
|
+
enteringToggles.add(sessionId);
|
|
3905
5307
|
await asr.warmupSense();
|
|
5308
|
+
const enterStale = pluginDisposed || myToggleGen !== toggleGen;
|
|
5309
|
+
enteringToggles.delete(sessionId);
|
|
5310
|
+
if (enterStale) {
|
|
5311
|
+
respondJson2(res, 200, { active: activeVoiceSession, stale: true });
|
|
5312
|
+
return;
|
|
5313
|
+
}
|
|
3906
5314
|
asr.reset(sessionId);
|
|
3907
5315
|
queue.cancel(sessionId);
|
|
3908
5316
|
const previous = activeVoiceSession;
|
|
@@ -3920,6 +5328,7 @@ function apply(ctx, config) {
|
|
|
3920
5328
|
}
|
|
3921
5329
|
broadcast("mode", { active: activeVoiceSession, ownerTabId: activeTabId });
|
|
3922
5330
|
} else {
|
|
5331
|
+
if (activeVoiceSession === sessionId || enteringToggles.has(sessionId)) toggleGen++;
|
|
3923
5332
|
if (activeVoiceSession === sessionId) {
|
|
3924
5333
|
activeVoiceSession = null;
|
|
3925
5334
|
activeTabId = null;
|
|
@@ -3944,7 +5353,12 @@ function apply(ctx, config) {
|
|
|
3944
5353
|
path: `${base}/models/status`,
|
|
3945
5354
|
handler: (req, res) => {
|
|
3946
5355
|
if (denyNonLoopback(req, res)) return;
|
|
3947
|
-
respondJson2(res, 200, {
|
|
5356
|
+
respondJson2(res, 200, {
|
|
5357
|
+
...asr.modelStatus(),
|
|
5358
|
+
tts: { ...queue.status(), ...ttsKeyState() },
|
|
5359
|
+
// P1-3:词表规则数与命中计数(本次生效以来;设置变更重建即清零)。
|
|
5360
|
+
replacements: { rules: replacementRuleCount, hits: [...replacementHits] }
|
|
5361
|
+
});
|
|
3948
5362
|
}
|
|
3949
5363
|
})
|
|
3950
5364
|
);
|
|
@@ -3960,6 +5374,14 @@ function apply(ctx, config) {
|
|
|
3960
5374
|
return;
|
|
3961
5375
|
}
|
|
3962
5376
|
if (denyCrossOrigin(req, res)) return;
|
|
5377
|
+
if (!isLoopbackRequest(req)) {
|
|
5378
|
+
respondJson2(res, 403, { code: "forbidden", error: "model cache writes are loopback-only" });
|
|
5379
|
+
return;
|
|
5380
|
+
}
|
|
5381
|
+
if (!limiter.hit(`models-retry:${clientKey(req)}`, 6, 6e4)) {
|
|
5382
|
+
respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
|
|
5383
|
+
return;
|
|
5384
|
+
}
|
|
3963
5385
|
if (!config.enabled) {
|
|
3964
5386
|
respondJson2(res, 403, { code: "voice_disabled", error: "voice mode disabled" });
|
|
3965
5387
|
return;
|
|
@@ -3982,7 +5404,7 @@ function apply(ctx, config) {
|
|
|
3982
5404
|
void asr.retryModel(kind).then((done) => {
|
|
3983
5405
|
respondJson2(res, 200, { ok: done, kind });
|
|
3984
5406
|
}).catch((e) => {
|
|
3985
|
-
console.warn(`[dsh-voice-mode] model retry failed: ${
|
|
5407
|
+
console.warn(`[dsh-voice-mode] model retry failed: ${redactSecrets(e)}`);
|
|
3986
5408
|
respondJson2(res, 500, { code: "internal", error: "model retry failed" });
|
|
3987
5409
|
});
|
|
3988
5410
|
});
|
|
@@ -3995,7 +5417,20 @@ function apply(ctx, config) {
|
|
|
3995
5417
|
path: `${base}/models/clean`,
|
|
3996
5418
|
handler: (req, res) => {
|
|
3997
5419
|
if (denyNonLoopback(req, res)) return;
|
|
5420
|
+
if (req.method !== "POST") {
|
|
5421
|
+
res.setHeader("allow", "POST");
|
|
5422
|
+
respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
|
|
5423
|
+
return;
|
|
5424
|
+
}
|
|
3998
5425
|
if (denyCrossOrigin(req, res)) return;
|
|
5426
|
+
if (!isLoopbackRequest(req)) {
|
|
5427
|
+
respondJson2(res, 403, { code: "forbidden", error: "model cache writes are loopback-only" });
|
|
5428
|
+
return;
|
|
5429
|
+
}
|
|
5430
|
+
if (!limiter.hit(`models-clean:${clientKey(req)}`, 6, 6e4)) {
|
|
5431
|
+
respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
|
|
5432
|
+
return;
|
|
5433
|
+
}
|
|
3999
5434
|
if (!config.enabled) {
|
|
4000
5435
|
respondJson2(res, 403, { code: "voice_disabled", error: "voice mode disabled" });
|
|
4001
5436
|
return;
|
|
@@ -4004,7 +5439,7 @@ function apply(ctx, config) {
|
|
|
4004
5439
|
let engine = "vits";
|
|
4005
5440
|
try {
|
|
4006
5441
|
const p = JSON.parse(body || "{}");
|
|
4007
|
-
if (p.engine
|
|
5442
|
+
if (isLocalEngine(p.engine)) engine = p.engine;
|
|
4008
5443
|
else {
|
|
4009
5444
|
respondJson2(res, 400, { code: "bad_request", error: "invalid engine" });
|
|
4010
5445
|
return;
|
|
@@ -4021,7 +5456,7 @@ function apply(ctx, config) {
|
|
|
4021
5456
|
}
|
|
4022
5457
|
respondJson2(res, 200, { ok: true, engine });
|
|
4023
5458
|
}).catch((e) => {
|
|
4024
|
-
console.warn(`[dsh-voice-mode] models/
|
|
5459
|
+
console.warn(`[dsh-voice-mode] models/clean failed: ${redactSecrets(e)}`);
|
|
4025
5460
|
respondJson2(res, 500, { code: "internal", error: "internal error" });
|
|
4026
5461
|
});
|
|
4027
5462
|
});
|
|
@@ -4034,7 +5469,20 @@ function apply(ctx, config) {
|
|
|
4034
5469
|
path: `${base}/models/download`,
|
|
4035
5470
|
handler: (req, res) => {
|
|
4036
5471
|
if (denyNonLoopback(req, res)) return;
|
|
5472
|
+
if (req.method !== "POST") {
|
|
5473
|
+
res.setHeader("allow", "POST");
|
|
5474
|
+
respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
|
|
5475
|
+
return;
|
|
5476
|
+
}
|
|
4037
5477
|
if (denyCrossOrigin(req, res)) return;
|
|
5478
|
+
if (!isLoopbackRequest(req)) {
|
|
5479
|
+
respondJson2(res, 403, { code: "forbidden", error: "model cache writes are loopback-only" });
|
|
5480
|
+
return;
|
|
5481
|
+
}
|
|
5482
|
+
if (!limiter.hit(`models-download:${clientKey(req)}`, 6, 6e4)) {
|
|
5483
|
+
respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
|
|
5484
|
+
return;
|
|
5485
|
+
}
|
|
4038
5486
|
if (!config.enabled) {
|
|
4039
5487
|
respondJson2(res, 403, { code: "voice_disabled", error: "voice mode disabled" });
|
|
4040
5488
|
return;
|
|
@@ -4043,7 +5491,7 @@ function apply(ctx, config) {
|
|
|
4043
5491
|
let engine = "vits";
|
|
4044
5492
|
try {
|
|
4045
5493
|
const p = JSON.parse(body || "{}");
|
|
4046
|
-
if (p.engine
|
|
5494
|
+
if (isLocalEngine(p.engine)) engine = p.engine;
|
|
4047
5495
|
else {
|
|
4048
5496
|
respondJson2(res, 400, { code: "bad_request", error: "invalid engine" });
|
|
4049
5497
|
return;
|
|
@@ -4057,7 +5505,7 @@ function apply(ctx, config) {
|
|
|
4057
5505
|
return;
|
|
4058
5506
|
}
|
|
4059
5507
|
void queue.prepare().then(() => respondJson2(res, 200, { ok: true, engine })).catch((e) => {
|
|
4060
|
-
console.warn(`[dsh-voice-mode] model download failed: ${
|
|
5508
|
+
console.warn(`[dsh-voice-mode] model download failed: ${redactSecrets(e)}`);
|
|
4061
5509
|
respondJson2(res, 502, { code: "model_download_failed", error: "model download failed" });
|
|
4062
5510
|
});
|
|
4063
5511
|
});
|
|
@@ -4069,13 +5517,21 @@ function apply(ctx, config) {
|
|
|
4069
5517
|
kind: "exact",
|
|
4070
5518
|
path: `${base}/voices`,
|
|
4071
5519
|
handler: async (req, res) => {
|
|
5520
|
+
if (req.method !== "POST" && req.method !== "GET") {
|
|
5521
|
+
respondJson2(res, 405, { code: "method_not_allowed", error: "method not allowed" });
|
|
5522
|
+
return;
|
|
5523
|
+
}
|
|
4072
5524
|
if (denyNonLoopback(req, res)) return;
|
|
4073
5525
|
if (denyCrossOrigin(req, res)) return;
|
|
5526
|
+
if (!limiter.hit(`voices:${clientKey(req)}`, 10, 6e4)) {
|
|
5527
|
+
respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
|
|
5528
|
+
return;
|
|
5529
|
+
}
|
|
4074
5530
|
try {
|
|
4075
5531
|
const voices = await listEdgeVoices();
|
|
4076
5532
|
respondJson2(res, 200, { voices });
|
|
4077
5533
|
} catch (e) {
|
|
4078
|
-
console.warn(`[dsh-voice-mode] listing Edge voices failed: ${
|
|
5534
|
+
console.warn(`[dsh-voice-mode] listing Edge voices failed: ${redactSecrets(e)}`);
|
|
4079
5535
|
respondJson2(res, 502, { code: "internal", error: "voice list unavailable" });
|
|
4080
5536
|
}
|
|
4081
5537
|
}
|
|
@@ -4106,7 +5562,9 @@ function apply(ctx, config) {
|
|
|
4106
5562
|
if (sid && sid === activeVoiceSession) {
|
|
4107
5563
|
try {
|
|
4108
5564
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
4109
|
-
|
|
5565
|
+
if (url.searchParams.get("vadOnly") !== "1" && url.searchParams.get("reset") !== "1") {
|
|
5566
|
+
setTurn(sid, url.searchParams.get("final") === "1" ? "finalizing" : "listening");
|
|
5567
|
+
}
|
|
4110
5568
|
} catch {
|
|
4111
5569
|
}
|
|
4112
5570
|
}
|
|
@@ -4119,6 +5577,10 @@ function apply(ctx, config) {
|
|
|
4119
5577
|
kind: "exact",
|
|
4120
5578
|
path: `${base}/cancel`,
|
|
4121
5579
|
handler: (req, res) => {
|
|
5580
|
+
if (req.method !== "POST" && req.method !== "GET") {
|
|
5581
|
+
respondJson2(res, 405, { code: "method_not_allowed", error: "method not allowed" });
|
|
5582
|
+
return;
|
|
5583
|
+
}
|
|
4122
5584
|
if (denyNonLoopback(req, res)) return;
|
|
4123
5585
|
if (denyCrossOrigin(req, res)) return;
|
|
4124
5586
|
collectBody(req, res, MAX_JSON_BODY, (body) => {
|
|
@@ -4154,7 +5616,8 @@ function apply(ctx, config) {
|
|
|
4154
5616
|
handler: (req, res) => {
|
|
4155
5617
|
if (denyNonLoopback(req, res)) return;
|
|
4156
5618
|
if (req.method === "GET") {
|
|
4157
|
-
|
|
5619
|
+
const view = buildSettingsGetView(vset, config);
|
|
5620
|
+
respondJson2(res, 200, { managedBy: settingsScopeRef ? "dsh" : "plugin", ...view });
|
|
4158
5621
|
return;
|
|
4159
5622
|
}
|
|
4160
5623
|
if (req.method !== "POST") {
|
|
@@ -4167,6 +5630,14 @@ function apply(ctx, config) {
|
|
|
4167
5630
|
respondJson2(res, 409, { code: "settings_managed", error: "settings are managed by dsh on this host" });
|
|
4168
5631
|
return;
|
|
4169
5632
|
}
|
|
5633
|
+
if (!isLoopbackRequest(req)) {
|
|
5634
|
+
respondJson2(res, 403, { code: "forbidden", error: "settings writes are loopback-only" });
|
|
5635
|
+
return;
|
|
5636
|
+
}
|
|
5637
|
+
if (!limiter.hit(`settings:${clientKey(req)}`, 30, 6e4)) {
|
|
5638
|
+
respondJson2(res, 429, { code: "rate_limited", error: "too many settings updates, retry in a minute" });
|
|
5639
|
+
return;
|
|
5640
|
+
}
|
|
4170
5641
|
collectBody(req, res, MAX_JSON_BODY, async (body) => {
|
|
4171
5642
|
let patch;
|
|
4172
5643
|
try {
|
|
@@ -4179,17 +5650,28 @@ function apply(ctx, config) {
|
|
|
4179
5650
|
respondJson2(res, 400, { code: "bad_request", error: "body must be a JSON object" });
|
|
4180
5651
|
return;
|
|
4181
5652
|
}
|
|
4182
|
-
const
|
|
5653
|
+
const rawClear = patch.clearSecrets;
|
|
5654
|
+
let cleared;
|
|
5655
|
+
try {
|
|
5656
|
+
cleared = applyClearSecrets(patch, rawClear);
|
|
5657
|
+
} catch (e) {
|
|
5658
|
+
respondJson2(res, 400, { code: "bad_request", error: String(e.message).slice(0, 120) });
|
|
5659
|
+
return;
|
|
5660
|
+
}
|
|
5661
|
+
const unknown = unknownKeys(cleared, SETTING_KEYS);
|
|
4183
5662
|
if (unknown.length > 0) {
|
|
4184
5663
|
respondJson2(res, 400, { code: "bad_request", error: `unknown settings: ${unknown.slice(0, 5).join(", ")}` });
|
|
4185
5664
|
return;
|
|
4186
5665
|
}
|
|
5666
|
+
const rest = { ...pickKnownKeys(cleared, SETTING_KEYS) };
|
|
5667
|
+
const clearAllMap = Array.isArray(rawClear) && rawClear.includes("openaiApiKeys");
|
|
4187
5668
|
try {
|
|
4188
|
-
const next = await persistSettings(
|
|
4189
|
-
|
|
5669
|
+
const next = await persistSettings(rest, clearAllMap);
|
|
5670
|
+
const out = { ...next, openaiApiKey: "", mimoApiKey: "", openaiApiKeys: {} };
|
|
5671
|
+
respondJson2(res, 200, { ok: true, managedBy: "plugin", value: out });
|
|
4190
5672
|
} catch (e) {
|
|
4191
5673
|
const isValidation = e instanceof Error && e.name === "ValidationError";
|
|
4192
|
-
console.warn(`[dsh-voice-mode] settings update failed: ${
|
|
5674
|
+
console.warn(`[dsh-voice-mode] settings update failed: ${redactSecrets(e)}`);
|
|
4193
5675
|
respondJson2(res, isValidation ? 400 : 500, {
|
|
4194
5676
|
code: isValidation ? "bad_request" : "internal",
|
|
4195
5677
|
error: isValidation ? `invalid value: ${e.message.slice(0, 200)}` : "settings update failed"
|
|
@@ -4205,7 +5687,20 @@ function apply(ctx, config) {
|
|
|
4205
5687
|
path: `${base}/mode`,
|
|
4206
5688
|
handler: (req, res) => {
|
|
4207
5689
|
if (denyNonLoopback(req, res)) return;
|
|
5690
|
+
if (req.method !== "POST") {
|
|
5691
|
+
res.setHeader("allow", "POST");
|
|
5692
|
+
respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
|
|
5693
|
+
return;
|
|
5694
|
+
}
|
|
4208
5695
|
if (denyCrossOrigin(req, res)) return;
|
|
5696
|
+
if (!isLoopbackRequest(req)) {
|
|
5697
|
+
respondJson2(res, 403, { code: "forbidden", error: "settings writes are loopback-only" });
|
|
5698
|
+
return;
|
|
5699
|
+
}
|
|
5700
|
+
if (!limiter.hit(`mode:${clientKey(req)}`, 30, 6e4)) {
|
|
5701
|
+
respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
|
|
5702
|
+
return;
|
|
5703
|
+
}
|
|
4209
5704
|
collectBody(req, res, MAX_JSON_BODY, (body) => {
|
|
4210
5705
|
let mode;
|
|
4211
5706
|
try {
|
|
@@ -4221,7 +5716,7 @@ function apply(ctx, config) {
|
|
|
4221
5716
|
void persistMode.then(() => {
|
|
4222
5717
|
respondJson2(res, 200, { ok: true, mode });
|
|
4223
5718
|
}).catch((e) => {
|
|
4224
|
-
console.warn(`[dsh-voice-mode] mode update failed: ${
|
|
5719
|
+
console.warn(`[dsh-voice-mode] mode update failed: ${redactSecrets(e)}`);
|
|
4225
5720
|
respondJson2(res, 500, { code: "internal", error: "mode update failed" });
|
|
4226
5721
|
});
|
|
4227
5722
|
});
|
|
@@ -4260,7 +5755,7 @@ function apply(ctx, config) {
|
|
|
4260
5755
|
focusedSessionId = null;
|
|
4261
5756
|
focusedTabId = null;
|
|
4262
5757
|
}
|
|
4263
|
-
if (prevFocus !== null && prevFocus !== focusedSessionId) stopFocusReading(prevFocus);
|
|
5758
|
+
if (prevFocus !== null && prevFocus !== focusedSessionId) stopFocusReading(prevFocus, tabId);
|
|
4264
5759
|
if (prevFocus !== null && prevFocus !== focusedSessionId) reclaimFocusState(prevFocus);
|
|
4265
5760
|
broadcast("focus", { sessionId: focusedSessionId, tabId: focusedTabId });
|
|
4266
5761
|
respondJson2(res, 200, { ok: true, sessionId: focusedSessionId, tabId: focusedTabId });
|
|
@@ -4275,6 +5770,11 @@ function apply(ctx, config) {
|
|
|
4275
5770
|
handler: (req, res) => {
|
|
4276
5771
|
if (denyNonLoopback(req, res)) return;
|
|
4277
5772
|
if (denyCrossOrigin(req, res)) return;
|
|
5773
|
+
if (req.method && req.method !== "GET") {
|
|
5774
|
+
res.setHeader("allow", "GET");
|
|
5775
|
+
respondJson2(res, 405, { code: "method_not_allowed", error: "GET required" });
|
|
5776
|
+
return;
|
|
5777
|
+
}
|
|
4278
5778
|
let tabId = null;
|
|
4279
5779
|
try {
|
|
4280
5780
|
const u = new URL(req.url ?? "/", "http://localhost");
|
|
@@ -4313,7 +5813,13 @@ data: ${JSON.stringify(payload)}
|
|
|
4313
5813
|
res.destroy();
|
|
4314
5814
|
}
|
|
4315
5815
|
};
|
|
5816
|
+
let heartbeat = null;
|
|
4316
5817
|
const end = () => {
|
|
5818
|
+
if (heartbeat) {
|
|
5819
|
+
clearInterval(heartbeat);
|
|
5820
|
+
heartbeat = null;
|
|
5821
|
+
}
|
|
5822
|
+
sseClients.delete(client);
|
|
4317
5823
|
try {
|
|
4318
5824
|
res.end();
|
|
4319
5825
|
} catch {
|
|
@@ -4329,7 +5835,7 @@ data: ${JSON.stringify(payload)}
|
|
|
4329
5835
|
send("mode", { active: activeVoiceSession, ownerTabId: activeTabId });
|
|
4330
5836
|
send("focus", { sessionId: focusedSessionId, tabId: focusedTabId });
|
|
4331
5837
|
send("display", displayOf(vset));
|
|
4332
|
-
|
|
5838
|
+
heartbeat = setInterval(() => {
|
|
4333
5839
|
try {
|
|
4334
5840
|
res.write(": hb\n");
|
|
4335
5841
|
} catch {
|
|
@@ -4340,7 +5846,10 @@ data: ${JSON.stringify(payload)}
|
|
|
4340
5846
|
const cleanup = () => {
|
|
4341
5847
|
if (cleaned) return;
|
|
4342
5848
|
cleaned = true;
|
|
4343
|
-
|
|
5849
|
+
if (heartbeat) {
|
|
5850
|
+
clearInterval(heartbeat);
|
|
5851
|
+
heartbeat = null;
|
|
5852
|
+
}
|
|
4344
5853
|
sseClients.delete(client);
|
|
4345
5854
|
if (tabId !== null && latestConnByTab.get(tabId) === client) {
|
|
4346
5855
|
latestConnByTab.delete(tabId);
|
|
@@ -4438,6 +5947,7 @@ async function* tapActiveStream(sessionId, inner, queue, broadcast, onTurn, spea
|
|
|
4438
5947
|
}
|
|
4439
5948
|
export {
|
|
4440
5949
|
Config,
|
|
5950
|
+
MimoTtsConfig,
|
|
4441
5951
|
OpenAiTtsConfig,
|
|
4442
5952
|
VoiceSettingsSchema,
|
|
4443
5953
|
apply,
|