dsh-voice-mode 0.7.27 → 0.7.28

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
@@ -294,6 +294,7 @@ async function ensureModelTree(opts) {
294
294
  const res = await fetchWithHeadersTimeout(host + "/api/models/" + repo + "?blobs=true", {
295
295
  headers: { "user-agent": "dsh-voice-mode" }
296
296
  });
297
+ if (!redirectHostAllowed(res.url, allowCustomHost)) continue;
297
298
  if (res.ok) {
298
299
  const j = await res.json();
299
300
  tree = (j.siblings ?? []).map((s) => s.rfilename ?? "").filter((f) => isSafeModelRel(f, subdir));
@@ -321,12 +322,12 @@ async function ensureModelTree(opts) {
321
322
  for (const host of hosts) {
322
323
  try {
323
324
  const url = host + "/" + repo + "/resolve/main/" + encodeURIComponent(rel);
324
- const res = await fetch(url, { headers: { "user-agent": "dsh-voice-mode" }, redirect: "follow" });
325
+ const res = await fetchWithHeadersTimeout(url, { headers: { "user-agent": "dsh-voice-mode" }, redirect: "follow" });
325
326
  if (!redirectHostAllowed(res.url, allowCustomHost)) continue;
326
327
  if (res.status !== 200) continue;
327
- const sink = createWriteStream(partPath);
328
328
  const reader = res.body?.getReader();
329
329
  if (!reader) continue;
330
+ const sink = createWriteStream(partPath);
330
331
  let size = 0;
331
332
  await new Promise((resolve, reject) => {
332
333
  sink.on("error", reject);
@@ -424,6 +425,7 @@ function createAsrRuntime(options) {
424
425
  const finalizing = /* @__PURE__ */ new Map();
425
426
  const resetGen = /* @__PURE__ */ new Map();
426
427
  let recognizer = null;
428
+ let recognizerDisposed = false;
427
429
  let modelsReady = false;
428
430
  let modelsLoading = null;
429
431
  let asrFailAt = 0;
@@ -449,7 +451,9 @@ function createAsrRuntime(options) {
449
451
  return modelsLoading;
450
452
  };
451
453
  const getRecognizer = async () => {
454
+ if (recognizerDisposed) return null;
452
455
  if (!await ensureModels()) return null;
456
+ if (recognizerDisposed) return null;
453
457
  if (recognizer) return recognizer;
454
458
  const t = (f) => join2(repoDir, f);
455
459
  recognizer = createOnlineRecognizer({
@@ -830,6 +834,7 @@ function createAsrRuntime(options) {
830
834
  dispose: () => {
831
835
  clearInterval(sweepTimer);
832
836
  senseDisposed = true;
837
+ recognizerDisposed = true;
833
838
  let w = senseWorker;
834
839
  senseWorker = null;
835
840
  senseWorkerSyncing = null;
@@ -1063,14 +1068,27 @@ function splitSentences(chunk) {
1063
1068
  }
1064
1069
  return { sentences, tail: chunk.slice(lastEnd) };
1065
1070
  }
1071
+ function cutHead(text, max) {
1072
+ let idx = -1;
1073
+ for (let i = Math.min(max, text.length) - 1; i > 0; i--) {
1074
+ if (/[,,、\s]/.test(text[i])) {
1075
+ idx = i + 1;
1076
+ break;
1077
+ }
1078
+ }
1079
+ if (idx <= 0) idx = Math.max(1, Math.floor(max / 2));
1080
+ return [text.slice(0, idx), text.slice(idx)];
1081
+ }
1066
1082
  var SentenceSegmenter = class {
1067
1083
  buffer = "";
1068
1084
  maxChars;
1069
1085
  /** 是否处在 ``` 代码块内(跨 delta 有效:流式 delta 只有几个 token,代码块总是被切碎送达,
1070
1086
  * plainText 的整块正则匹配不到,代码会被逐句念出——「总是朗读」覆盖打字会话后尤其明显)。 */
1071
1087
  inFence = false;
1072
- /** delta 末尾悬挂的 1-2 个反引号(可能是被切开的 ``` 前半)。 */
1088
+ /** delta 末尾悬挂的 1-2 个反引号(被切开的 ``` 前半;连续 3 个及以上是完整围栏,不悬挂)。 */
1073
1089
  ticks = "";
1090
+ /** 围栏内被抑制的内容暂存:流结束时若仍未闭合则回退输出(宁可念代码,也不吞掉整回合正文)。 */
1091
+ fenced = "";
1074
1092
  constructor(options = {}) {
1075
1093
  this.maxChars = options.maxSentenceChars ?? 200;
1076
1094
  }
@@ -1078,23 +1096,49 @@ var SentenceSegmenter = class {
1078
1096
  dropFences(chunk) {
1079
1097
  let s = this.ticks + chunk;
1080
1098
  this.ticks = "";
1081
- const hang = /`{1,2}$/.exec(s);
1082
- if (hang) {
1083
- this.ticks = hang[0];
1084
- s = s.slice(0, -hang[0].length);
1099
+ const trail = /`+$/.exec(s);
1100
+ const hang = trail ? trail[0].length : 0;
1101
+ if (hang > 0 && hang <= 2) {
1102
+ this.ticks = s.slice(-hang);
1103
+ s = s.slice(0, -hang);
1085
1104
  }
1086
1105
  let out = "";
1087
1106
  for (; ; ) {
1088
- const i = s.indexOf("```");
1089
- if (i < 0) {
1090
- if (!this.inFence) out += s;
1107
+ const m = /`{3,}/.exec(s);
1108
+ if (!m) {
1109
+ if (this.inFence) this.fenced += s;
1110
+ else out += s;
1091
1111
  return out;
1092
1112
  }
1093
- if (!this.inFence) out += s.slice(0, i) + "\n";
1113
+ if (this.inFence) this.fenced += s.slice(0, m.index);
1114
+ else out += s.slice(0, m.index) + "\n";
1094
1115
  this.inFence = !this.inFence;
1095
- s = s.slice(i + 3);
1116
+ if (!this.inFence) this.fenced = "";
1117
+ s = s.slice(m.index + m[0].length);
1096
1118
  }
1097
1119
  }
1120
+ /**
1121
+ * 安全阀:把超过 maxChars 的文字墙切下一段(feed 与 flush 共用同一口径)。
1122
+ * 切点取 ≤ maxChars 内**最后一个**「,,、\s」——取第一个会把无标点的英文/代码逐词切成
1123
+ * 几十个小段;超长段必须 ≤ maxChars,否则阀形同虚设。没有可用分隔符时取一半。
1124
+ */
1125
+ cutWall() {
1126
+ const [head, rest] = cutHead(this.buffer, this.maxChars);
1127
+ this.buffer = rest;
1128
+ return sanitizeForTts(head).trim();
1129
+ }
1130
+ /** 成句本身超过 maxChars(长逗号句)同样过安全阀,逐段输出。 */
1131
+ capSentence(s, out) {
1132
+ let rest = s;
1133
+ while (rest.length > this.maxChars) {
1134
+ const [head, tail] = cutHead(rest, this.maxChars);
1135
+ rest = tail;
1136
+ const t2 = sanitizeForTts(head).trim();
1137
+ if (t2 && !SKIP_PREFIX.test(t2)) out.push(t2);
1138
+ }
1139
+ const t = sanitizeForTts(rest).trim();
1140
+ if (t && !SKIP_PREFIX.test(t)) out.push(t);
1141
+ }
1098
1142
  /** 喂入一段 raw delta,返回它补全的完整句子。 */
1099
1143
  feed(chunk) {
1100
1144
  const cleaned = plainText(this.dropFences(chunk));
@@ -1103,27 +1147,36 @@ var SentenceSegmenter = class {
1103
1147
  const { sentences, tail } = splitSentences(this.buffer);
1104
1148
  this.buffer = tail;
1105
1149
  const out = [];
1106
- for (const s of sentences) {
1107
- const t = sanitizeForTts(s).trim();
1108
- if (t && !SKIP_PREFIX.test(t)) out.push(t);
1109
- }
1110
- if (this.buffer.length > this.maxChars) {
1111
- const cut = this.buffer.search(/[,,、\s]/);
1112
- const idx = cut > 0 ? cut : Math.floor(this.maxChars / 2);
1113
- const head = sanitizeForTts(this.buffer.slice(0, idx)).trim();
1114
- this.buffer = this.buffer.slice(idx);
1115
- if (head) out.push(head);
1150
+ for (const s of sentences) this.capSentence(s, out);
1151
+ while (this.buffer.length > this.maxChars) {
1152
+ const head = this.cutWall();
1153
+ if (head && !SKIP_PREFIX.test(head)) out.push(head);
1116
1154
  }
1117
1155
  return out;
1118
1156
  }
1119
- /** 收尾:flush 剩余缓冲(流结束)。 */
1157
+ /**
1158
+ * 收尾:flush 剩余缓冲(流结束)。
1159
+ * 整回合未见闭合围栏 → 把围栏内被抑制的内容回退输出(v0.7.27 之前未配对围栏零损失,
1160
+ * 全靠这一条守住;否则一个孤立的 ``` 会静默吞掉本回合剩余正文)。
1161
+ *
1162
+ * 过安全阀后的多段仍按「代码内容」朗读:既有取舍是「宁念代码不吞正文」,切分只改朗读粒度
1163
+ * (每段一次合成请求)、不改取舍;段序 = 原文字序,段内容 = 原文字符的连续切片(切点沿用
1164
+ * feed() 同一口径)。不回退成「整体不念」——那等于回到吞正文的老问题。
1165
+ */
1120
1166
  flush() {
1167
+ if (this.inFence) this.buffer = plainText(this.buffer + this.fenced);
1168
+ const out = [];
1169
+ while (this.buffer.length > this.maxChars) {
1170
+ const head = this.cutWall();
1171
+ if (head && !SKIP_PREFIX.test(head)) out.push(head);
1172
+ }
1121
1173
  const t = sanitizeForTts(this.buffer).trim();
1122
1174
  this.buffer = "";
1123
1175
  this.inFence = false;
1124
1176
  this.ticks = "";
1125
- if (t && !SKIP_PREFIX.test(t)) return [t];
1126
- return [];
1177
+ this.fenced = "";
1178
+ if (t && !SKIP_PREFIX.test(t)) out.push(t);
1179
+ return out;
1127
1180
  }
1128
1181
  };
1129
1182
 
@@ -1204,7 +1257,38 @@ async function listEdgeVoices(force = false) {
1204
1257
  }
1205
1258
  }
1206
1259
  var TtsQueue = class {
1260
+ /**
1261
+ * 各会话队列:只在**有活**时存在(见 pump finally 的退休处置),不再随历史会话数增长。
1262
+ *
1263
+ * R15(Issue #15 T-3):本表原先每会话留一个空 SessionQueue 且永不回收,而所有对外
1264
+ * 清理入口都是 cancel()(index.ts:1007/1376/1390/1409/1665)——cancel 按设计必须保留
1265
+ * 队列对象,故 turn 退出路径下这张表只增不减(量级 = 历史会话数,非本次回归)。
1266
+ * 真正的回收点只能是「队列已排空、泵已收工」的那一刻。
1267
+ *
1268
+ * 【不变式:seq 单调】回收绝不能让某会话的 sentenceId 归零或回退——client 的
1269
+ * rejectSeqUpTo(client.tsx:1359/1385,`frame.sentenceId <= rejectLine` 即丢弃)记的是
1270
+ * 「本会话已见过的最大句号」,新句必须**大于**它,否则新回复前 N 句被静默丢弃(静音)。
1271
+ * 这正是 index.ts:1376/1409 与 setEngine B1 都写明「用 cancel 而非 prune 保 seq 连续」
1272
+ * 的同一条理由,也是不用 prune() 回收的直接原因。
1273
+ * 故 seq 已上移为本类的全局计数器(见下方 seq),会话维度不再持有任何 seq 状态——
1274
+ * 这样「回收」与「seq 不归零」不再互相排斥:会话回来时拿到的必然是一个比它历史上
1275
+ * 任何一句都大的句号(全局单调在会话上的投影必然严格递增)。
1276
+ */
1207
1277
  queues = /* @__PURE__ */ new Map();
1278
+ /**
1279
+ * 句序号发号器(**全局**,非每会话)。
1280
+ *
1281
+ * 为什么不是每会话:每会话 seq 必须活到会话彻底消失,可任何「活到会话消失」的形态
1282
+ * (墓碑表、有界 LRU 淘汰)都只是把同一张永不回收的表换个名字——LRU 淘汰后该会话再回来
1283
+ * 仍会 seq 归零,仍撞 rejectSeqUpTo。全局计数器则让「会话维度 seq 状态」根本不存在,
1284
+ * 回收得以无条件成立。
1285
+ *
1286
+ * 只在成功广播时自增(pump 的 `const sentenceId = this.seq++` 位于成功分支内),
1287
+ * 与改动前逐字等价。client 只把 sentenceId 用于**比较**(`> rejectLine` 放行、
1288
+ * `!== curSentenceId` 重建拼帧缓冲),从不假设连续或小值——见 client.tsx:1354
1289
+ * 「host 的 sentenceId 跨回合单调递增,新回合必然 > 线」。
1290
+ */
1291
+ seq = 0;
1208
1292
  listeners = /* @__PURE__ */ new Set();
1209
1293
  engine;
1210
1294
  /** TTS 全体不可达通知(每会话去重,成功后复位)。 */
@@ -1212,8 +1296,34 @@ var TtsQueue = class {
1212
1296
  /** 单句合成重试耗尽被跳过通知(每句一次;此前是静默丢句——真机「回复偶尔不朗读」根因之一)。 */
1213
1297
  onSkip;
1214
1298
  /** 某会话队列跑空(无在途、无积压):「说完就关」据此判定朗读真正结束——客户端只能看到
1215
- * 句间的播放空档,分不清「后面还有句子在合成」与「已全部读完」。 */
1299
+ * 句间的播放空档,分不清「后面还有句子在合成」与「已全部读完」。
1300
+ *
1301
+ * R15(Issue #15 Important-2):本回调的口径取决于 awaitTurnEnd,见下方 openTurns。 */
1216
1302
  onIdle;
1303
+ /**
1304
+ * R15(Issue #15 Important-2):回合闸门——「队列排空」≠「回合结束」。
1305
+ *
1306
+ * 缺陷(逐行核对 8c0368a):onIdle 原义「排空一次即发」,无「回合是否真正结束」约束。
1307
+ * 而 host 在**每一条** llm/stream 的 finally 都把 turn 打回 listening(index.ts:1875,
1308
+ * 于是一条流结束 = 回合结束)。带工具调用的 agent 在第一轮流结束与第二轮开始之间存在
1309
+ * 秒级到分钟级的空档:第一段文本排空 → tts-idle → 客户端 ttsDrained=true;播完、playing
1310
+ * =false → mic-gesture.onceFinished(sawRun && !running && ttsDrained && !playing)成立
1311
+ * → 维持 ONCE_SETTLE_MS=1.2s 后 exitMode('manual') → /toggle off → queue.cancel;第二轮
1312
+ * llm/stream 因 activeVoiceSession 已空不再被 tap(index.ts:957)→ **后半段回复永不朗读**,
1313
+ * 麦克风在 AI 还在干活时熄灭。非工具场景的等价触发是句间停顿 >1.2s。
1314
+ *
1315
+ * 修法:onIdle 降级为「候选空闲」,真正的结束信号由 host 在**回合真正结束**时确认——
1316
+ * 即宿主 dsh 的 `agent/turn-stopping`(契约原文「the model owes no response: no live
1317
+ * tool calls, no fresh steering」,正是工具空档与真回合结束的判别式),在那儿调
1318
+ * noteTurnEnd(sessionId)。队列侧:enqueue 视为「新回合在途」标记,pump finally 的排空
1319
+ * 回调在该标记存在时**不发**(那只是句间空档);回合结束标记被清且队列已排空时补发。
1320
+ *
1321
+ * awaitTurnEnd 缺省 false = 闸门关闭,保持原语义(排空即发),供尚未接回合结束钩子的
1322
+ * 宿主零行为变化地兼容;置 true 后本集合才被 enqueue 填充。
1323
+ */
1324
+ awaitTurnEnd;
1325
+ /** awaitTurnEnd 开启时:某会话当前有一轮可能仍在进行(已入队过文本、回合尚未确认结束)。 */
1326
+ openTurns = /* @__PURE__ */ new Set();
1217
1327
  /**
1218
1328
  * M7②(Issue #15 R11):退避重启计时器句柄集。
1219
1329
  *
@@ -1251,12 +1361,59 @@ var TtsQueue = class {
1251
1361
  this.onError = options.onError;
1252
1362
  this.onSkip = options.onSkip;
1253
1363
  this.onIdle = options.onIdle;
1364
+ this.awaitTurnEnd = options.awaitTurnEnd === true;
1365
+ }
1366
+ /**
1367
+ * R15(Issue #15 Important-2):host 确认该会话的一轮作答**真正结束**(不会再有新的
1368
+ * llm/stream)时调用,接线点为宿主 dsh 的 `agent/turn-stopping`。
1369
+ *
1370
+ * 置 awaitTurnEnd 后:关闭该会话的在途标记;若队列此刻已排空则立即补发一次 onIdle
1371
+ * ——回合结束时 pump 的 finally 可能早已过去(最后一句播完时就发过「候选空闲」被
1372
+ * 闸门拦下),此时没有后续回调可等,必须在此补发。
1373
+ * 幂等/重复调用无害:重复触发时消费侧有 `!ttsDrained` 去重护栏(client.tsx:1189)。
1374
+ */
1375
+ noteTurnEnd(sessionId) {
1376
+ if (this.closed) return;
1377
+ this.openTurns.delete(sessionId);
1378
+ if (!this.awaitTurnEnd) return;
1379
+ if (!this.isIdle(sessionId)) return;
1380
+ try {
1381
+ this.onIdle?.(sessionId);
1382
+ } catch {
1383
+ }
1254
1384
  }
1255
1385
  /** 该会话当前无在途合成、无积压(未建队列也算空闲)。 */
1256
1386
  isIdle(sessionId) {
1257
1387
  const q = this.queues.get(sessionId);
1258
1388
  return !q || !q.busy && q.pending.length === 0;
1259
1389
  }
1390
+ /**
1391
+ * R15(Issue #15 T-4):回合作废——本轮**不会再有任何后续文本**,但与「回合正常结束」
1392
+ * (noteTurnEnd)不同的一点是:**不补发 onIdle**。
1393
+ *
1394
+ * 为何队列侧无法自行判断 abort(宿主侧实测 + 本文件调用点实测):
1395
+ * · 回合 abort 时宿主是 `catch → 直接重抛`:不派发 `agent/turn-stopping`、不派发
1396
+ * `agent/error`、不经本插件的任何入口——队列侧**收不到任何信号**,无法自愈;
1397
+ * · 唯一在队列侧与 abort「沾边」的入口是 cancel(),但它是五处语义完全不同的出口的
1398
+ * 共同出口,对队列可见的输入**只有 sessionId 一个**:/cancel「停止朗读」与用户打断
1399
+ * (index.ts:1665)、进模式 (:1376)、退模式 (:1409)、会话让出 (:1007/:1390)。
1400
+ * 在 cancel() 里清 openTurns,「停止朗读」后队列排空就会补发一条 tts-idle → 把
1401
+ * R15 Important-1(回合间空档误发致 mode:once 提前退出、后半段永不朗读)**重新
1402
+ * 引进来**。故这里刻意不挂 cancel(),宁可把区分权交回 host。
1403
+ *
1404
+ * 语义(与 noteTurnEnd 唯一的差别就是不发 onIdle):
1405
+ * · 只合闸门(清 openTurns):此后该会话若还有句子读尽,pump finally 会正常补发;
1406
+ * 下一回合的 enqueue 也照常重开闸门,语义与 noteTurnEnd 之后完全一致。
1407
+ * · 不主动补发:abort 时队列可能已空,此时该不该让 mode:once 立即收尾取决于 host
1408
+ * 的上下文(用户是否马上又要开口),队列无从判断。若 host 判定「abort 前已读尽」,
1409
+ * 在其后紧接一次 noteTurnEnd(sessionId) 即可补发(两次调用对 openTurns 幂等)。
1410
+ *
1411
+ * 接线点:宿主侧在判定回合被 abort / blocked / 空首步时调用(这三类路径都不派发
1412
+ * agent/turn-stopping——error 半边已由 ctx.on('agent/error') 覆盖,见 index.ts:1112)。
1413
+ */
1414
+ abandonTurn(sessionId) {
1415
+ this.openTurns.delete(sessionId);
1416
+ }
1260
1417
  /** 当前引擎音频 MIME(/preview 的 Content-Type 也用它)。 */
1261
1418
  get mime() {
1262
1419
  return this.engine.mime;
@@ -1273,8 +1430,10 @@ var TtsQueue = class {
1273
1430
  * sentenceId 拒绝线(rejectSeqUpTo)是「旧会话遗留的最大句号」,新回复前 N 句
1274
1431
  * 全部 ≤ 线被静默丢弃——正是 /toggle 用 cancel 而非 prune 保 seq 连续的同一条
1275
1432
  * 不变式(index.ts:1177 进模式 cancel / :1191 让出旧会话 cancel(previous) / :1210 退出 cancel)。
1276
- * 故此处与 cancel() 同构:逐队列 epoch++ + 清积压,但保留 SessionQueue 对象本身
1277
- * (seq 连续递增,跨引擎切换不归零)。
1433
+ * 故此处与 cancel() 同构:逐队列 epoch++ + 清积压,但保留 SessionQueue 对象本身。
1434
+ * R15 T-3 后这条顾虑的一半已由构造消除:seq 是**全局**发号器(不再随队列存亡),
1435
+ * 故即便队列对象事后被回收,重入的会话拿到的句号仍必然 > 旧线;但 epoch 仍必须
1436
+ * 逐队列提升才能压住孤儿泵,那部分保留原样。
1278
1437
  */
1279
1438
  setEngine(engine) {
1280
1439
  const old = this.engine;
@@ -1330,9 +1489,10 @@ var TtsQueue = class {
1330
1489
  /** 为某会话入队一句;若泵空闲则启动。 */
1331
1490
  enqueue(sessionId, text) {
1332
1491
  if (this.closed) return;
1492
+ if (this.awaitTurnEnd) this.openTurns.add(sessionId);
1333
1493
  let q = this.queues.get(sessionId);
1334
1494
  if (!q) {
1335
- q = { pending: [], busy: false, seq: 0, epoch: 0, errorNotified: false, backoff: 0, failStreak: 0 };
1495
+ q = { pending: [], busy: false, epoch: 0, errorNotified: false, backoff: 0, failStreak: 0 };
1336
1496
  this.queues.set(sessionId, q);
1337
1497
  }
1338
1498
  if (q.pending.length >= 500) {
@@ -1361,6 +1521,7 @@ var TtsQueue = class {
1361
1521
  q.epoch++;
1362
1522
  q.pending.length = 0;
1363
1523
  }
1524
+ this.openTurns.delete(sessionId);
1364
1525
  this.queues.delete(sessionId);
1365
1526
  }
1366
1527
  async pump(sessionId, q) {
@@ -1395,7 +1556,7 @@ var TtsQueue = class {
1395
1556
  q.errorNotified = false;
1396
1557
  q.failStreak = 0;
1397
1558
  q.backoff = 0;
1398
- const sentenceId = q.seq++;
1559
+ const sentenceId = this.seq++;
1399
1560
  const mime = this.engine.mime;
1400
1561
  const dataFrame = {
1401
1562
  sessionId,
@@ -1438,10 +1599,13 @@ var TtsQueue = class {
1438
1599
  if (this.queues.get(sessionId) !== q) return;
1439
1600
  if (this.closed) return;
1440
1601
  if (q.pending.length === 0) {
1441
- try {
1442
- this.onIdle?.(sessionId);
1443
- } catch {
1602
+ if (!this.openTurns.has(sessionId)) {
1603
+ try {
1604
+ this.onIdle?.(sessionId);
1605
+ } catch {
1606
+ }
1444
1607
  }
1608
+ this.queues.delete(sessionId);
1445
1609
  } else {
1446
1610
  const delay = q.errorNotified ? q.backoff : 0;
1447
1611
  q.backoff = Math.min(8e3, delay + 1e3);
@@ -1457,6 +1621,7 @@ var TtsQueue = class {
1457
1621
  }
1458
1622
  async close() {
1459
1623
  this.closed = true;
1624
+ this.openTurns.clear();
1460
1625
  for (const timer of this.backoffTimers) clearTimeout(timer);
1461
1626
  this.backoffTimers.clear();
1462
1627
  for (const timer of this.retryTimers) clearTimeout(timer);
@@ -1888,6 +2053,7 @@ function createSherpaLocalEngine(options) {
1888
2053
  allowCustomHost,
1889
2054
  broadcast: trackedBroadcast
1890
2055
  });
2056
+ if (closed) return;
1891
2057
  if (!treeOk) throw new Error("local TTS model download failed: espeak-ng-data");
1892
2058
  }
1893
2059
  if (!child) {
@@ -1897,6 +2063,7 @@ function createSherpaLocalEngine(options) {
1897
2063
  stdio: ["ignore", "ignore", "pipe", "ipc"],
1898
2064
  ...runtime.execPath ? { execPath: runtime.execPath, env: runtime.env } : {}
1899
2065
  });
2066
+ const me = child;
1900
2067
  let stderrTail = "";
1901
2068
  child.stderr?.on("data", (chunk) => {
1902
2069
  stderrTail += String(chunk);
@@ -1918,12 +2085,14 @@ function createSherpaLocalEngine(options) {
1918
2085
  });
1919
2086
  child.on("error", (e) => {
1920
2087
  rejectAll(e instanceof Error ? e : new Error(String(e)));
2088
+ if (child !== me) return;
1921
2089
  child = null;
1922
2090
  childInit = false;
1923
2091
  ready = null;
1924
2092
  });
1925
2093
  child.on("exit", (code) => {
1926
2094
  rejectAll(new Error(`tts child exited with code ${code}`));
2095
+ if (child !== me) return;
1927
2096
  child = null;
1928
2097
  childInit = false;
1929
2098
  ready = null;
@@ -1931,6 +2100,7 @@ function createSherpaLocalEngine(options) {
1931
2100
  }
1932
2101
  if (!childInit) {
1933
2102
  const init = await call({ type: "init", kind: options.kind, paths: spec.workerPaths(repoDir) });
2103
+ if (closed) return;
1934
2104
  if (!init.ok) throw new Error(init.error ?? "tts child init failed");
1935
2105
  childInit = true;
1936
2106
  }
@@ -2171,7 +2341,7 @@ var en = {
2171
2341
  startFail: "Voice mode failed to start: {err}",
2172
2342
  holdDots: "Hold to talk\u2026",
2173
2343
  exit: "Exit",
2174
- configUnavailableNote: " (settings document not ready; the panel will appear when it is).",
2344
+ configUnavailableNote: " (settings document not ready; retrying \u2014 the panel will appear when it is).",
2175
2345
  previewNameFirst: "Enter a voice ShortName first",
2176
2346
  previewDisabled: "Voice mode disabled (plugin enabled=false); preview unavailable",
2177
2347
  // 批 G 任务 6:本地 TTS 引擎未下载模型时禁用试听按钮 + 提示。
@@ -2211,6 +2381,17 @@ var en = {
2211
2381
  // R1 收尾(fix-client 直连 tk() 调用):连续 3 次回声拒断的解释出口 + 快捷键非法停用提示。
2212
2382
  echoRejectHint: "Strong echo detected \u2014 barge-in is limited by echo protection. Use headphones or switch to manual barge-in",
2213
2383
  shortcutInvalid: "Invalid shortcut, disabled. Fix it in settings (e.g. Ctrl+Shift+V); leave empty to use the mic button only",
2384
+ descComposerShortcut: "Shortcut to toggle voice mode while the composer has focus (default Alt/Option+Enter)",
2385
+ composerShortcutLabel: "Enter / exit voice mode (in composer)",
2386
+ shortcutRecord: "Record",
2387
+ shortcutRecording: "Press a key combo\u2026",
2388
+ shortcutCancel: "Cancel",
2389
+ shortcutNeedModifier: "At least one modifier is required",
2390
+ shortcutUnsupportedKey: "Only letters, digits, Enter, Space and Tab are supported",
2391
+ shortcutPlaceholder: "Click Record, then press a combo",
2392
+ shortcutReset: "Reset to default",
2393
+ shortcutNote: "Alt/Option+Enter toggles inside the composer; Cmd / Ctrl / Alt / Shift combos are supported; leaving it empty means mic button only. While recording, Backspace clears and Esc cancels; avoid browser-reserved combos (Cmd+W / T / N / L). Changes apply immediately.",
2394
+ secShortcut: "Shortcut",
2214
2395
  elapsedHint: "Current voice session duration",
2215
2396
  botLevelsHint: "AI playback level (blue bar = TTS playback, green bar = microphone)",
2216
2397
  interruptConfirm: "interrupt confirm",
@@ -2263,7 +2444,7 @@ var en = {
2263
2444
  descShowStatusBar: "Show the voice status bar above the composer (waveform, transcript, timer, notices, exit); when off, state shows only on the mic button",
2264
2445
  descWakeWord: 'Wake word (default off; e.g. "Hey D"): recognition starts only after you say it, to avoid accidental triggers. You may say it together with your command ("Hey D, check the weather" \u2014 the wake word is stripped and never sent); it must be repeated after each utterance split or barge-in; toggle mode only (inactive in hold / manual barge-in \u2014 and equally inactive when the detect probe fails and falls back to manual, the default on machines without native echo cancellation such as Safari); saying it while the agent is reading does not trigger (barge-in stays VAD-based). Fault-tolerant matching (homophones / leading fillers); 3-4 characters recommended; not a dedicated KWS engine \u2014 noisy environments may delay or falsely trigger',
2265
2446
  wakePlaceholder: "e.g. Hey D",
2266
- settingsCardDesc: "Engine / voice / rate / interrupt / barge-in / echo gate / silence / idle / model host / auto-send / auto-resume / mode / wake word / tool beep / ITN / caption font / caption width / yielding / yield window / barge-in salvage / LLM correction",
2447
+ settingsCardDesc: "Engine / voice / rate / interrupt / barge-in / echo gate / silence / idle / model host / auto-send / read replies / status bar / caption overlay / auto-resume / mode / wake word / tool beep / ITN / caption font / caption width / yielding / yield window / barge-in salvage / LLM correction",
2267
2448
  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.",
2268
2449
  effectivePending: "{count} change(s) will apply next time you enter voice mode: {items}",
2269
2450
  valueOn: "On",
@@ -2341,7 +2522,7 @@ var en = {
2341
2522
  bargeInModeLabel: "Interrupt mode",
2342
2523
  echoGateDbLabel: "Echo gate",
2343
2524
  modeLabel: "Interaction mode",
2344
- shortcutLabel: "Shortcut",
2525
+ shortcutLabel: "Enter / exit voice mode (app-wide)",
2345
2526
  wakeWordLabel: "Wake word",
2346
2527
  toolBeepLabel: "Tool-call beep",
2347
2528
  autoSendLabel: "Auto-send",
@@ -2377,6 +2558,7 @@ var en = {
2377
2558
  errUnknownSession: "Voice session expired \u2014 re-enter voice mode",
2378
2559
  errForbidden: "Request denied (local access only, or origin mismatch)",
2379
2560
  errBadRequest: "Invalid request",
2561
+ errMethodNotAllowed: "Request method not allowed",
2380
2562
  errEngineNotActive: "That read-aloud engine is not active",
2381
2563
  errModelDownload: "Model download failed \u2014 check your network",
2382
2564
  errTooManyStreams: "Too many voice connections \u2014 close other voice tabs and retry",
@@ -2393,7 +2575,16 @@ var en = {
2393
2575
  function correctionSystem(lang) {
2394
2576
  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";
2395
2577
  }
2396
- var CORRECTION_PREAMBLE_RE = /^(?:以下是|这是)?(?:修正|纠正|更正|纠错)|^(?:here is (?:the )?)?(?:corrected|correction)\b/i;
2578
+ var CORRECTION_PREAMBLE_RE = /^(?:以下是|这是)?(?:修正|纠正|更正|纠错)|^(?:here(?:'s| is) (?:the |an |a )?)?(?:corrected|correction)\b/i;
2579
+ 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
+ var CORRECTION_FILLER_PREFIX_RE = new RegExp(
2581
+ "^(?:(?:" + CORRECTION_FILLER_WORDS + ")(?:\\s*[,\uFF0C\u3001:\uFF1A.\u3002!\uFF01?\uFF1F)\uFF09]|\\s))+",
2582
+ "i"
2583
+ );
2584
+ var CORRECTION_PURE_FILLER_RE = new RegExp(
2585
+ "^(?:(?:" + CORRECTION_FILLER_WORDS + ")(?:\\s*[,\uFF0C\u3001:\uFF1A.\u3002!\uFF01?\uFF1F)\uFF09]\\s*|\\s+))*(?:" + CORRECTION_FILLER_WORDS + ")\\s*$",
2586
+ "i"
2587
+ );
2397
2588
  async function correctText(ctx, text, lang) {
2398
2589
  const trimmed = String(text ?? "").trim();
2399
2590
  if (!trimmed) return text;
@@ -2418,6 +2609,17 @@ async function correctText(ctx, text, lang) {
2418
2609
  const corrected = out.trim();
2419
2610
  if (corrected.length > Math.max(trimmed.length * 3, trimmed.length + 24)) return text;
2420
2611
  if (CORRECTION_PREAMBLE_RE.test(corrected)) return text;
2612
+ let noFiller = corrected;
2613
+ for (; ; ) {
2614
+ const next = noFiller.replace(CORRECTION_FILLER_PREFIX_RE, "").trimStart();
2615
+ const after = CORRECTION_PURE_FILLER_RE.test(next) ? "" : next;
2616
+ if (after === noFiller) break;
2617
+ noFiller = after;
2618
+ }
2619
+ if (noFiller !== corrected) {
2620
+ if (noFiller === "") return text;
2621
+ if (CORRECTION_PREAMBLE_RE.test(noFiller)) return text;
2622
+ }
2421
2623
  return corrected || text;
2422
2624
  } catch {
2423
2625
  return text;
@@ -2551,6 +2753,7 @@ function readLegacyVoiceSettings(dir, keys) {
2551
2753
  // src/index.ts
2552
2754
  var name = "voice-mode";
2553
2755
  var NS_VOICE_MODE = "voice-mode";
2756
+ var MUTED_STREAMS_WITHOUT_TURN = 4;
2554
2757
  var BASE_PATH = "/voice-mode";
2555
2758
  var PREVIEW_NETWORK_PATTERN = /fetch failed|ECONN|ENOTFOUND|getaddrinfo|ETIMEDOUT|EAI_AGAIN|network|unreachable|socket hang up|aborted|WebSocket error/i;
2556
2759
  var PREVIEW_ENGINE_PATTERN = /model download|model verify|init failed|child exited|tts child|local TTS|prepare|sherpa|local Kokoro/i;
@@ -2594,6 +2797,7 @@ var VOICE_SETTINGS_DEFAULTS = {
2594
2797
  bargeInMode: "detect",
2595
2798
  echoGateDb: 6,
2596
2799
  shortcut: "Ctrl+Shift+V",
2800
+ composerShortcut: "Alt+Enter",
2597
2801
  spokenFormat: true,
2598
2802
  senseVoice: true,
2599
2803
  wakeWord: "",
@@ -2627,6 +2831,7 @@ var DESC = {
2627
2831
  readAloud: en.descReadAloud,
2628
2832
  showCaptions: en.descShowCaptions,
2629
2833
  showStatusBar: en.descShowStatusBar,
2834
+ composerShortcut: en.descComposerShortcut,
2630
2835
  bargeInMode: en.descBargeIn,
2631
2836
  echoGateDb: en.descEchoGate,
2632
2837
  shortcut: en.descShortcut,
@@ -2668,6 +2873,7 @@ function createVoiceSettingsSchema(defs) {
2668
2873
  readAloud: z.union([z.const("voice"), z.const("always"), z.const("off")]).default(d.readAloud).description(DESC.readAloud),
2669
2874
  showCaptions: z.boolean().default(d.showCaptions).description(DESC.showCaptions),
2670
2875
  showStatusBar: z.boolean().default(d.showStatusBar).description(DESC.showStatusBar),
2876
+ composerShortcut: z.string().default(d.composerShortcut).description(DESC.composerShortcut),
2671
2877
  bargeInMode: z.union([z.const("auto"), z.const("manual"), z.const("detect")]).default(d.bargeInMode).description(DESC.bargeInMode),
2672
2878
  echoGateDb: z.number().min(3).max(12).default(d.echoGateDb).description(
2673
2879
  DESC.echoGateDb
@@ -2736,6 +2942,7 @@ var Config = z.object({
2736
2942
  // 仍可把回声门阈设成 0(句句误打断)或让位窗口设成 60000(让位后一分钟不说话)。
2737
2943
  echoGateDb: z.number().min(3).max(12).default(6),
2738
2944
  shortcut: z.string().default("Ctrl+Shift+V"),
2945
+ composerShortcut: z.string().default("Alt+Enter"),
2739
2946
  spokenFormat: z.boolean().default(true),
2740
2947
  senseVoice: z.boolean().default(true),
2741
2948
  wakeWord: z.string().default(""),
@@ -2773,6 +2980,7 @@ function voiceSettingsFromConfig(config) {
2773
2980
  bargeInMode,
2774
2981
  echoGateDb,
2775
2982
  shortcut,
2983
+ composerShortcut,
2776
2984
  spokenFormat,
2777
2985
  senseVoice,
2778
2986
  wakeWord,
@@ -2803,6 +3011,7 @@ function voiceSettingsFromConfig(config) {
2803
3011
  bargeInMode,
2804
3012
  echoGateDb,
2805
3013
  shortcut,
3014
+ composerShortcut,
2806
3015
  spokenFormat,
2807
3016
  senseVoice,
2808
3017
  wakeWord,
@@ -2823,17 +3032,29 @@ function apply(ctx, config) {
2823
3032
  let activeTabId = null;
2824
3033
  let activeVoiceLang = "zh";
2825
3034
  let ownerYieldTimer = null;
3035
+ const readMuted = /* @__PURE__ */ new Map();
3036
+ const turnOfSession = /* @__PURE__ */ new Map();
3037
+ const tapInFlight = /* @__PURE__ */ new Set();
2826
3038
  const turnStates = /* @__PURE__ */ new Map();
2827
- const setTurn = (sessionId, state) => {
3039
+ const setTurn = (sessionId, state, turn) => {
2828
3040
  if (turnStates.get(sessionId) === state) return;
2829
3041
  turnStates.set(sessionId, state);
2830
- broadcast("turn", { sessionId, state });
3042
+ broadcast("turn", { sessionId, state, turn });
2831
3043
  };
2832
3044
  const turnGen = /* @__PURE__ */ new Map();
2833
- const clearTurnState = (sessionId) => {
2834
- setTurn(sessionId, "idle");
3045
+ const dropTurnTables = (sessionId) => {
2835
3046
  turnStates.delete(sessionId);
2836
3047
  turnGen.delete(sessionId);
3048
+ readMuted.delete(sessionId);
3049
+ turnOfSession.delete(sessionId);
3050
+ };
3051
+ const clearTurnState = (sessionId) => {
3052
+ setTurn(sessionId, "idle");
3053
+ dropTurnTables(sessionId);
3054
+ };
3055
+ const reclaimFocusState = (sessionId) => {
3056
+ if (sessionId === null || sessionId === activeVoiceSession || tapInFlight.has(sessionId)) return;
3057
+ dropTurnTables(sessionId);
2837
3058
  };
2838
3059
  const sessions = ctx.get("sessions");
2839
3060
  const limiter = new RateLimiter();
@@ -3001,7 +3222,12 @@ function apply(ctx, config) {
3001
3222
  // 单句重试耗尽被跳过:显式下行(客户端提示 + 诊断),不再静默丢句。
3002
3223
  // streak = 连续被跳过的句数:客户端据此区分偶发抖动与「云端整体不可用」(如服务端拒绝握手)。
3003
3224
  onSkip: (sessionId, text, streak) => broadcast("tts-skip", { sessionId, text: text.slice(0, 80), streak }),
3004
- onIdle: (sessionId) => broadcast("tts-idle", { sessionId })
3225
+ onIdle: (sessionId) => broadcast("tts-idle", { sessionId }),
3226
+ // R15(Issue #15 Important-2 host 侧接线):onIdle 降级为「候选空闲」——「队列排空」不等于
3227
+ // 「回合结束」。带工具调用的回合会在工具执行期间把队列排空一次,据此发 tts-idle 会让
3228
+ // mode:once 在空档里提前 exitMode(麦克风熄灭、后半段回复永不朗读)。置 true 后 tts-idle
3229
+ // 只在 host 经 `agent/turn-stopping` 确认回合真正结束后才发(见下方钩子)。
3230
+ awaitTurnEnd: true
3005
3231
  });
3006
3232
  queue.updateVoice(vset.voice, vset.rate);
3007
3233
  const unsubscribe = queue.subscribe((frame) => broadcast("audio", frame));
@@ -3069,23 +3295,49 @@ function apply(ctx, config) {
3069
3295
  const rawSessionId = options.sessionId;
3070
3296
  if (!config.enabled || rawSessionId === void 0 || options.purpose !== void 0) return next();
3071
3297
  const sessionId = rawSessionId;
3072
- const alwaysRead = vset.readAloud === "always" && focusedSessionId === sessionId;
3298
+ const alwaysRead = vset.readAloud === "always" && focusedSessionId === sessionId && activeVoiceSession === null;
3073
3299
  if (activeVoiceSession !== sessionId && !alwaysRead) return next();
3074
3300
  const gen = (turnGen.get(sessionId) ?? 0) + 1;
3075
3301
  turnGen.set(sessionId, gen);
3302
+ const mute = readMuted.get(sessionId);
3303
+ const pos = turnOfSession.get(sessionId);
3304
+ if (mute !== void 0) {
3305
+ const atTurnBoundary = pos !== void 0 && (mute.turn === null ? pos.step === 1 : pos.turn !== mute.turn);
3306
+ if (atTurnBoundary) {
3307
+ readMuted.delete(sessionId);
3308
+ } else if (pos === void 0 || mute.turn === null) {
3309
+ mute.streams += 1;
3310
+ if (mute.streams > MUTED_STREAMS_WITHOUT_TURN) readMuted.delete(sessionId);
3311
+ }
3312
+ }
3313
+ tapInFlight.add(sessionId);
3076
3314
  return tapActiveStream(
3077
3315
  sessionId,
3078
3316
  next(),
3079
3317
  queue,
3080
3318
  broadcast,
3081
3319
  (state) => {
3320
+ const turn = turnOfSession.get(sessionId)?.turn;
3321
+ if (state === "listening") {
3322
+ tapInFlight.delete(sessionId);
3323
+ if (focusedSessionId !== sessionId && activeVoiceSession !== sessionId) {
3324
+ reclaimFocusState(sessionId);
3325
+ }
3326
+ }
3082
3327
  if ((turnGen.get(sessionId) ?? 0) !== gen) return;
3083
- setTurn(sessionId, state);
3084
- if (state === "listening" && queue.isIdle(sessionId)) broadcast("tts-idle", { sessionId });
3328
+ setTurn(sessionId, state, turn);
3085
3329
  },
3086
- vset.readAloud !== "off"
3330
+ vset.readAloud !== "off",
3331
+ () => readMuted.has(sessionId)
3087
3332
  );
3088
3333
  });
3334
+ ctx.on("agent/turn-stopping", ({ agent }) => queue.noteTurnEnd(agent.id));
3335
+ ctx.on("agent/error", ({ agent }) => queue.noteTurnEnd(agent.id));
3336
+ ctx.on("agent/pre-step", ({ agent, turn, step }, next) => {
3337
+ const sid = agent.id;
3338
+ if (sid === activeVoiceSession || sid === focusedSessionId) turnOfSession.set(sid, { turn, step });
3339
+ return next();
3340
+ });
3089
3341
  const base = BASE_PATH;
3090
3342
  ctx.effect(
3091
3343
  () => ctx.webServer.register({
@@ -3126,6 +3378,7 @@ function apply(ctx, config) {
3126
3378
  bargeInMode: vset.bargeInMode,
3127
3379
  echoGateDb: vset.echoGateDb,
3128
3380
  shortcut: vset.shortcut,
3381
+ composerShortcut: vset.composerShortcut,
3129
3382
  wakeWord: vset.wakeWord,
3130
3383
  toolBeep: vset.toolBeep,
3131
3384
  captionFontSize: vset.captionFontSize,
@@ -3149,11 +3402,12 @@ function apply(ctx, config) {
3149
3402
  path: `${base}/preview`,
3150
3403
  handler: (req, res) => {
3151
3404
  if (denyNonLoopback(req, res)) return;
3152
- if (denyCrossOrigin(req, res)) return;
3153
- if (!limiter.hit(`preview:${clientKey(req)}`, 20, 6e4)) {
3154
- respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
3405
+ if (req.method !== "POST") {
3406
+ res.setHeader("allow", "POST");
3407
+ respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
3155
3408
  return;
3156
3409
  }
3410
+ if (denyCrossOrigin(req, res)) return;
3157
3411
  if (!config.enabled) {
3158
3412
  respondJson2(res, 403, { code: "voice_disabled", error: "voice mode disabled" });
3159
3413
  return;
@@ -3177,6 +3431,10 @@ function apply(ctx, config) {
3177
3431
  respondJson2(res, 400, { code: "bad_request", error: "voice required" });
3178
3432
  return;
3179
3433
  }
3434
+ if (!limiter.hit(`preview:${clientKey(req)}`, 20, 6e4)) {
3435
+ respondJson2(res, 429, { code: "rate_limited", error: "rate limited" });
3436
+ return;
3437
+ }
3180
3438
  const sample = previewSample(currentEngine(), voice);
3181
3439
  let buf;
3182
3440
  try {
@@ -3333,9 +3591,8 @@ function apply(ctx, config) {
3333
3591
  handler: (req, res) => {
3334
3592
  if (denyNonLoopback(req, res)) return;
3335
3593
  if (req.method !== "POST") {
3336
- res.statusCode = 405;
3337
3594
  res.setHeader("allow", "POST");
3338
- res.end();
3595
+ respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
3339
3596
  return;
3340
3597
  }
3341
3598
  if (denyCrossOrigin(req, res)) return;
@@ -3467,6 +3724,11 @@ function apply(ctx, config) {
3467
3724
  handler: (req, res) => {
3468
3725
  if (denyNonLoopback(req, res)) return;
3469
3726
  if (denyCrossOrigin(req, res)) return;
3727
+ if (req.method !== "POST") {
3728
+ res.setHeader("allow", "POST");
3729
+ respondJson2(res, 405, { code: "method_not_allowed", error: "POST required" });
3730
+ return;
3731
+ }
3470
3732
  let sid = "";
3471
3733
  try {
3472
3734
  const url = new URL(req.url ?? "/", "http://localhost");
@@ -3498,10 +3760,12 @@ function apply(ctx, config) {
3498
3760
  collectBody(req, res, MAX_JSON_BODY, (body) => {
3499
3761
  let sessionId;
3500
3762
  let keepAsr = false;
3763
+ let isInterrupt = false;
3501
3764
  try {
3502
3765
  const parsed = JSON.parse(body || "{}");
3503
3766
  sessionId = parsed.sessionId;
3504
3767
  keepAsr = parsed.keepAsr === true;
3768
+ isInterrupt = parsed.reason === "interrupt";
3505
3769
  } catch {
3506
3770
  }
3507
3771
  if (sessionId && (sessionId === activeVoiceSession || sessionId === focusedSessionId)) {
@@ -3510,6 +3774,8 @@ function apply(ctx, config) {
3510
3774
  return;
3511
3775
  }
3512
3776
  queue.cancel(sessionId);
3777
+ if (isInterrupt) queue.abandonTurn(sessionId);
3778
+ readMuted.set(sessionId, { turn: turnOfSession.get(sessionId)?.turn ?? null, streams: 0 });
3513
3779
  if (!keepAsr && sessionId === activeVoiceSession) asr.reset(sessionId);
3514
3780
  }
3515
3781
  respondJson2(res, 200, { ok: true });
@@ -3528,9 +3794,8 @@ function apply(ctx, config) {
3528
3794
  return;
3529
3795
  }
3530
3796
  if (req.method !== "POST") {
3531
- res.statusCode = 405;
3532
3797
  res.setHeader("allow", "GET, POST");
3533
- res.end();
3798
+ respondJson2(res, 405, { code: "method_not_allowed", error: "GET or POST required" });
3534
3799
  return;
3535
3800
  }
3536
3801
  if (denyCrossOrigin(req, res)) return;
@@ -3613,6 +3878,7 @@ function apply(ctx, config) {
3613
3878
  } catch {
3614
3879
  }
3615
3880
  const { sessionId, tabId } = parsed;
3881
+ const prevFocus = focusedSessionId;
3616
3882
  const validTab = typeof tabId === "string" && tabId.length > 0 && tabId.length <= 64;
3617
3883
  const validSid = typeof sessionId === "string" && sessionId.length > 0 && sessionId.length <= 128;
3618
3884
  if (!validTab || !(validSid || sessionId === null)) {
@@ -3620,12 +3886,17 @@ function apply(ctx, config) {
3620
3886
  return;
3621
3887
  }
3622
3888
  if (validSid) {
3889
+ if (sessions && !sessions.get(sessionId)) {
3890
+ respondJson2(res, 403, { code: "unknown_session", error: "unknown session" });
3891
+ return;
3892
+ }
3623
3893
  focusedSessionId = sessionId;
3624
3894
  focusedTabId = tabId;
3625
3895
  } else if (tabId === focusedTabId) {
3626
3896
  focusedSessionId = null;
3627
3897
  focusedTabId = null;
3628
3898
  }
3899
+ if (prevFocus !== null && prevFocus !== focusedSessionId) reclaimFocusState(prevFocus);
3629
3900
  broadcast("focus", { sessionId: focusedSessionId, tabId: focusedTabId });
3630
3901
  respondJson2(res, 200, { ok: true, sessionId: focusedSessionId, tabId: focusedTabId });
3631
3902
  });
@@ -3705,8 +3976,10 @@ data: ${JSON.stringify(payload)}
3705
3976
  if (tabId !== null && latestConnByTab.get(tabId) === client) {
3706
3977
  latestConnByTab.delete(tabId);
3707
3978
  if (tabId === focusedTabId) {
3979
+ const prevFocus = focusedSessionId;
3708
3980
  focusedSessionId = null;
3709
3981
  focusedTabId = null;
3982
+ reclaimFocusState(prevFocus);
3710
3983
  broadcast("focus", { sessionId: null, tabId: null });
3711
3984
  }
3712
3985
  if (tabId === activeTabId) {
@@ -3751,7 +4024,7 @@ function collectBody(req, res, maxBytes, onBody) {
3751
4024
  req.on("error", () => {
3752
4025
  });
3753
4026
  }
3754
- async function* tapActiveStream(sessionId, inner, queue, broadcast, onTurn, speak = true) {
4027
+ async function* tapActiveStream(sessionId, inner, queue, broadcast, onTurn, speak = true, muted = () => false) {
3755
4028
  const segmenter = new SentenceSegmenter();
3756
4029
  let firstTokenBroadcast = false;
3757
4030
  let firstSentenceBroadcast = false;
@@ -3761,7 +4034,7 @@ async function* tapActiveStream(sessionId, inner, queue, broadcast, onTurn, spea
3761
4034
  if (flushed) return;
3762
4035
  flushed = true;
3763
4036
  for (const s of segmenter.flush()) {
3764
- if (speak) queue.enqueue(sessionId, s);
4037
+ if (speak && !muted()) queue.enqueue(sessionId, s);
3765
4038
  }
3766
4039
  };
3767
4040
  try {
@@ -3777,7 +4050,7 @@ async function* tapActiveStream(sessionId, inner, queue, broadcast, onTurn, spea
3777
4050
  firstSentenceBroadcast = true;
3778
4051
  broadcast("latency", { sessionId, stage: "first-sentence-text" });
3779
4052
  }
3780
- if (speak) queue.enqueue(sessionId, s);
4053
+ if (speak && !muted()) queue.enqueue(sessionId, s);
3781
4054
  }
3782
4055
  }
3783
4056
  if (chunk.type === "tool-call-delta" && chunk.name) {