dsh-mobile-plugin 0.5.138 → 0.5.139

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.
Files changed (35) hide show
  1. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/pairing.md +2 -2
  2. package/lib/impl.js +8 -5
  3. package/lib/mobile/permissions.js +10 -0
  4. package/lib/mobile/session-step.js +17 -11
  5. package/lib/mobile/voice/frames.js +198 -0
  6. package/lib/mobile/voice/gateway.js +746 -0
  7. package/lib/mobile/voice/lang.js +347 -0
  8. package/lib/mobile/voice/lexicon-store.js +189 -0
  9. package/lib/mobile/voice/lexicon.js +508 -0
  10. package/lib/mobile/voice/panel-api.js +88 -0
  11. package/lib/mobile/voice/postprocess.js +551 -0
  12. package/lib/mobile/voice/protocol.js +306 -0
  13. package/lib/mobile/voice/providers/cn/aliyun.js +401 -0
  14. package/lib/mobile/voice/providers/cn/tencent.js +402 -0
  15. package/lib/mobile/voice/providers/cn/volc.js +328 -0
  16. package/lib/mobile/voice/providers/cn/xfyun.js +290 -0
  17. package/lib/mobile/voice/providers/host.js +190 -0
  18. package/lib/mobile/voice/providers/intl/_common.js +346 -0
  19. package/lib/mobile/voice/providers/intl/assemblyai.js +353 -0
  20. package/lib/mobile/voice/providers/intl/azure.js +444 -0
  21. package/lib/mobile/voice/providers/intl/deepgram.js +366 -0
  22. package/lib/mobile/voice/providers/intl/openai.js +389 -0
  23. package/lib/mobile/voice/providers/intl/speechmatics.js +405 -0
  24. package/lib/mobile/voice/providers/local/ondevice.js +129 -0
  25. package/lib/mobile/voice/providers/registry.js +277 -0
  26. package/lib/mobile/voice/routes.js +278 -0
  27. package/lib/mobile/voice/runtime.js +84 -0
  28. package/lib/mobile/voice/settings.js +206 -0
  29. package/lib/mobile/voice/stream.js +415 -0
  30. package/lib/mobile/voice/voice-provider.js +268 -0
  31. package/lib/panel/index.html +17 -17
  32. package/lib/routes/control-plane.js +19 -0
  33. package/lib/routes/mobile-api.js +33 -1
  34. package/lib/sidecar-facade-worker.cjs +1 -1
  35. package/package.json +13 -14
