dsh-voice-mode 0.7.28 → 0.7.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -141,7 +141,7 @@ import sherpa_onnx from "sherpa-onnx";
141
141
  // src/models.ts
142
142
  import { createHash } from "node:crypto";
143
143
  import { createWriteStream } from "node:fs";
144
- import { mkdir, rename, stat, unlink } from "node:fs/promises";
144
+ import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
145
145
  import { join } from "node:path";
146
146
  var HOST_PRIMARY = "https://huggingface.co";
147
147
  var HOST_FALLBACK = "https://hf-mirror.com";
@@ -172,6 +172,8 @@ function redirectHostAllowed(finalUrl, allowCustomHost) {
172
172
  return false;
173
173
  }
174
174
  }
175
+ var verifiedCache = /* @__PURE__ */ new Map();
176
+ var cacheKey = (st) => `${st.size}:${st.ino}:${st.ctimeMs}`;
175
177
  async function sha256OfFile(path) {
176
178
  const hash = createHash("sha256");
177
179
  const { createReadStream } = await import("node:fs");
@@ -184,8 +186,17 @@ async function sha256OfFile(path) {
184
186
  return hash.digest("hex");
185
187
  }
186
188
  var MODEL_FETCH_HEADERS_TIMEOUT_MS = 6e4;
187
- async function fetchWithHeadersTimeout(url, init) {
188
- const ac = new AbortController();
189
+ var MODEL_BODY_IDLE_TIMEOUT_MS = 12e4;
190
+ function makeIdleWatch(ac, ms) {
191
+ let t;
192
+ const stop = () => clearTimeout(t);
193
+ const kick = () => {
194
+ stop();
195
+ t = setTimeout(() => ac.abort(new Error("model download idle timeout")), ms);
196
+ };
197
+ return { kick, stop };
198
+ }
199
+ async function fetchWithHeadersTimeout(url, init, ac = new AbortController()) {
189
200
  const timer = setTimeout(() => ac.abort(new Error("model fetch headers timeout")), MODEL_FETCH_HEADERS_TIMEOUT_MS);
190
201
  try {
191
202
  return await fetch(url, { ...init, signal: ac.signal });
@@ -197,9 +208,14 @@ async function ensureModelFile(opts) {
197
208
  const { repoDir, spec, primaryHost, broadcast } = opts;
198
209
  const localPath = join(repoDir, spec.file);
199
210
  const partPath = `${localPath}.part`;
200
- if ((await stat(localPath).catch(() => null))?.isFile()) {
211
+ const existing = await stat(localPath).catch(() => null);
212
+ if (existing?.isFile()) {
213
+ if (verifiedCache.get(localPath) === `${cacheKey(existing)}:${spec.sha256}`) return true;
201
214
  const ok = await sha256OfFile(localPath).catch(() => "") === spec.sha256;
202
- if (ok) return true;
215
+ if (ok) {
216
+ verifiedCache.set(localPath, `${cacheKey(existing)}:${spec.sha256}`);
217
+ return true;
218
+ }
203
219
  await unlink(localPath).catch(() => void 0);
204
220
  }
205
221
  await mkdir(join(repoDir, spec.file.includes("/") ? spec.file.slice(0, spec.file.lastIndexOf("/")) : ""), {
@@ -208,6 +224,7 @@ async function ensureModelFile(opts) {
208
224
  const hosts = [...new Set([primaryHost, HOST_PRIMARY, HOST_FALLBACK].filter(Boolean))];
209
225
  let lastError = "no upstream reachable";
210
226
  for (const host of hosts) {
227
+ if (opts.signal?.aborted) break;
211
228
  try {
212
229
  const done = await downloadVerified({ ...opts, host, partPath, localPath });
213
230
  if (done) return true;
@@ -215,78 +232,125 @@ async function ensureModelFile(opts) {
215
232
  lastError = String(e);
216
233
  }
217
234
  }
235
+ if (opts.signal?.aborted) return false;
218
236
  if (lastError) console.warn(`[dsh-voice-mode] model download failed: ${spec.file}: ${lastError}`);
219
237
  broadcast("asr-error", { file: spec.file, reason: "checksum_or_download_failed" });
220
238
  return false;
221
239
  }
222
240
  async function downloadVerified(opts) {
223
241
  const { repo, spec, host, allowCustomHost, partPath, localPath, broadcast } = opts;
224
- const url = `${host}/${repo}/resolve/main/${spec.file}`;
225
- const partSt = await stat(partPath).catch(() => null);
226
- const resumeFrom = partSt?.isFile() ? partSt.size : 0;
227
- const headers = { "user-agent": "dsh-voice-mode" };
228
- if (resumeFrom > 0) headers.range = `bytes=${resumeFrom}-`;
229
- const res = await fetchWithHeadersTimeout(url, { headers, redirect: "follow" });
230
- if (!redirectHostAllowed(res.url, allowCustomHost)) return false;
231
- if (res.status === 416) {
232
- if (await sha256OfFile(partPath).catch(() => "") === spec.sha256) {
233
- await rename(partPath, localPath);
234
- return true;
235
- }
236
- await unlink(partPath).catch(() => void 0);
237
- return false;
242
+ const ac = new AbortController();
243
+ const onAbort = () => ac.abort(opts.signal?.reason);
244
+ if (opts.signal?.aborted) onAbort();
245
+ else opts.signal?.addEventListener("abort", onAbort, { once: true });
246
+ const idle = makeIdleWatch(ac, opts.idleTimeoutMs ?? MODEL_BODY_IDLE_TIMEOUT_MS);
247
+ try {
248
+ return await downloadBody();
249
+ } finally {
250
+ idle.stop();
251
+ opts.signal?.removeEventListener("abort", onAbort);
238
252
  }
239
- if (res.status !== 200 && res.status !== 206) return false;
240
- const resume = res.status === 206 ? resumeFrom : 0;
241
- const total = Number(res.headers.get("content-length") ?? 0) + resume;
242
- const src = res.body;
243
- if (!src) return false;
244
- const sink = createWriteStream(partPath, resume > 0 ? { flags: "a" } : {});
245
- const reader = src.getReader();
246
- let received = resume;
247
- await new Promise((resolve, reject) => {
248
- sink.on("error", (e) => reject(e));
249
- sink.on("finish", () => resolve());
250
- void (async () => {
251
- try {
252
- for (; ; ) {
253
- const { done, value } = await reader.read();
254
- if (done) break;
255
- received += value.byteLength;
256
- if (!sink.write(value)) {
257
- await new Promise((r) => sink.once("drain", r));
258
- }
259
- if (total > 0) {
260
- broadcast("asr-progress", {
261
- file: spec.file,
262
- percent: Math.min(100, Math.round(received / total * 100))
263
- });
253
+ async function downloadBody() {
254
+ const url = `${host}/${repo}/resolve/main/${spec.file}`;
255
+ const partSt = await stat(partPath).catch(() => null);
256
+ const resumeFrom = partSt?.isFile() ? partSt.size : 0;
257
+ const headers = { "user-agent": "dsh-voice-mode" };
258
+ if (resumeFrom > 0) headers.range = `bytes=${resumeFrom}-`;
259
+ const res = await fetchWithHeadersTimeout(url, { headers, redirect: "follow" }, ac);
260
+ idle.kick();
261
+ if (!redirectHostAllowed(res.url, allowCustomHost)) return false;
262
+ if (res.status === 416) {
263
+ if (await sha256OfFile(partPath).catch(() => "") === spec.sha256) {
264
+ await rename(partPath, localPath);
265
+ return true;
266
+ }
267
+ await unlink(partPath).catch(() => void 0);
268
+ return false;
269
+ }
270
+ if (res.status !== 200 && res.status !== 206) return false;
271
+ const resume = res.status === 206 ? resumeFrom : 0;
272
+ const total = Number(res.headers.get("content-length") ?? 0) + resume;
273
+ const src = res.body;
274
+ if (!src) return false;
275
+ const sink = createWriteStream(partPath, resume > 0 ? { flags: "a" } : {});
276
+ const reader = src.getReader();
277
+ let received = resume;
278
+ await new Promise((resolve, reject) => {
279
+ sink.on("error", (e) => reject(e));
280
+ sink.on("finish", () => resolve());
281
+ void (async () => {
282
+ try {
283
+ for (; ; ) {
284
+ const { done, value } = await reader.read();
285
+ if (done) break;
286
+ idle.kick();
287
+ received += value.byteLength;
288
+ if (!sink.write(value)) {
289
+ await new Promise((r) => sink.once("drain", r));
290
+ idle.kick();
291
+ }
292
+ if (total > 0) {
293
+ broadcast("asr-progress", {
294
+ file: spec.file,
295
+ percent: Math.min(100, Math.round(received / total * 100))
296
+ });
297
+ }
264
298
  }
299
+ sink.end();
300
+ } catch (e) {
301
+ sink.destroy(e);
302
+ reject(e);
265
303
  }
266
- sink.end();
267
- } catch (e) {
268
- sink.destroy(e);
269
- reject(e);
270
- }
271
- })();
272
- });
273
- const actual = await sha256OfFile(partPath).catch(() => "");
274
- if (actual !== spec.sha256) {
275
- await unlink(partPath).catch(() => void 0);
276
- return false;
304
+ })();
305
+ });
306
+ idle.stop();
307
+ const actual = await sha256OfFile(partPath).catch(() => "");
308
+ if (actual !== spec.sha256) {
309
+ await unlink(partPath).catch(() => void 0);
310
+ return false;
311
+ }
312
+ await rename(partPath, localPath);
313
+ const st = await stat(localPath).catch(() => null);
314
+ if (st) verifiedCache.set(localPath, `${cacheKey(st)}:${spec.sha256}`);
315
+ return true;
277
316
  }
278
- await rename(partPath, localPath);
279
- return true;
280
317
  }
281
318
  function isSafeModelRel(rel, subdir) {
282
319
  if (!rel.startsWith(subdir + "/")) return false;
283
320
  if (rel.includes("\\") || rel.includes("\0")) return false;
284
321
  return !rel.split("/").some((seg) => seg === "" || seg === "." || seg === "..");
285
322
  }
323
+ var TREE_MANIFEST = ".model-tree.json";
324
+ async function countTreeFiles(dir) {
325
+ const ents = await readdir(dir, { recursive: true, withFileTypes: true }).catch(() => []);
326
+ return ents.filter((e) => e.isFile() && !e.name.endsWith(".part") && e.name !== TREE_MANIFEST).length;
327
+ }
328
+ async function treeCompleteLocally(repoDir, subdir, sentinel, minFiles) {
329
+ const subRoot = join(repoDir, subdir);
330
+ const raw = await readFile(join(subRoot, TREE_MANIFEST), "utf8").catch(() => null);
331
+ if (raw !== null) {
332
+ try {
333
+ const m = JSON.parse(raw);
334
+ const files = m.files ?? [];
335
+ if (files.length > 0) {
336
+ for (const f of files) {
337
+ const st = await stat(join(repoDir, f.rel)).catch(() => null);
338
+ if (!st?.isFile() || st.size !== f.size) return false;
339
+ }
340
+ return true;
341
+ }
342
+ } catch {
343
+ }
344
+ }
345
+ if (!sentinel || !minFiles) return false;
346
+ if (!(await stat(join(repoDir, sentinel)).catch(() => null))?.isFile()) return false;
347
+ return await countTreeFiles(subRoot) >= minFiles;
348
+ }
286
349
  async function ensureModelTree(opts) {
287
350
  const { repo, repoDir, subdir, primaryHost, allowCustomHost, broadcast } = opts;
288
351
  const hosts = [...new Set([primaryHost, HOST_PRIMARY, HOST_FALLBACK].filter(Boolean))];
289
352
  const subRoot = join(repoDir, subdir);
353
+ if (await treeCompleteLocally(repoDir, subdir, opts.sentinel, opts.minFiles)) return true;
290
354
  await mkdir(subRoot, { recursive: true }).catch(() => void 0);
291
355
  let tree = [];
292
356
  for (const host of hosts) {
@@ -322,37 +386,53 @@ async function ensureModelTree(opts) {
322
386
  for (const host of hosts) {
323
387
  try {
324
388
  const url = host + "/" + repo + "/resolve/main/" + encodeURIComponent(rel);
325
- const res = await fetchWithHeadersTimeout(url, { headers: { "user-agent": "dsh-voice-mode" }, redirect: "follow" });
326
- if (!redirectHostAllowed(res.url, allowCustomHost)) continue;
327
- if (res.status !== 200) continue;
328
- const reader = res.body?.getReader();
329
- if (!reader) continue;
330
- const sink = createWriteStream(partPath);
331
- let size = 0;
332
- await new Promise((resolve, reject) => {
333
- sink.on("error", reject);
334
- sink.on("finish", resolve);
335
- void (async () => {
336
- try {
337
- for (; ; ) {
338
- const r = await reader.read();
339
- if (r.done) break;
340
- size += r.value.byteLength;
341
- if (!sink.write(r.value)) await new Promise((r2) => sink.once("drain", r2));
389
+ const ac = new AbortController();
390
+ const onAbort = () => ac.abort(opts.signal?.reason);
391
+ if (opts.signal?.aborted) onAbort();
392
+ else opts.signal?.addEventListener("abort", onAbort, { once: true });
393
+ const idle = makeIdleWatch(ac, opts.idleTimeoutMs ?? MODEL_BODY_IDLE_TIMEOUT_MS);
394
+ try {
395
+ const res = await fetchWithHeadersTimeout(url, { headers: { "user-agent": "dsh-voice-mode" }, redirect: "follow" }, ac);
396
+ if (!redirectHostAllowed(res.url, allowCustomHost)) continue;
397
+ if (res.status !== 200) continue;
398
+ idle.kick();
399
+ const reader = res.body?.getReader();
400
+ if (!reader) continue;
401
+ const sink = createWriteStream(partPath);
402
+ let size = 0;
403
+ await new Promise((resolve, reject) => {
404
+ sink.on("error", reject);
405
+ sink.on("finish", resolve);
406
+ void (async () => {
407
+ try {
408
+ for (; ; ) {
409
+ const r = await reader.read();
410
+ if (r.done) break;
411
+ idle.kick();
412
+ size += r.value.byteLength;
413
+ if (!sink.write(r.value)) {
414
+ await new Promise((r2) => sink.once("drain", r2));
415
+ idle.kick();
416
+ }
417
+ }
418
+ sink.end();
419
+ } catch (e) {
420
+ sink.destroy(e);
421
+ reject(e);
342
422
  }
343
- sink.end();
344
- } catch (e) {
345
- sink.destroy(e);
346
- reject(e);
347
- }
348
- })();
349
- });
350
- if (size > 0) {
351
- await rename(partPath, localPath);
352
- ok = true;
353
- break;
423
+ })();
424
+ });
425
+ if (size > 0) {
426
+ await rename(partPath, localPath);
427
+ ok = true;
428
+ break;
429
+ }
430
+ } finally {
431
+ idle.stop();
432
+ opts.signal?.removeEventListener("abort", onAbort);
354
433
  }
355
434
  } catch {
435
+ if (opts.signal?.aborted) break;
356
436
  }
357
437
  }
358
438
  if (ok) {
@@ -364,6 +444,16 @@ async function ensureModelTree(opts) {
364
444
  }
365
445
  };
366
446
  await Promise.all(Array.from({ length: 8 }, () => worker()));
447
+ if (allOk) {
448
+ const files = [];
449
+ for (const rel of tree) {
450
+ const st = await stat(join(repoDir, rel)).catch(() => null);
451
+ if (st?.isFile()) files.push({ rel, size: st.size });
452
+ }
453
+ if (files.length === tree.length) {
454
+ await writeFile(join(subRoot, TREE_MANIFEST), JSON.stringify({ files })).catch(() => void 0);
455
+ }
456
+ }
367
457
  return allOk;
368
458
  }
369
459
 
@@ -446,6 +536,7 @@ function createAsrRuntime(options) {
446
536
  return true;
447
537
  })().finally(() => {
448
538
  modelsLoading = null;
539
+ lastProgress = null;
449
540
  });
450
541
  }
451
542
  return modelsLoading;
@@ -489,6 +580,7 @@ function createAsrRuntime(options) {
489
580
  return join2(vadDir, VAD_FILES[0].file);
490
581
  })().finally(() => {
491
582
  vadLoading = null;
583
+ lastProgress = null;
492
584
  });
493
585
  }
494
586
  return vadLoading;
@@ -544,6 +636,7 @@ function createAsrRuntime(options) {
544
636
  return join2(senseDir, SENSE_FILES[0].file);
545
637
  })().finally(() => {
546
638
  senseLoading = null;
639
+ lastProgress = null;
547
640
  });
548
641
  }
549
642
  return senseLoading;
@@ -1182,6 +1275,71 @@ var SentenceSegmenter = class {
1182
1275
 
1183
1276
  // src/tts-queue.ts
1184
1277
  import { MsEdgeTTS, OUTPUT_FORMAT } from "./msedge-tts.cjs";
1278
+
1279
+ // src/emotion.ts
1280
+ var EMOTION_TAG_PATTERN = "<\\s*(break\\s+(?<ms>\\d+)\\s*ms|whisper|\\/whisper|laugh|sigh|emphasis)\\s*>";
1281
+ var TAG_RE = new RegExp(EMOTION_TAG_PATTERN, "gi");
1282
+ var STRIP_RE = new RegExp(EMOTION_TAG_PATTERN, "gi");
1283
+ function stripEmotionTags(raw) {
1284
+ return raw.replace(STRIP_RE, " ");
1285
+ }
1286
+ function parseEmotionTags(raw) {
1287
+ const out = [];
1288
+ let buf = "";
1289
+ let whisper = false;
1290
+ let pendingBreakMs = 0;
1291
+ const flush = () => {
1292
+ const t = buf.trim();
1293
+ buf = "";
1294
+ if (t.length === 0) return;
1295
+ const seg = { text: t, whisper };
1296
+ out.push(seg);
1297
+ };
1298
+ let lastEnd = 0;
1299
+ for (const m of raw.matchAll(TAG_RE)) {
1300
+ const idx = m.index ?? 0;
1301
+ buf += raw.slice(lastEnd, idx);
1302
+ lastEnd = idx + m[0].length;
1303
+ const tag = (m[1] ?? "").toLowerCase().trim();
1304
+ if (tag.startsWith("break")) {
1305
+ const ms = Number(m.groups?.ms ?? 0);
1306
+ if (!Number.isFinite(ms) || ms <= 0) continue;
1307
+ if (buf.trim().length > 0) {
1308
+ flush();
1309
+ }
1310
+ const last = out[out.length - 1];
1311
+ if (last) {
1312
+ ;
1313
+ last.preBreakMs = (last.preBreakMs ?? 0) + ms;
1314
+ } else {
1315
+ pendingBreakMs += ms;
1316
+ }
1317
+ } else if (tag === "whisper") {
1318
+ flush();
1319
+ whisper = true;
1320
+ } else if (tag === "/whisper") {
1321
+ flush();
1322
+ whisper = false;
1323
+ } else {
1324
+ }
1325
+ }
1326
+ buf += raw.slice(lastEnd);
1327
+ flush();
1328
+ if (pendingBreakMs > 0) {
1329
+ const last = out[out.length - 1];
1330
+ if (last) {
1331
+ ;
1332
+ last.preBreakMs = (last.preBreakMs ?? 0) + pendingBreakMs;
1333
+ }
1334
+ pendingBreakMs = 0;
1335
+ }
1336
+ if (whisper) {
1337
+ for (const s of out) s.whisper = false;
1338
+ }
1339
+ return out;
1340
+ }
1341
+
1342
+ // src/tts-queue.ts
1185
1343
  var MP3_MAGIC = 255;
1186
1344
  var TTS_METADATA = { wordBoundaryEnabled: false, sentenceBoundaryEnabled: false };
1187
1345
  var EDGE_VOICES_TIMEOUT_MS = 3e4;
@@ -1192,6 +1350,17 @@ function prosodyFromRate(rate) {
1192
1350
  function isValidMp3(buf) {
1193
1351
  return buf.length > 0 && buf[0] === MP3_MAGIC;
1194
1352
  }
1353
+ function escapeXmlText(text) {
1354
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1355
+ }
1356
+ function isEmptyAudio(buf) {
1357
+ if (buf.length === 0) return true;
1358
+ if (buf.length !== 44) return false;
1359
+ if (buf.toString("latin1", 0, 4) !== "RIFF") return false;
1360
+ if (buf.toString("latin1", 8, 12) !== "WAVE") return false;
1361
+ if (buf.toString("latin1", 36, 40) !== "data") return false;
1362
+ return buf.readUInt32LE(40) === 0;
1363
+ }
1195
1364
  var EdgeTtsEngine = class {
1196
1365
  voice;
1197
1366
  rate;
@@ -1205,6 +1374,8 @@ var EdgeTtsEngine = class {
1205
1374
  if (rate !== void 0 && Number.isFinite(rate)) this.rate = rate;
1206
1375
  }
1207
1376
  async synthesize(text, options = {}) {
1377
+ const spoken = escapeXmlText(stripEmotionTags(text));
1378
+ if (spoken.trim() === "") return Buffer.alloc(0);
1208
1379
  const tts = new MsEdgeTTS();
1209
1380
  try {
1210
1381
  await tts.setMetadata(
@@ -1212,7 +1383,7 @@ var EdgeTtsEngine = class {
1212
1383
  OUTPUT_FORMAT.AUDIO_24KHZ_48KBITRATE_MONO_MP3,
1213
1384
  TTS_METADATA
1214
1385
  );
1215
- const { audioStream } = tts.toStream(text, prosodyFromRate(options.rate ?? this.rate));
1386
+ const { audioStream } = tts.toStream(spoken, prosodyFromRate(options.rate ?? this.rate));
1216
1387
  const chunks = [];
1217
1388
  for await (const chunk of audioStream) chunks.push(chunk);
1218
1389
  const buf = Buffer.concat(chunks);
@@ -1553,6 +1724,7 @@ var TtsQueue = class {
1553
1724
  this.onSkip?.(sessionId, item.text, q.failStreak);
1554
1725
  continue;
1555
1726
  }
1727
+ if (isEmptyAudio(buf)) continue;
1556
1728
  q.errorNotified = false;
1557
1729
  q.failStreak = 0;
1558
1730
  q.backoff = 0;
@@ -1687,64 +1859,6 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
1687
1859
  import { join as join3 } from "node:path";
1688
1860
  import { statSync as statSync2 } from "node:fs";
1689
1861
 
1690
- // src/emotion.ts
1691
- var TAG_RE = /<\s*(break\s+(?<ms>\d+)\s*ms|whisper|\/whisper|laugh|sigh|emphasis)\s*>/gi;
1692
- function parseEmotionTags(raw) {
1693
- const out = [];
1694
- let buf = "";
1695
- let whisper = false;
1696
- let pendingBreakMs = 0;
1697
- const flush = () => {
1698
- const t = buf.trim();
1699
- buf = "";
1700
- if (t.length === 0) return;
1701
- const seg = { text: t, whisper };
1702
- out.push(seg);
1703
- };
1704
- let lastEnd = 0;
1705
- for (const m of raw.matchAll(TAG_RE)) {
1706
- const idx = m.index ?? 0;
1707
- buf += raw.slice(lastEnd, idx);
1708
- lastEnd = idx + m[0].length;
1709
- const tag = (m[1] ?? "").toLowerCase().trim();
1710
- if (tag.startsWith("break")) {
1711
- const ms = Number(m.groups?.ms ?? 0);
1712
- if (!Number.isFinite(ms) || ms <= 0) continue;
1713
- if (buf.trim().length > 0) {
1714
- flush();
1715
- }
1716
- const last = out[out.length - 1];
1717
- if (last) {
1718
- ;
1719
- last.preBreakMs = (last.preBreakMs ?? 0) + ms;
1720
- } else {
1721
- pendingBreakMs += ms;
1722
- }
1723
- } else if (tag === "whisper") {
1724
- flush();
1725
- whisper = true;
1726
- } else if (tag === "/whisper") {
1727
- flush();
1728
- whisper = false;
1729
- } else {
1730
- }
1731
- }
1732
- buf += raw.slice(lastEnd);
1733
- flush();
1734
- if (pendingBreakMs > 0) {
1735
- const last = out[out.length - 1];
1736
- if (last) {
1737
- ;
1738
- last.preBreakMs = (last.preBreakMs ?? 0) + pendingBreakMs;
1739
- }
1740
- pendingBreakMs = 0;
1741
- }
1742
- if (whisper) {
1743
- for (const s of out) s.whisper = false;
1744
- }
1745
- return out;
1746
- }
1747
-
1748
1862
  // src/voice-catalog.ts
1749
1863
  var VITS_SPEAKERS = [
1750
1864
  { name: "suyingxue", sid: 0, zh: "\u7D20\u6620\u96EA", en: "Su Yingxue", gender: "F" },
@@ -1972,6 +2086,7 @@ function kokoroSpec(model) {
1972
2086
  toSid: kokoroVoiceToSid
1973
2087
  };
1974
2088
  }
2089
+ var CALL_TIMEOUT_MS = 12e4;
1975
2090
  function createSherpaLocalEngine(options) {
1976
2091
  const { cacheDir, modelHost, allowCustomHost, broadcast } = options;
1977
2092
  let downloadProgress = null;
@@ -1992,13 +2107,15 @@ function createSherpaLocalEngine(options) {
1992
2107
  let child = null;
1993
2108
  let childInit = false;
1994
2109
  let closed = false;
2110
+ const dlAbort = new AbortController();
2111
+ let starting = false;
1995
2112
  const respawnChild = async () => {
1996
2113
  if (child) {
1997
2114
  child.kill();
1998
2115
  child = null;
1999
2116
  }
2000
2117
  childInit = false;
2001
- ready = null;
2118
+ if (!starting) ready = null;
2002
2119
  };
2003
2120
  let voice = spec.defaultVoice;
2004
2121
  let speed = 1;
@@ -2008,23 +2125,36 @@ function createSherpaLocalEngine(options) {
2008
2125
  let engineErrorCode;
2009
2126
  let nextId = 1;
2010
2127
  const pending = /* @__PURE__ */ new Map();
2011
- const call = (msg) => new Promise((resolve, reject) => {
2128
+ const call = (msg, timeoutMs = CALL_TIMEOUT_MS) => new Promise((resolve, reject) => {
2012
2129
  if (!child) {
2013
2130
  reject(new Error("tts child not running"));
2014
2131
  return;
2015
2132
  }
2016
2133
  const id = nextId++;
2017
- pending.set(id, { resolve, reject });
2134
+ const timer = setTimeout(() => {
2135
+ if (!pending.delete(id)) return;
2136
+ reject(new Error(`tts child call timeout: ${String(msg.type)}`));
2137
+ if (msg.type !== "close") void respawnChild();
2138
+ }, timeoutMs);
2139
+ pending.set(id, {
2140
+ owner: child,
2141
+ resolve: (r) => (clearTimeout(timer), resolve(r)),
2142
+ reject: (e) => (clearTimeout(timer), reject(e))
2143
+ });
2018
2144
  child.send({ id, ...msg });
2019
2145
  });
2020
- const rejectAll = (e) => {
2021
- for (const p of pending.values()) p.reject(e);
2022
- pending.clear();
2146
+ const rejectAll = (e, owner) => {
2147
+ for (const [id, p] of pending) {
2148
+ if (owner && p.owner !== owner) continue;
2149
+ pending.delete(id);
2150
+ p.reject(e);
2151
+ }
2023
2152
  };
2024
2153
  const ensureReady = () => {
2025
2154
  if (ready && child) return ready;
2026
2155
  if (!ready) {
2027
2156
  ready = (async () => {
2157
+ starting = true;
2028
2158
  engineLoading = true;
2029
2159
  engineError = void 0;
2030
2160
  engineErrorCode = void 0;
@@ -2039,7 +2169,8 @@ function createSherpaLocalEngine(options) {
2039
2169
  spec: f,
2040
2170
  primaryHost: modelHost(),
2041
2171
  allowCustomHost,
2042
- broadcast: trackedBroadcast
2172
+ broadcast: trackedBroadcast,
2173
+ signal: dlAbort.signal
2043
2174
  });
2044
2175
  if (closed) return;
2045
2176
  if (!ok) throw new Error("local TTS model download/verify failed: " + f.file);
@@ -2051,7 +2182,12 @@ function createSherpaLocalEngine(options) {
2051
2182
  subdir: "espeak-ng-data",
2052
2183
  primaryHost: modelHost(),
2053
2184
  allowCustomHost,
2054
- broadcast: trackedBroadcast
2185
+ broadcast: trackedBroadcast,
2186
+ signal: dlAbort.signal,
2187
+ // I-3:本地完整则 0 网络;无清单的旧缓存以哨兵 + 文件数兜底。
2188
+ // 取上游整树文件数(HF API 实测 int8/fp32 均 355):低于它一律联网补全,半成品树不会被误判完整。
2189
+ sentinel: "espeak-ng-data/phontab",
2190
+ minFiles: 355
2055
2191
  });
2056
2192
  if (closed) return;
2057
2193
  if (!treeOk) throw new Error("local TTS model download failed: espeak-ng-data");
@@ -2084,18 +2220,18 @@ function createSherpaLocalEngine(options) {
2084
2220
  else p.reject(new Error(m.error ?? "tts child error"));
2085
2221
  });
2086
2222
  child.on("error", (e) => {
2087
- rejectAll(e instanceof Error ? e : new Error(String(e)));
2223
+ rejectAll(e instanceof Error ? e : new Error(String(e)), me);
2088
2224
  if (child !== me) return;
2089
2225
  child = null;
2090
2226
  childInit = false;
2091
- ready = null;
2227
+ if (!starting) ready = null;
2092
2228
  });
2093
2229
  child.on("exit", (code) => {
2094
- rejectAll(new Error(`tts child exited with code ${code}`));
2230
+ rejectAll(new Error(`tts child exited with code ${code}`), me);
2095
2231
  if (child !== me) return;
2096
2232
  child = null;
2097
2233
  childInit = false;
2098
- ready = null;
2234
+ if (!starting) ready = null;
2099
2235
  });
2100
2236
  }
2101
2237
  if (!childInit) {
@@ -2112,6 +2248,8 @@ function createSherpaLocalEngine(options) {
2112
2248
  throw e;
2113
2249
  } finally {
2114
2250
  engineLoading = false;
2251
+ starting = false;
2252
+ downloadProgress = null;
2115
2253
  }
2116
2254
  })().then(
2117
2255
  (v) => {
@@ -2172,7 +2310,7 @@ function createSherpaLocalEngine(options) {
2172
2310
  const spd = typeof opts.rate === "number" && Number.isFinite(opts.rate) ? Math.min(2, Math.max(0.5, opts.rate)) : speed;
2173
2311
  const segments = parseEmotionTags(text);
2174
2312
  if (segments.length === 0) {
2175
- return pcmToWav(Buffer.alloc(0), 16e3);
2313
+ return Buffer.alloc(0);
2176
2314
  }
2177
2315
  const chunks = [];
2178
2316
  let resolvedSampleRate = 0;
@@ -2202,7 +2340,7 @@ function createSherpaLocalEngine(options) {
2202
2340
  }
2203
2341
  }
2204
2342
  if (chunks.length === 0) {
2205
- return pcmToWav(Buffer.alloc(0), resolvedSampleRate || 16e3);
2343
+ return Buffer.alloc(0);
2206
2344
  }
2207
2345
  const total = chunks.reduce((acc, c) => acc + c.length, 0);
2208
2346
  const merged = new Float32Array(total);
@@ -2215,10 +2353,11 @@ function createSherpaLocalEngine(options) {
2215
2353
  },
2216
2354
  async close() {
2217
2355
  closed = true;
2356
+ dlAbort.abort();
2218
2357
  const c = child;
2219
2358
  if (c) {
2220
2359
  try {
2221
- await call({ type: "close" });
2360
+ await call({ type: "close" }, 100);
2222
2361
  } catch {
2223
2362
  }
2224
2363
  try {
@@ -2575,7 +2714,26 @@ var en = {
2575
2714
  function correctionSystem(lang) {
2576
2715
  return lang === "en" ? "You are a speech-recognition corrector. The user text comes from ASR and may contain homophone errors, typos, or missing/wrong punctuation. Make only minimal fixes: correct typos/homophones and fix punctuation, preserving the original meaning and colloquial style. Do not rewrite sentences, do not add content, do not answer questions, and do not alter numbers or proper nouns. Output only the corrected text, with no explanation. If the input has no obvious errors, return it unchanged." : "\u4F60\u662F\u4E2D\u6587\u8BED\u97F3\u8BC6\u522B\u7EA0\u9519\u5668\u3002\u7528\u6237\u7684\u8BDD\u6765\u81EA\u8BED\u97F3\u8BC6\u522B\uFF08ASR\uFF09\uFF0C\u53EF\u80FD\u6709\u540C\u97F3\u5B57\u3001\u9519\u522B\u5B57\u3001\u6807\u70B9\u7F3A\u5931\u6216\u9519\u8BEF\u3002\u8BF7\u53EA\u505A\u6700\u5C0F\u4FEE\u6B63\uFF1A\u6539\u9519\u522B\u5B57/\u540C\u97F3\u5B57\u3001\u8865\u6807\u70B9\uFF0C\u4FDD\u6301\u539F\u610F\u4E0E\u53E3\u8BED\u98CE\u683C\uFF1B\u4E0D\u8981\u6539\u5199\u53E5\u5B50\u3001\u4E0D\u8981\u8865\u5145\u5185\u5BB9\u3001\u4E0D\u8981\u56DE\u7B54\u95EE\u9898\u3001\u4E0D\u8981\u6539\u53D8\u6570\u5B57\u548C\u4E13\u4E1A\u672F\u8BED\u3002\u53EA\u8F93\u51FA\u4FEE\u6B63\u540E\u7684\u6587\u672C\uFF0C\u4E0D\u8981\u4EFB\u4F55\u89E3\u91CA\u3002\u5982\u679C\u539F\u6587\u6CA1\u6709\u660E\u663E\u9519\u8BEF\uFF0C\u539F\u6837\u8FD4\u56DE\u3002";
2577
2716
  }
2578
- var CORRECTION_PREAMBLE_RE = /^(?:以下是|这是)?(?:修正|纠正|更正|纠错)|^(?:here(?:'s| is) (?:the |an |a )?)?(?:corrected|correction)\b/i;
2717
+ var CORRECTION_PREAMBLE_RE = /^(?:以下是|这是|已|文本)?(?:修正|纠正|更正|纠错)|^(?:here(?:'s| is) (?:the |an |a )?|i have |text after )?(?:corrected|correction)\b/i;
2718
+ var CORRECTION_MIN_SIMILARITY = 0.45;
2719
+ var SIMILARITY_MAX_CHARS = 1500;
2720
+ function normalizedSimilarity(a, b) {
2721
+ const norm = (s) => Array.from(s.toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, ""));
2722
+ const x = norm(a);
2723
+ const y = norm(b);
2724
+ const n = Math.max(x.length, y.length);
2725
+ if (n === 0) return 1;
2726
+ if (n > SIMILARITY_MAX_CHARS) return 1;
2727
+ let prev = Array.from({ length: y.length + 1 }, (_, j) => j);
2728
+ for (let i = 1; i <= x.length; i++) {
2729
+ const cur = [i];
2730
+ for (let j = 1; j <= y.length; j++) {
2731
+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x[i - 1] === y[j - 1] ? 0 : 1));
2732
+ }
2733
+ prev = cur;
2734
+ }
2735
+ return 1 - prev[y.length] / n;
2736
+ }
2579
2737
  var CORRECTION_FILLER_WORDS = "\u5F53\u7136\u53EF\u4EE5|\u5F53\u7136|\u597D\u5427|\u597D\u7684?|\u884C\u5427|\u884C|\u662F\u7684|\u55EF|\u6536\u5230|\u660E\u767D\u4E86|\u77E5\u9053\u4E86|Thank you|Of course|Got it|OK|Okay|Sure|Certainly|Alright|Understood|Hello|Hi|Yes|Thanks";
2580
2738
  var CORRECTION_FILLER_PREFIX_RE = new RegExp(
2581
2739
  "^(?:(?:" + CORRECTION_FILLER_WORDS + ")(?:\\s*[,\uFF0C\u3001:\uFF1A.\u3002!\uFF01?\uFF1F)\uFF09]|\\s))+",
@@ -2608,6 +2766,7 @@ async function correctText(ctx, text, lang) {
2608
2766
  }
2609
2767
  const corrected = out.trim();
2610
2768
  if (corrected.length > Math.max(trimmed.length * 3, trimmed.length + 24)) return text;
2769
+ if (normalizedSimilarity(trimmed, corrected) < CORRECTION_MIN_SIMILARITY) return text;
2611
2770
  if (CORRECTION_PREAMBLE_RE.test(corrected)) return text;
2612
2771
  let noFiller = corrected;
2613
2772
  for (; ; ) {
@@ -3085,6 +3244,15 @@ function apply(ctx, config) {
3085
3244
  };
3086
3245
  const sseClients = /* @__PURE__ */ new Set();
3087
3246
  const latestConnByTab = /* @__PURE__ */ new Map();
3247
+ const SSE_MAX_BUFFERED = 4 * 1024 * 1024;
3248
+ ctx.effect(() => () => {
3249
+ if (ownerYieldTimer) clearTimeout(ownerYieldTimer);
3250
+ ownerYieldTimer = null;
3251
+ const live = [...sseClients];
3252
+ sseClients.clear();
3253
+ latestConnByTab.clear();
3254
+ for (const c of live) c.end();
3255
+ });
3088
3256
  const broadcast = (event, payload) => {
3089
3257
  for (const c of sseClients) {
3090
3258
  try {
@@ -3525,7 +3693,7 @@ function apply(ctx, config) {
3525
3693
  respondJson2(res, 400, { code: "bad_request", error: "invalid on" });
3526
3694
  return;
3527
3695
  }
3528
- if (!limiter.hit(`toggle:${sessionId}`, 2, 2e3)) {
3696
+ if (on === true && !limiter.hit(`toggle:${sessionId}`, 2, 2e3)) {
3529
3697
  respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
3530
3698
  return;
3531
3699
  }
@@ -3943,6 +4111,10 @@ function apply(ctx, config) {
3943
4111
  data: ${JSON.stringify(payload)}
3944
4112
 
3945
4113
  `);
4114
+ if (res.writableLength > SSE_MAX_BUFFERED) {
4115
+ console.warn(`[dsh-voice-mode] SSE client too slow (buffered ${res.writableLength}B); dropping connection`);
4116
+ res.destroy();
4117
+ }
3946
4118
  };
3947
4119
  const end = () => {
3948
4120
  try {