@@ -0,0 +1,508 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 内置词库:所有词都在**本机**生成,只把当次真正需要的几个热词交给 provider。
5
+ *
6
+ * 三层来源(`docs/voice-input-plan.md` 5.3):
7
+ * ① 工作区术语 —— 文件名 / 目录名 / 包名 / `package.json` 的 keywords / `AGENTS.md` 里
8
+ * 被反引号或首字母大写的专有名词。扫描只走到浅层、有上限,不读源码正文;
9
+ * ② 用户改错学习 —— App 上报的「听错 → 改对」映射,是唯一带真值的一层,优先级最高;
10
+ * ③ 当前会话最近消息的关键词 —— 只取最近几条,按出现次数挑,不把原句搬走。
11
+ *
12
+ * 三条约束写死在这里,不靠调用方自觉:
13
+ * - **绝不外传整份名单**:`hotwords` 有上限,`context` 是压缩过的提示串(长度另设上限),
14
+ * 原始消息、文件内容、源码一概不进返回值;
15
+ * - **去重**:三层合并后同一个词只出现一次,大小写不敏感;
16
+ * - **排序稳定**:分数相同时按长度、再按字典序,结果不随 `readdir` 顺序漂移 ——
17
+ * 否则同一段话每次生成的热词顺序不同,缓存和测试都稳不住。
18
+ *
19
+ * 语言判断不在这里做:中文词、英文标识符混在同一张表里,按 provider 的能力原样注入即可。
20
+ */
21
+
22
+ const fs = require('node:fs');
23
+ const path = require('node:path');
24
+
25
+ const DEFAULTS = {
26
+ maxHotwords: 40,
27
+ maxWorkspace: 24,
28
+ maxSession: 12,
29
+ maxUserDict: 12,
30
+ maxFiles: 300,
31
+ maxScanDepth: 2,
32
+ maxContextChars: 240,
33
+ minSessionCount: 2,
34
+ maxSessionMessages: 8,
35
+ maxHotwordChars: 32,
36
+ };
37
+
38
+ /** 扫描时整目录跳过的名字:词库用不上,扫进去只会把额度耗光。 */
39
+ const SKIP_DIRS = new Set([
40
+ 'node_modules', '.git', '.hg', '.svn', 'dist', 'build', 'out', 'coverage', '.next', '.nuxt',
41
+ '.cache', '.turbo', '.parcel-cache', 'vendor', 'Pods', '.idea', '.vscode', '__pycache__',
42
+ '.venv', 'venv', 'target', 'DerivedData', '.gradle', '.expo', 'tmp', 'temp',
43
+ ]);
44
+
45
+ /** 文件扩展名不是词,别让它们占热词额度。 */
46
+ const EXT_TOKENS = new Set([
47
+ 'js', 'ts', 'cjs', 'mjs', 'jsx', 'tsx', 'json', 'md', 'txt', 'yml', 'yaml', 'toml', 'ini',
48
+ 'css', 'scss', 'sass', 'less', 'html', 'htm', 'xml', 'svg', 'png', 'jpg', 'jpeg', 'gif', 'webp',
49
+ 'ico', 'lock', 'sh', 'bash', 'zsh', 'py', 'rb', 'go', 'rs', 'swift', 'kt', 'java', 'c', 'h',
50
+ 'cc', 'cpp', 'hpp', 'm', 'mm', 'gradle', 'plist', 'xcodeproj', 'bundle', 'keep', 'example',
51
+ ]);
52
+
53
+ /** 通用词:出现在文件名里不代表是这个项目的术语。 */
54
+ const GENERIC_WORDS = new Set([
55
+ 'index', 'main', 'src', 'lib', 'libs', 'test', 'tests', 'spec', 'specs', 'dist', 'build',
56
+ 'readme', 'license', 'licence', 'changelog', 'package', 'packages', 'config', 'configs',
57
+ 'utils', 'util', 'helper', 'helpers', 'common', 'core', 'types', 'type', 'interface', 'docs',
58
+ 'doc', 'scripts', 'script', 'assets', 'public', 'static', 'app', 'apps', 'ios', 'android',
59
+ 'mobile', 'the', 'and', 'for', 'with', 'from', 'this', 'that', 'these', 'those', 'your',
60
+ 'our', 'you', 'are', 'was', 'were', 'will', 'would', 'can', 'could', 'should', 'must', 'not',
61
+ 'into', 'onto', 'when', 'then', 'than', 'also', 'all', 'any', 'each', 'more', 'most', 'some',
62
+ 'only', 'other', 'others', 'use', 'used', 'using', 'via', 'per', 'one', 'two', 'new', 'old',
63
+ 'get', 'set', 'add', 'remove', 'update', 'make', 'done', 'step', 'steps', 'path', 'paths',
64
+ 'name', 'names', 'value', 'values', 'data', 'time', 'user', 'users', 'http', 'https', 'www',
65
+ 'com', 'org', 'net', 'io', 'dev', 'default', 'options', 'option', 'version', 'info', 'error',
66
+ 'errors', 'true', 'false', 'null', 'self', 'node', 'npm', 'pnpm', 'yarn', 'eslint', 'prettier',
67
+ 'tsconfig', 'gitignore', 'editorconfig', 'dockerfile', 'makefile', 'env', 'local', 'global',
68
+ 'agents', 'contributing', 'codeowners', 'authors', 'notice', 'faq',
69
+ 'server', 'client', 'api', 'apis', 'read', 'write', 'file', 'files', 'line', 'lines', 'list',
70
+ ]);
71
+
72
+ /** 会话关键词里过滤掉的口语词:它们出现次数最高,但一点信息量都没有。 */
73
+ const CJK_STOPWORDS = new Set([
74
+ '这个', '那个', '这些', '那些', '这里', '那里', '这样', '那样', '什么', '怎么', '为什么',
75
+ '然后', '就是', '所以', '但是', '因为', '而且', '还是', '或者', '如果', '已经', '现在',
76
+ '可以', '应该', '需要', '我们', '你们', '他们', '她们', '它们', '自己', '一下', '一点',
77
+ '时候', '问题', '东西', '地方', '可能', '开始', '继续', '不用', '不要', '没有', '不是',
78
+ '还有', '以及', '之后', '之前', '上面', '下面', '里面', '外面', '今天', '明天', '昨天',
79
+ ]);
80
+
81
+ /** 中文断词用的虚词/代词:会话里没有分词器,靠它们把长串切成候选词。 */
82
+ const CJK_SEPARATORS = /[的地得了是在和与就也都吧呢吗啊把被让给这那那我你他她它们]/;
83
+
84
+ const CAPITALIZED = /(?:^|[\s((「“"'*>-])([A-Z][A-Za-z0-9_.-]{2,})/g;
85
+ const BACKTICK = /`([^`\n]{1,40})`/g;
86
+
87
+ /** 合并用户传进来的上限,非法值一律回落到默认,别让 `NaN` 变成「不限」。 */
88
+ function mergeLimits(limits) {
89
+ const merged = { ...DEFAULTS };
90
+ if (!limits || typeof limits !== 'object') return merged;
91
+ for (const key of Object.keys(DEFAULTS)) {
92
+ const value = limits[key];
93
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) merged[key] = Math.floor(value);
94
+ }
95
+ return merged;
96
+ }
97
+
98
+ /** 一个候选词值不值得进词库:长度、字符集、占位符都过一遍。 */
99
+ function usableTerm(term, limits) {
100
+ if (typeof term !== 'string') return false;
101
+ const trimmed = term.trim().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');
102
+ if (!trimmed || trimmed.length > limits.maxHotwordChars) return false;
103
+ if (!/[\p{L}]/u.test(trimmed)) return false;
104
+ if (/^[\d\s._-]+$/.test(trimmed)) return false;
105
+ if (/^[\d.]+$/.test(trimmed)) return false;
106
+ return true;
107
+ }
108
+
109
+ /** CJK 串按虚词切段,丢掉单字和通用词。 */
110
+ function cjkSegments(text) {
111
+ const out = [];
112
+ for (const run of text.match(/[\u3400-\u4dbf\u4e00-\u9fff]{2,}/g) || []) {
113
+ for (const piece of run.split(CJK_SEPARATORS)) {
114
+ if (piece.length >= 2 && piece.length <= 8 && !CJK_STOPWORDS.has(piece)) out.push(piece);
115
+ }
116
+ }
117
+ return out;
118
+ }
119
+
120
+ /** 拉丁标识符切词:驼峰、下划线、连字符、点都拆开;整词本身也有价值(`dsh-relay`)。 */
121
+ function latinTokens(text) {
122
+ const tokens = [];
123
+ for (const raw of text.match(/[A-Za-z][A-Za-z0-9_.-]*/g) || []) {
124
+ const words = raw.split(/[._-]+/).filter(Boolean);
125
+ if (words.length > 1) tokens.push(raw.replace(/^[._-]+|[._-]+$/g, ''));
126
+ for (const word of words) {
127
+ const split = word
128
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
129
+ .split(/\s+/)
130
+ .filter(Boolean);
131
+ tokens.push(...split);
132
+ }
133
+ }
134
+ return tokens.filter((token) => token.length >= 3 && !EXT_TOKENS.has(token.toLowerCase())
135
+ && !GENERIC_WORDS.has(token.toLowerCase()) && !/^\d+$/.test(token));
136
+ }
137
+
138
+ /** 读文本,读不到就当没有 —— 词库是锦上添花,不能因为少一个文件就抛错。 */
139
+ function readText(file) {
140
+ try {
141
+ return fs.readFileSync(file, 'utf8');
142
+ } catch {
143
+ return '';
144
+ }
145
+ }
146
+
147
+ /** 浅层列目录:深度、条数都有上限,跳过大目录。返回 `{ name, dir }`。 */
148
+ function scanWorkspace(cwd, limits) {
149
+ const entries = [];
150
+ const walk = (dir, depth) => {
151
+ if (entries.length >= limits.maxFiles || depth > limits.maxScanDepth) return;
152
+ let items;
153
+ try {
154
+ items = fs.readdirSync(dir, { withFileTypes: true });
155
+ } catch {
156
+ return;
157
+ }
158
+ items.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
159
+ for (const item of items) {
160
+ if (entries.length >= limits.maxFiles) return;
161
+ if (item.name.startsWith('.')) continue;
162
+ if (item.isDirectory()) {
163
+ if (SKIP_DIRS.has(item.name)) continue;
164
+ entries.push({ name: item.name, dir: true });
165
+ walk(path.join(dir, item.name), depth + 1);
166
+ } else if (item.isFile()) {
167
+ entries.push({ name: item.name, dir: false });
168
+ }
169
+ }
170
+ };
171
+ walk(cwd, 0);
172
+ return entries;
173
+ }
174
+
175
+ /**
176
+ * 工作区术语:文件/目录名、包名、keywords、`AGENTS.md` 里的专有名词。
177
+ * 分数只用于排序,口径是「越像专有名词分越高」:包名 > AGENTS.md 反引号 > 文件名复合词 > 单词。
178
+ */
179
+ function workspaceTerms({ cwd, files, limits }) {
180
+ const scores = new Map();
181
+ const bump = (term, score) => {
182
+ if (!usableTerm(term, limits)) return;
183
+ const key = term.toLowerCase();
184
+ const current = scores.get(key);
185
+ if (current) current.score += score;
186
+ else scores.set(key, { term: term.trim(), score });
187
+ };
188
+
189
+ const names = Array.isArray(files) && files.length
190
+ ? files.map((entry) => {
191
+ const raw = typeof entry === 'string' ? entry : entry && (entry.path || entry.name);
192
+ if (typeof raw !== 'string' || !raw) return null;
193
+ const base = path.basename(raw);
194
+ return base ? { name: base, dir: false } : null;
195
+ }).filter(Boolean)
196
+ : cwd ? scanWorkspace(cwd, limits) : [];
197
+
198
+ for (const entry of names) {
199
+ const stem = entry.dir ? entry.name : entry.name.replace(/\.[^.]+$/, '');
200
+ for (const token of latinTokens(stem)) bump(token, 1);
201
+ for (const segment of cjkSegments(stem)) bump(segment, 1);
202
+ // `voice-input-contract` 这种复合名整词保留:热词里它比拆开的三个单词更有用。
203
+ if (/[-_.]/.test(stem) && stem.length >= 4) bump(stem, 2);
204
+ }
205
+
206
+ if (cwd) {
207
+ const pkgText = readText(path.join(cwd, 'package.json'));
208
+ if (pkgText) {
209
+ try {
210
+ const pkg = JSON.parse(pkgText);
211
+ if (typeof pkg.name === 'string') {
212
+ const bare = pkg.name.replace(/^@[^/]+\//, '');
213
+ bump(bare, 6);
214
+ for (const token of latinTokens(bare)) bump(token, 3);
215
+ const scope = /^@([^/]+)\//.exec(pkg.name);
216
+ if (scope) bump(scope[1], 4);
217
+ }
218
+ if (Array.isArray(pkg.keywords)) {
219
+ for (const keyword of pkg.keywords) {
220
+ if (typeof keyword === 'string') bump(keyword, 4);
221
+ }
222
+ }
223
+ } catch {
224
+ // package.json 坏了不拦词库生成。
225
+ }
226
+ }
227
+
228
+ const agents = readText(path.join(cwd, 'AGENTS.md'));
229
+ if (agents) {
230
+ for (const match of agents.matchAll(BACKTICK)) {
231
+ const value = match[1].trim();
232
+ if (/[\u3400-\u4dbf\u4e00-\u9fff]/.test(value)) bump(value, 5);
233
+ else if (/^[A-Za-z][A-Za-z0-9_.-]{2,}$/.test(value)) bump(value, 5);
234
+ }
235
+ for (const match of agents.matchAll(CAPITALIZED)) {
236
+ const word = match[1].replace(/[._-]+$/, '');
237
+ if (!GENERIC_WORDS.has(word.toLowerCase())) bump(word, 3);
238
+ }
239
+ }
240
+ }
241
+
242
+ return [...scores.values()]
243
+ .sort((a, b) => b.score - a.score
244
+ || b.term.length - a.term.length
245
+ || (a.term.toLowerCase() < b.term.toLowerCase() ? -1 : a.term.toLowerCase() > b.term.toLowerCase() ? 1 : 0))
246
+ .map((item) => item.term);
247
+ }
248
+
249
+ /** 会话消息归一:字符串、`{content}`、`{text}`、内容分段数组都认,取最后一小段。 */
250
+ function messageText(message) {
251
+ if (typeof message === 'string') return message;
252
+ if (!message || typeof message !== 'object') return '';
253
+ const content = message.content !== undefined ? message.content : message.text;
254
+ if (typeof content === 'string') return content;
255
+ if (Array.isArray(content)) {
256
+ return content
257
+ .map((part) => (typeof part === 'string' ? part : part && typeof part.text === 'string' ? part.text : ''))
258
+ .filter(Boolean)
259
+ .join('\n');
260
+ }
261
+ return '';
262
+ }
263
+
264
+ /**
265
+ * 会话关键词:在最近几条消息里出现 ≥ `minSessionCount` 次的候选词。
266
+ * 只留词,不留句 —— 上下文提示可以送 provider,原话不行。
267
+ */
268
+ function sessionTerms(sessionMessages, limits) {
269
+ if (!Array.isArray(sessionMessages) || !sessionMessages.length) return [];
270
+ const texts = sessionMessages
271
+ .map(messageText)
272
+ .filter(Boolean)
273
+ .slice(-limits.maxSessionMessages);
274
+
275
+ const counts = new Map();
276
+ const bump = (term) => {
277
+ if (!usableTerm(term, limits)) return;
278
+ const key = term.toLowerCase();
279
+ const current = counts.get(key);
280
+ if (current) current.count += 1;
281
+ else counts.set(key, { term, count: 1 });
282
+ };
283
+ for (const text of texts) {
284
+ for (const segment of cjkSegments(text)) bump(segment);
285
+ for (const token of latinTokens(text)) bump(token);
286
+ }
287
+
288
+ return [...counts.values()]
289
+ .filter((item) => item.count >= limits.minSessionCount)
290
+ .sort((a, b) => b.count - a.count
291
+ || b.term.length - a.term.length
292
+ || (a.term.toLowerCase() < b.term.toLowerCase() ? -1 : a.term.toLowerCase() > b.term.toLowerCase() ? 1 : 0))
293
+ .map((item) => item.term);
294
+ }
295
+
296
+ /**
297
+ * 归一用户词库:接受 `[{heard, corrected}]`、`[{from, to}]`、`[{raw, fixed}]` 或 `{听错: 改对}` 映射。
298
+ * 输出统一形状,后续层只认这一种。
299
+ */
300
+ function normalizeUserDict(userDict, limits) {
301
+ const pairs = [];
302
+ const add = (heard, corrected) => {
303
+ if (typeof heard !== 'string' || typeof corrected !== 'string') return;
304
+ const from = heard.trim();
305
+ const to = corrected.trim();
306
+ if (!from || !to || from === to) return;
307
+ if (from.length > limits.maxHotwordChars || to.length > limits.maxHotwordChars) return;
308
+ pairs.push({ heard: from, corrected: to, weight: 1 });
309
+ };
310
+ if (Array.isArray(userDict)) {
311
+ for (const entry of userDict) {
312
+ if (!entry || typeof entry !== 'object') continue;
313
+ add(entry.heard !== undefined ? entry.heard : entry.from !== undefined ? entry.from : entry.raw,
314
+ entry.corrected !== undefined ? entry.corrected : entry.to !== undefined ? entry.to : entry.fixed);
315
+ }
316
+ } else if (userDict && typeof userDict === 'object') {
317
+ for (const [heard, corrected] of Object.entries(userDict)) add(heard, corrected);
318
+ }
319
+ const seen = new Set();
320
+ return pairs.filter((pair) => {
321
+ const key = `${pair.heard}\u0000${pair.corrected}`;
322
+ if (seen.has(key)) return false;
323
+ seen.add(key);
324
+ return true;
325
+ }).slice(0, limits.maxUserDict);
326
+ }
327
+
328
+ /** 上下文提示串:只放工作区名和几个词,按长度预算挑词,超出的词整条不进(不切半个词)。 */
329
+ function buildContext(cwd, terms, limits) {
330
+ const head = typeof cwd === 'string' && cwd ? `工作区 ${path.basename(cwd)}` : '';
331
+ const picked = [];
332
+ const render = (list) => {
333
+ const parts = [];
334
+ if (head) parts.push(head);
335
+ if (list.length) parts.push(`常用词 ${list.join('、')}`);
336
+ return parts.join(';');
337
+ };
338
+ for (const term of terms) {
339
+ if (render([...picked, term]).length > limits.maxContextChars) break;
340
+ picked.push(term);
341
+ }
342
+ return render(picked);
343
+ }
344
+
345
+ /**
346
+ * 生成词库。
347
+ *
348
+ * @param {{cwd?:string, files?:string[], sessionMessages?:Array, userDict?:Array|object,
349
+ * limits?:object}} [input]
350
+ * @returns {{hotwords:string[], context:string, corrections:Array<{heard:string,corrected:string,weight:number}>}}
351
+ * `corrections` 是归一后的用户改错映射,后处理直接拿去做术语纠正(不占热词额度)。
352
+ */
353
+ function buildLexicon(input = {}) {
354
+ const limits = mergeLimits(input.limits);
355
+ const corrections = normalizeUserDict(input.userDict, limits);
356
+ const learned = corrections.map((pair) => pair.corrected);
357
+
358
+ const workspace = workspaceTerms({
359
+ cwd: typeof input.cwd === 'string' ? input.cwd : '',
360
+ files: Array.isArray(input.files) ? input.files : [],
361
+ limits,
362
+ });
363
+ const session = sessionTerms(input.sessionMessages, limits);
364
+
365
+ // 优先级:用户改错学到的是真值 > 工作区专有名词 > 近期话题。合并后大小写不敏感去重。
366
+ const hotwords = [];
367
+ const seen = new Set();
368
+ const push = (term) => {
369
+ if (!usableTerm(term, limits)) return;
370
+ const key = term.toLowerCase();
371
+ if (seen.has(key)) return;
372
+ seen.add(key);
373
+ hotwords.push(term.trim());
374
+ };
375
+ for (const term of learned) push(term);
376
+ for (const term of workspace.slice(0, limits.maxWorkspace)) push(term);
377
+ for (const term of session.slice(0, limits.maxSession)) push(term);
378
+
379
+ const contextTerms = [...hotwords];
380
+ return {
381
+ hotwords: hotwords.slice(0, limits.maxHotwords),
382
+ context: buildContext(input.cwd, contextTerms.slice(0, limits.maxWorkspace), limits),
383
+ corrections,
384
+ };
385
+ }
386
+
387
+ /**
388
+ * 从一次「听错 → 用户改成什么」里学出映射,供调用方自己落盘(本函数不写文件)。
389
+ *
390
+ * 只学**同一句里小段替换**的情况:两段文字相似度(公共前后缀之外)太低就是整句重写,
391
+ * 学进去只会把用户正常的改写当成听错。单字差异不落成单字映射 —— 单字替换命中率太高,
392
+ * 下次会把正常文本改坏;拉丁词扩到整词,中文取错字旁边的一个字凑成两字窗口。
393
+ *
394
+ * @param {string} previous 识别原文
395
+ * @param {string} correction 用户改定后的文本
396
+ * @param {{maxPairs?:number, now?:string|number}} [options]
397
+ * @returns {Array<{heard:string, corrected:string, lang:string, weight:number, at?:string|number}>}
398
+ */
399
+ function learnCorrection(previous, correction, options = {}) {
400
+ if (typeof previous !== 'string' || typeof correction !== 'string') return [];
401
+ const before = previous.trim();
402
+ const after = correction.trim();
403
+ if (!before || !after || before === after) return [];
404
+ const maxPairs = Number.isFinite(options.maxPairs) && options.maxPairs > 0
405
+ ? Math.floor(options.maxPairs)
406
+ : 5;
407
+
408
+ /** 一句内的差异段:公共前缀 + 公共后缀之外的那截。 */
409
+ const diffPair = (from, to) => {
410
+ if (from === to) return null;
411
+ let prefix = 0;
412
+ while (prefix < from.length && prefix < to.length && from[prefix] === to[prefix]) prefix += 1;
413
+ let suffix = 0;
414
+ while (suffix < from.length - prefix && suffix < to.length - prefix
415
+ && from[from.length - 1 - suffix] === to[to.length - 1 - suffix]) suffix += 1;
416
+ return {
417
+ prefix,
418
+ suffix,
419
+ heard: from.slice(prefix, from.length - suffix),
420
+ corrected: to.slice(prefix, to.length - suffix),
421
+ };
422
+ };
423
+
424
+ const pairs = [];
425
+
426
+ /** 两句差得太多就是正常改写,不是听错 —— 学进去会拿用户的改写去改以后的正常文本。 */
427
+ const plausible = (from, to) => {
428
+ const pair = diffPair(from, to);
429
+ if (!pair) return false;
430
+ const common = pair.prefix + pair.suffix;
431
+ return common / Math.max(from.length, to.length) >= 0.6;
432
+ };
433
+
434
+ /** 差异落在拉丁单词里就扩到整词(`gatewai` → `gateway`),中文没有词边界,另走上下文窗口。 */
435
+ const expandLatinWord = (value, start, end) => {
436
+ const isWordChar = (ch) => /[A-Za-z0-9_.-]/.test(ch);
437
+ let left = start;
438
+ let right = end;
439
+ while (left > 0 && isWordChar(value[left - 1])) left -= 1;
440
+ while (right < value.length && isWordChar(value[right])) right += 1;
441
+ return [left, right];
442
+ };
443
+
444
+ const take = (from, to) => {
445
+ const pair = diffPair(from, to);
446
+ if (!pair) return;
447
+ if (!plausible(from, to)) return;
448
+ let heard = pair.heard.trim();
449
+ let corrected = pair.corrected.trim();
450
+ const diffStart = pair.prefix;
451
+ const diffEnd = from.length - pair.suffix;
452
+ // 只差一个字(「网管」被听成「网关」的典型情形)时,单字映射会把所有用到这个字的词改坏,
453
+ // 必须带上上下文:拉丁词扩到整词;中文取「前一个字 + 错字」这个两字窗口(词首则取「错字 + 后一个字」)。
454
+ if (heard.length === 1) {
455
+ if (/[A-Za-z0-9]/.test(pair.heard) || /[A-Za-z0-9]/.test(pair.corrected)) {
456
+ const [fromLeft, fromRight] = expandLatinWord(from, diffStart, diffEnd);
457
+ const [toLeft, toRight] = expandLatinWord(to, diffStart, diffEnd);
458
+ heard = from.slice(fromLeft, fromRight).trim();
459
+ corrected = to.slice(toLeft, toRight).trim();
460
+ } else if (pair.prefix > 0) {
461
+ heard = from.slice(pair.prefix - 1, pair.prefix + 1).trim();
462
+ corrected = to.slice(pair.prefix - 1, pair.prefix + 1).trim();
463
+ } else if (pair.suffix > 0) {
464
+ heard = from.slice(0, 2).trim();
465
+ corrected = to.slice(0, 2).trim();
466
+ }
467
+ }
468
+ if (heard.length < 2 || heard.length > 12) return;
469
+ if (corrected.length < 1 || corrected.length > 32) return;
470
+ if (/^[\s\p{P}\p{S}]+$/u.test(heard) || /^[\s\p{P}\p{S}]+$/u.test(corrected)) return;
471
+ if (pairs.some((item) => item.heard === heard && item.corrected === corrected)) return;
472
+ pairs.push({ heard, corrected });
473
+ };
474
+
475
+ const fromSentences = splitSentencesSafe(before);
476
+ const toSentences = splitSentencesSafe(after);
477
+ if (fromSentences.length === toSentences.length && fromSentences.length > 1) {
478
+ for (let i = 0; i < fromSentences.length && pairs.length < maxPairs; i += 1) {
479
+ take(fromSentences[i], toSentences[i]);
480
+ }
481
+ } else {
482
+ take(before, after);
483
+ }
484
+
485
+ // 语言标记只用于落盘时分类,不影响纠正;按「改对」那个词本身判。
486
+ const langOf = (value) => {
487
+ if (/[\u3040-\u30ff]/.test(value)) return 'ja';
488
+ if (/[\uac00-\ud7af]/.test(value)) return 'ko';
489
+ if (/[\u4e00-\u9fff]/.test(value)) return 'zh';
490
+ return 'en';
491
+ };
492
+ return pairs.slice(0, maxPairs).map((pair) => {
493
+ const entry = { heard: pair.heard, corrected: pair.corrected, lang: langOf(pair.corrected), weight: 1 };
494
+ if (options.now !== undefined) entry.at = options.now;
495
+ return entry;
496
+ });
497
+ }
498
+
499
+ /** 学改错时不想为断句再引一次 lang.js 的完整逻辑,这里只要「按句对齐」。 */
500
+ function splitSentencesSafe(text) {
501
+ const pieces = text.match(/[^。!?!?;;\n]+[。!?!?;;\n]?/g) || [];
502
+ return pieces.map((piece) => piece.trim()).filter(Boolean);
503
+ }
504
+
505
+ module.exports = {
506
+ buildLexicon,
507
+ learnCorrection,
508
+ };
@@ -0,0 +1,88 @@
1
+ // 2026-11-28:插件面板「语音」页的本机接口——provider 列表 / 默认项 / 填 key / 限额用量。
2
+ 'use strict';
3
+
4
+ /**
5
+ * 面板(本机浏览器)用的语音配置接口:`GET|POST /api/relay/voice/config`。
6
+ *
7
+ * 手机的移动 API 只有能力表与识别入口,**不碰配置**;provider 选择与各家 key 全留在电脑上
8
+ * (契约 §5:App 不得出现任何厂商配置项)。这条挂在控制面前缀下,注册在
9
+ * `lib/routes/control-plane.js` 并套那里的 `localOnly` —— 与其它面板接口同一档来源限制
10
+ * (拒绝经中转 / 局域网代理转发来的请求),不在本文件里另写一份判定。
11
+ *
12
+ * 安全口径:
13
+ * - secret 字段只回 `set: true/false`,原文不出电脑(`providerConfigView` 里做掉);
14
+ * - POST 只收声明过的字段(`pickConfig`),不认字段名就是丢弃,不往配置里写任意键;
15
+ * - 不提供「读某家的 key」这条路 —— 面板不需要回显,用户要换就是整段重填。
16
+ */
17
+
18
+ const { sendJson, readJsonBody } = require('../../shared/http-util.js');
19
+ const { voiceGatewayFor, noteContext } = require('./runtime.js');
20
+ const { PROVIDER_STATUS } = require('./voice-provider.js');
21
+
22
+ function log(...args) {
23
+ try { console.warn('[dsh-mobile-plugin] [voice]', ...args) } catch { /* 日志不反噬 */ }
24
+ }
25
+
26
+ /** 一次 POST 的字段上限:面板就那几个输入框,超过这个数一定是构造出来的包。 */
27
+ const MAX_PANEL_BODY = 64 * 1024;
28
+
29
+ /**
30
+ * POST 体:`{ enabled?, default?, provider?, config? }`,可只带其中一部分。
31
+ * 返回归一后的补丁;有非法项就回 400(面板知道自己在提交什么,静默忽略会让人以为存上了)。
32
+ */
33
+ function normalizePatch(body) {
34
+ const patch = {};
35
+ if (body && typeof body.enabled === 'boolean') patch.enabled = body.enabled;
36
+ if (body && typeof body.default === 'string') patch.default = body.default.trim();
37
+ if (body && typeof body.provider === 'string') patch.provider = body.provider.trim();
38
+ if (body && body.config !== undefined) {
39
+ if (body.config === null || typeof body.config !== 'object' || Array.isArray(body.config)) {
40
+ return { error: 'config 必须是对象' };
41
+ }
42
+ patch.config = body.config;
43
+ }
44
+ return { patch };
45
+ }
46
+
47
+ /**
48
+ * 本机面板的语音配置。
49
+ *
50
+ * @param {object} ctx 插件 ctx(host provider 要问宿主的 speechToText)
51
+ * @param {object} req
52
+ * @param {object} res
53
+ */
54
+ async function handleVoicePanelConfig(ctx, req, res) {
55
+ noteContext(ctx);
56
+ try {
57
+ const gateway = voiceGatewayFor(ctx);
58
+
59
+ if (String(req.method || 'GET').toUpperCase() === 'GET') {
60
+ return sendJson(res, 200, gateway.panelView());
61
+ }
62
+
63
+ const body = await readJsonBody(req, MAX_PANEL_BODY);
64
+ const { patch, error } = normalizePatch(body);
65
+ if (error) return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: error } });
66
+
67
+ if (patch.enabled !== undefined) gateway.setEnabled(patch.enabled);
68
+ if (patch.default !== undefined && patch.default) gateway.setDefault(patch.default);
69
+ if (patch.provider !== undefined && patch.provider) {
70
+ // config 跟着 provider 一起提交:面板一次只改「当前选中的那家」。
71
+ if (patch.config !== undefined) gateway.setProviderConfig(patch.provider, patch.config);
72
+ } else if (patch.config !== undefined) {
73
+ return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '改配置要带 provider' } });
74
+ }
75
+ return sendJson(res, 200, gateway.panelView());
76
+ } catch (error) {
77
+ // 宿主 web 服务器对 handler 抛错只回一个没有正文的 400(见 control-plane.js 里同一处
78
+ // 教训)。这里自己兜住:把原因转成 JSON 回给面板,日志里留一条,别让整页变成空白 400。
79
+ const code = error && error.code === 'voice-provider-missing' ? 'voice-provider-missing' : 'voice-failed';
80
+ log('语音面板配置口失败:', error && error.message ? error.message : error);
81
+ return sendJson(res, code === 'voice-provider-missing' ? 404 : 500, {
82
+ ok: false,
83
+ error: { code, message: error && error.message ? error.message : '保存失败' },
84
+ });
85
+ }
86
+ }
87
+
88
+ module.exports = { handleVoicePanelConfig, normalizePatch, MAX_PANEL_BODY, PROVIDER_STATUS };