dsh-mobile-plugin 0.5.138 → 0.5.140
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/config/agent-presets/standard/skills/dsh-mobile-kb/references/pairing.md +2 -2
- package/lib/impl.js +8 -5
- package/lib/mobile/permissions.js +10 -0
- package/lib/mobile/session-step.js +17 -11
- package/lib/mobile/voice/frames.js +198 -0
- package/lib/mobile/voice/gateway.js +746 -0
- package/lib/mobile/voice/lang.js +347 -0
- package/lib/mobile/voice/lexicon-store.js +189 -0
- package/lib/mobile/voice/lexicon.js +508 -0
- package/lib/mobile/voice/panel-api.js +88 -0
- package/lib/mobile/voice/postprocess.js +551 -0
- package/lib/mobile/voice/protocol.js +306 -0
- package/lib/mobile/voice/providers/cn/aliyun.js +401 -0
- package/lib/mobile/voice/providers/cn/tencent.js +402 -0
- package/lib/mobile/voice/providers/cn/volc.js +328 -0
- package/lib/mobile/voice/providers/cn/xfyun.js +290 -0
- package/lib/mobile/voice/providers/host.js +190 -0
- package/lib/mobile/voice/providers/intl/_common.js +346 -0
- package/lib/mobile/voice/providers/intl/assemblyai.js +353 -0
- package/lib/mobile/voice/providers/intl/azure.js +444 -0
- package/lib/mobile/voice/providers/intl/deepgram.js +366 -0
- package/lib/mobile/voice/providers/intl/openai.js +389 -0
- package/lib/mobile/voice/providers/intl/speechmatics.js +405 -0
- package/lib/mobile/voice/providers/local/ondevice.js +129 -0
- package/lib/mobile/voice/providers/registry.js +277 -0
- package/lib/mobile/voice/routes.js +278 -0
- package/lib/mobile/voice/runtime.js +84 -0
- package/lib/mobile/voice/settings.js +206 -0
- package/lib/mobile/voice/stream.js +415 -0
- package/lib/mobile/voice/voice-provider.js +268 -0
- package/lib/panel/index.html +17 -17
- package/lib/routes/control-plane.js +19 -0
- package/lib/routes/mobile-api.js +33 -1
- package/lib/sidecar-facade-worker.cjs +1 -1
- package/lib/zeronews/runner.cjs +7 -4
- package/lib/zeronews/wiring.cjs +36 -43
- package/package.json +14 -15
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
// 2026-11-29:端侧离线撤掉,只读 provider 目录清空(能力表 / 面板不再列本机离线)。
|
|
2
|
+
// 2026-11-28:语音 provider 注册表——扫描 cn/intl 适配器目录 + 内置 host,算出能力表与默认项。
|
|
3
|
+
// 2026-11-28:local/** 以只读能力条目进能力表(不进可用项 / 默认项 / 调用路径)。
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* provider 注册表:**发现**(扫目录)、**校验**(丢掉不合格的)、**判状态**(已配置 / 可用)。
|
|
8
|
+
*
|
|
9
|
+
* 目录约定(`docs/voice-input-contract.md` §1):
|
|
10
|
+
* - `providers/cn/**`:国内厂商,国内组负责;
|
|
11
|
+
* - `providers/intl/**`:国外厂商,国外组负责;
|
|
12
|
+
* - 加上内置的 `host`(委托宿主语音包)与 `local/**`(端侧模型):后者是**只读条目**,
|
|
13
|
+
* 只在能力表 / 面板里显示「手机上有这条能力」,不参与网关的 provider 选择。
|
|
14
|
+
*
|
|
15
|
+
* 为什么扫描目录而不是逐个 `require` 文件名:两组适配器是并行开发的,谁先落地、落地几个
|
|
16
|
+
* 都不该让网关改代码;扫描 + 校验的组合能让「文件还没来」= 能力表里少一行,而不是启动就崩。
|
|
17
|
+
* 扫描顺序按文件名字典序(Node 的 readdir 顺序依文件系统而变,不排序会让能力表每次启动
|
|
18
|
+
* 顺序都不同,App 那边的「上次选的 provider」就可能漂)。
|
|
19
|
+
*
|
|
20
|
+
* 每个适配器各是一个文件、`module.exports = provider 对象`;`index.js` / 以 `_` 开头的文件
|
|
21
|
+
* 不算适配器(按 Node 的惯用约定当私有模块)。
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const fs = require('node:fs');
|
|
25
|
+
const path = require('node:path');
|
|
26
|
+
|
|
27
|
+
const { validateProvider, capabilityOf, statusOf, PROVIDER_STATUS } = require('../voice-provider.js');
|
|
28
|
+
const { createHostBridge, createHostProvider } = require('./host.js');
|
|
29
|
+
|
|
30
|
+
const PROVIDER_DIRS = Object.freeze(['cn', 'intl']);
|
|
31
|
+
/**
|
|
32
|
+
* 只读目录:里面的适配器必须自带 `capabilityOnly: true` 才收,且只出现在能力表 / 面板里。
|
|
33
|
+
* 端侧识别跑在手机上,插件这侧没有可调用的执行体;放进 `PROVIDER_DIRS` 会让它变成可选项,
|
|
34
|
+
* 网关就会去「调用」一个不存在的远端。
|
|
35
|
+
*/
|
|
36
|
+
// 2026-11-29:端侧离线识别撤掉,能力表 / 面板不再列本机离线这条只读 provider。
|
|
37
|
+
const READONLY_DIRS = Object.freeze([]);
|
|
38
|
+
const PROVIDERS_ROOT = __dirname;
|
|
39
|
+
|
|
40
|
+
/** 某个目录里像适配器的文件名(排序后)。目录不存在回空数组——「还没人落地」不是错误。 */
|
|
41
|
+
function adapterFilesIn(dir) {
|
|
42
|
+
let names;
|
|
43
|
+
try {
|
|
44
|
+
names = fs.readdirSync(dir, { withFileTypes: true });
|
|
45
|
+
} catch {
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
return names
|
|
49
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith('.js') && !entry.name.startsWith('_') && entry.name !== 'index.js')
|
|
50
|
+
.map((entry) => entry.name)
|
|
51
|
+
.sort();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 扫一个目录并加载适配器。
|
|
56
|
+
*
|
|
57
|
+
* 单个文件 require 抛错只记一行日志、跳过那个文件:并行开发时那份可能正在写,半个文件
|
|
58
|
+
* 不该让整张能力表消失。require 缓存是正常的(同一进程里多次建网关不需要重读磁盘)。
|
|
59
|
+
*
|
|
60
|
+
* @returns {Array<object>} 已经通过形状校验的适配器
|
|
61
|
+
*/
|
|
62
|
+
function scanProviderDirectory(dir, log = () => {}) {
|
|
63
|
+
const out = [];
|
|
64
|
+
for (const name of adapterFilesIn(dir)) {
|
|
65
|
+
const full = path.join(dir, name);
|
|
66
|
+
let def;
|
|
67
|
+
try {
|
|
68
|
+
def = require(full);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
log(`语音:适配器 ${path.relative(PROVIDERS_ROOT, full)} 加载失败`, error && error.message ? error.message : error);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
const check = validateProvider(def);
|
|
74
|
+
if (!check.ok) {
|
|
75
|
+
log(`语音:适配器 ${path.relative(PROVIDERS_ROOT, full)} 形状不合格`, check.errors.join(';'));
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (out.some((item) => item.id === def.id)) {
|
|
79
|
+
log(`语音:适配器 ${def.id} 重复,后者被忽略`);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
out.push(def);
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 扫描全部适配器目录,返回数组(不含 host)。
|
|
89
|
+
* `root` 只给测试指到临时目录;生产就是本文件所在的 `providers/`。
|
|
90
|
+
*/
|
|
91
|
+
function loadAdapterProviders(options = {}) {
|
|
92
|
+
const root = typeof options.root === 'string' && options.root ? options.root : PROVIDERS_ROOT;
|
|
93
|
+
const dirs = Array.isArray(options.dirs) ? options.dirs : PROVIDER_DIRS;
|
|
94
|
+
const log = typeof options.log === 'function' ? options.log : () => {};
|
|
95
|
+
const out = [];
|
|
96
|
+
for (const dir of dirs) {
|
|
97
|
+
for (const def of scanProviderDirectory(path.join(root, dir), log)) {
|
|
98
|
+
if (out.some((item) => item.id === def.id)) {
|
|
99
|
+
log(`语音:适配器 ${def.id} 在多个目录里重复,只保留先扫到的那份`);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
out.push(def);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 扫只读目录,返回**只**带 `capabilityOnly: true` 的适配器。
|
|
110
|
+
*
|
|
111
|
+
* 没标这一位的文件直接跳过并记一行日志:本地目录以后可能放真正的手机端执行适配器,但把
|
|
112
|
+
* 一个没声明「只读」的东西塞进能力表会让 App 以为电脑能调用它。`root` 只给测试用。
|
|
113
|
+
*/
|
|
114
|
+
function loadReadonlyProviders(options = {}) {
|
|
115
|
+
const root = typeof options.root === 'string' && options.root ? options.root : PROVIDERS_ROOT;
|
|
116
|
+
const dirs = Array.isArray(options.dirs) ? options.dirs : READONLY_DIRS;
|
|
117
|
+
const log = typeof options.log === 'function' ? options.log : () => {};
|
|
118
|
+
const out = [];
|
|
119
|
+
for (const dir of dirs) {
|
|
120
|
+
for (const def of scanProviderDirectory(path.join(root, dir), log)) {
|
|
121
|
+
if (def.capabilityOnly !== true) {
|
|
122
|
+
log(`语音:只读目录里的适配器 ${def.id} 没标 capabilityOnly,按可调用条目处理会更危险,跳过`);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (out.some((item) => item.id === def.id)) {
|
|
126
|
+
log(`语音:只读适配器 ${def.id} 重复,后者被忽略`);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
out.push(def);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 建注册表。
|
|
137
|
+
*
|
|
138
|
+
* @param {object} options
|
|
139
|
+
* @param {object} [options.ctx] 插件 ctx:host 适配器靠它取 `ctx.speechToText`
|
|
140
|
+
* @param {{ configFor: (id: string) => object, defaultProvider: () => string }} options.store 配置存储
|
|
141
|
+
* @param {Array<object>} [options.providers] 直接给定适配器(测试用,跳过目录扫描)
|
|
142
|
+
* @param {object} [options.hostProvider] 直接给定 host 适配器(测试用)
|
|
143
|
+
* @param {() => void} [options.log]
|
|
144
|
+
*/
|
|
145
|
+
function createProviderRegistry(options = {}) {
|
|
146
|
+
const store = options.store;
|
|
147
|
+
const log = typeof options.log === 'function' ? options.log : () => {};
|
|
148
|
+
const injected = Array.isArray(options.providers) ? options.providers : null;
|
|
149
|
+
let providers = null;
|
|
150
|
+
let readonlyProviders = null;
|
|
151
|
+
let host = options.hostProvider || null;
|
|
152
|
+
|
|
153
|
+
/** 懒加载:第一次问能力时才扫目录(插件启动路径上不做磁盘枚举)。 */
|
|
154
|
+
function ensure() {
|
|
155
|
+
if (providers) return providers;
|
|
156
|
+
if (!host) host = createHostProvider(createHostBridge(options.ctx, log));
|
|
157
|
+
const prepared = [];
|
|
158
|
+
for (const def of injected || loadAdapterProviders({ log })) {
|
|
159
|
+
const check = validateProvider(def);
|
|
160
|
+
if (!check.ok) { log(`语音:注入的适配器 ${def && def.id} 形状不合格`, check.errors.join(';')); continue; }
|
|
161
|
+
if (prepared.some((item) => item.id === def.id)) { log(`语音:适配器 ${def.id} 重复,后者被忽略`); continue; }
|
|
162
|
+
prepared.push(def);
|
|
163
|
+
}
|
|
164
|
+
// host 永远排第一:它是「零配置开箱可用」的那一家,也是缺省项。
|
|
165
|
+
providers = [host, ...prepared];
|
|
166
|
+
return providers;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* 只读条目(端侧能力等):能力表 / 面板要显示,但**不进** `get()` 的可用项选择。
|
|
171
|
+
* 与 `ensure()` 分开加载,免得一次磁盘枚举把「可调用」和「只显示」混成一张表。
|
|
172
|
+
*/
|
|
173
|
+
function ensureReadonly() {
|
|
174
|
+
if (readonlyProviders) return readonlyProviders;
|
|
175
|
+
const injectedReadonly = Array.isArray(options.readonlyProviders) ? options.readonlyProviders : null;
|
|
176
|
+
readonlyProviders = [];
|
|
177
|
+
for (const def of injectedReadonly || loadReadonlyProviders({ log })) {
|
|
178
|
+
const check = validateProvider(def);
|
|
179
|
+
if (!check.ok) { log(`语音:只读适配器 ${def && def.id} 形状不合格`, check.errors.join(';')); continue; }
|
|
180
|
+
if (def.capabilityOnly !== true) { log(`语音:只读适配器 ${def && def.id} 没标 capabilityOnly,跳过`); continue; }
|
|
181
|
+
if (readonlyProviders.some((item) => item.id === def.id)) { log(`语音:只读适配器 ${def.id} 重复,后者被忽略`); continue; }
|
|
182
|
+
readonlyProviders.push(def);
|
|
183
|
+
}
|
|
184
|
+
return readonlyProviders;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function configOf(id) {
|
|
188
|
+
if (!store || typeof store.configFor !== 'function') return {};
|
|
189
|
+
try {
|
|
190
|
+
return store.configFor(id) || {};
|
|
191
|
+
} catch {
|
|
192
|
+
return {};
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* 一个 provider 此刻的状态。
|
|
198
|
+
* host 用适配器自己的 `status()`(去问宿主有没有那个服务),其余按配置判。
|
|
199
|
+
*/
|
|
200
|
+
function statusOfId(id) {
|
|
201
|
+
const provider = get(id);
|
|
202
|
+
if (!provider) return PROVIDER_STATUS.UNAVAILABLE;
|
|
203
|
+
if (typeof provider.status === 'function') {
|
|
204
|
+
try {
|
|
205
|
+
const status = provider.status();
|
|
206
|
+
if (status === PROVIDER_STATUS.AVAILABLE || status === PROVIDER_STATUS.UNAVAILABLE) return status;
|
|
207
|
+
} catch { /* 探宿主失败按不可用处理 */ }
|
|
208
|
+
return PROVIDER_STATUS.UNAVAILABLE;
|
|
209
|
+
}
|
|
210
|
+
const required = Array.isArray(provider.configFields) ? provider.configFields : [];
|
|
211
|
+
const config = configOf(provider.id);
|
|
212
|
+
const missing = required.some((field) => {
|
|
213
|
+
if (!field || field.required !== true) return false;
|
|
214
|
+
const value = config[field.key];
|
|
215
|
+
return value === undefined || value === null || value === '';
|
|
216
|
+
});
|
|
217
|
+
return missing ? PROVIDER_STATUS.UNCONFIGURED : statusOf(provider, config);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** 按 id 找条目(含只读条目:面板 / 能力表要显示它们;网关调用前会再判 capabilityOnly)。 */
|
|
221
|
+
function get(id) {
|
|
222
|
+
if (typeof id !== 'string' || !id) return null;
|
|
223
|
+
return ensure().find((provider) => provider.id === id)
|
|
224
|
+
|| ensureReadonly().find((provider) => provider.id === id)
|
|
225
|
+
|| null;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* 能力表:可调用 provider + 只读条目。只读条目排在最后——App 的旧版解析在缺 `default`
|
|
230
|
+
* 时会挑「第一个 batch / streaming 的行」,端侧那条永远不能成为那个兜底。
|
|
231
|
+
*/
|
|
232
|
+
function capabilities() {
|
|
233
|
+
return [...ensure(), ...ensureReadonly()].map((provider) => capabilityOf(provider, statusOfId(provider.id)));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** 现在能用的那些 id(按注册顺序):只读条目不算——它们没法被网关调用。 */
|
|
237
|
+
function availableIds() {
|
|
238
|
+
return ensure().filter((provider) => statusOfId(provider.id) === PROVIDER_STATUS.AVAILABLE).map((provider) => provider.id);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* 当前默认 provider 的 id。
|
|
243
|
+
*
|
|
244
|
+
* 规则:配置里选的那家**现在可用**就它是默认;否则退到第一个可用的;一个可用的都没有
|
|
245
|
+
* 就回配置里的值(面板据此显示「你选的那家现在不可用」,而不是静默换一家识别 ——
|
|
246
|
+
* 契约要求「不支持的组合直接报能力缺失,不做静默换家」)。
|
|
247
|
+
*/
|
|
248
|
+
function defaultId() {
|
|
249
|
+
const configured = store && typeof store.defaultProvider === 'function'
|
|
250
|
+
? String(store.defaultProvider() || '')
|
|
251
|
+
: '';
|
|
252
|
+
const available = availableIds();
|
|
253
|
+
if (configured && available.includes(configured)) return configured;
|
|
254
|
+
if (available.length > 0) return available[0];
|
|
255
|
+
// 一个可用的都没有就交空:`default` 是「现在能用的那一家」,不是「上次配过的那一家」。
|
|
256
|
+
// 把不可用的配置项回给 App,会让它画出麦克风然后在识别时失败(契约要求这时是 null)。
|
|
257
|
+
// 面板要显示「选中的那家」自己另拿 `store.defaultProvider()`,不靠这一格。
|
|
258
|
+
return '';
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** 列表(面板 / 能力表用):可调用在前、只读在后。 */
|
|
262
|
+
function list() {
|
|
263
|
+
return [...ensure(), ...ensureReadonly()];
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return { list, get, capabilities, availableIds, defaultId, statusOf: statusOfId, configOf };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
module.exports = {
|
|
270
|
+
PROVIDER_DIRS,
|
|
271
|
+
READONLY_DIRS,
|
|
272
|
+
adapterFilesIn,
|
|
273
|
+
scanProviderDirectory,
|
|
274
|
+
loadAdapterProviders,
|
|
275
|
+
loadReadonlyProviders,
|
|
276
|
+
createProviderRegistry,
|
|
277
|
+
};
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
// 2026-11-29:加 /voice/lexicon/learn 自动学习词库接口(把用户内容整理后写电脑侧)。
|
|
2
|
+
// 2026-11-28:语音网关的三条移动路由 + 面板配置口的接线(实现全在 voice/ 里,本文件只转 HTTP)。
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 语音入口的 HTTP / WS 网关层:
|
|
7
|
+
*
|
|
8
|
+
* - `GET /api/mobile/v1/voice/capabilities`:能力表(含 `limits`);
|
|
9
|
+
* - `POST /api/mobile/v1/voice/transcribe`:整段。主路是 JSON(`{audio:<base64 WAV>, format, lang}`,
|
|
10
|
+
* 因为 E2EE v2 信封只承载 JSON 字符串体);本机调试也接受 `Content-Type: audio/wav` 的裸字节;
|
|
11
|
+
* - `WS /api/mobile/v1/voice/stream`:流式升级路由(见 `stream.js`);
|
|
12
|
+
* - `GET|POST /api/relay/voice/config`:插件面板的语音页(见 `panel-api.js`)。
|
|
13
|
+
*
|
|
14
|
+
* 本文件不做任何业务判断:参数从 query / header / body 取出来,交给网关;错误按契约映射成
|
|
15
|
+
* HTTP 状态与 `{ ok:false, error:{ code, message } }`。手机只认 `code` 分支。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const { sendJson, readJsonBody, readRawBody } = require('../../shared/http-util.js');
|
|
19
|
+
const protocol = require('./protocol.js');
|
|
20
|
+
const { voiceGatewayFor, noteContext } = require('./runtime.js');
|
|
21
|
+
const { GLOBAL_MAX_BYTES } = require('./gateway.js');
|
|
22
|
+
const { createVoiceStreamService } = require('./stream.js');
|
|
23
|
+
const panelApi = require('./panel-api.js');
|
|
24
|
+
const { lexiconStore } = require('./lexicon-store.js');
|
|
25
|
+
const lexiconModule = require('./lexicon.js');
|
|
26
|
+
const { cwdOf } = require('../session-cwd.js');
|
|
27
|
+
|
|
28
|
+
const { VOICE_ERRORS, voiceError, httpStatusOf, errorPayload } = protocol;
|
|
29
|
+
|
|
30
|
+
/** 整段请求体最多读这么多:网关硬上限之外再给 WAV 头与分块补齐留一点余量。 */
|
|
31
|
+
const MAX_WAV_BODY = GLOBAL_MAX_BYTES + protocol.WAV_SLACK_BYTES;
|
|
32
|
+
/** JSON 主路的上限:base64 把字节放大 4/3,另加字段名与 format 的余量。 */
|
|
33
|
+
const MAX_JSON_VOICE_BODY = Math.ceil((MAX_WAV_BODY * 4) / 3) + 4096;
|
|
34
|
+
/** 已经扫过工作区术语的目录:每个目录一个进程只扫一次,避免每句听写都扫盘(性能)。 */
|
|
35
|
+
const minedCwds = new Set();
|
|
36
|
+
|
|
37
|
+
function log(...args) {
|
|
38
|
+
try { console.warn('[dsh-mobile-plugin] [voice]', ...args) } catch { /* 日志不反噬 */ }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 只取一个请求头(Node 会把重复头合成数组)。 */
|
|
42
|
+
function headerOf(req, name) {
|
|
43
|
+
const raw = req && req.headers ? req.headers[name] : undefined;
|
|
44
|
+
const value = Array.isArray(raw) ? raw[0] : raw;
|
|
45
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 请求是不是 JSON(信封解开之后 content-type 仍是客户端原来那个)。 */
|
|
49
|
+
function isJsonBody(req) {
|
|
50
|
+
const type = headerOf(req, 'content-type').toLowerCase();
|
|
51
|
+
if (type.includes('application/json')) return true;
|
|
52
|
+
if (type.includes('audio/') || type.includes('application/octet-stream')) return false;
|
|
53
|
+
// 没声明类型时看信封守卫有没有把解析好的对象放进来;有就是 JSON。
|
|
54
|
+
return Boolean(req && req.body && typeof req.body === 'object' && !Buffer.isBuffer(req.body));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 解 base64 音频。
|
|
59
|
+
*
|
|
60
|
+
* base64 的坑在「坏输入不会抛错」:`Buffer.from(x,'base64')` 会静默丢掉不认识的字符,
|
|
61
|
+
* 于是「客户端发错字段」变成一段更短的音频、报的却是格式错误。所以先按字符集与长度判一次,
|
|
62
|
+
* 解完再按 4/3 估一下字节数是否对得上(只判量级,不重编码整个包)。
|
|
63
|
+
*/
|
|
64
|
+
function decodeBase64Audio(value) {
|
|
65
|
+
if (typeof value !== 'string' || value === '') {
|
|
66
|
+
return { ok: false, code: VOICE_ERRORS.INVALID_AUDIO, message: 'body.audio 必须是 base64 的 WAV' };
|
|
67
|
+
}
|
|
68
|
+
// 允许带 data URL 前缀(浏览器 / 调试工具常见写法),其余原样解。
|
|
69
|
+
const comma = value.indexOf(',');
|
|
70
|
+
const raw = value.startsWith('data:') && comma >= 0 ? value.slice(comma + 1) : value;
|
|
71
|
+
const compact = raw.replace(/\s+/g, '');
|
|
72
|
+
if (compact.length === 0 || compact.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(compact)) {
|
|
73
|
+
return { ok: false, code: VOICE_ERRORS.INVALID_AUDIO, message: 'body.audio 不是有效的 base64' };
|
|
74
|
+
}
|
|
75
|
+
const audio = Buffer.from(compact, 'base64');
|
|
76
|
+
if (audio.length === 0) {
|
|
77
|
+
return { ok: false, code: VOICE_ERRORS.INVALID_AUDIO, message: 'body.audio 解出来是空音频' };
|
|
78
|
+
}
|
|
79
|
+
return { ok: true, audio };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** `format` 只能缺省或与协议口径一致;报了别的值就拒,别指望适配器替我们换算。 */
|
|
83
|
+
function formatErrorOf(format) {
|
|
84
|
+
if (format === undefined || format === null) return null;
|
|
85
|
+
if (typeof format !== 'object' || Array.isArray(format)) {
|
|
86
|
+
return voiceError(VOICE_ERRORS.INVALID_AUDIO, 'format 必须是 { rate, bits, channels }');
|
|
87
|
+
}
|
|
88
|
+
const rate = Number(format.rate ?? protocol.SAMPLE_RATE);
|
|
89
|
+
const bits = Number(format.bits ?? protocol.BITS_PER_SAMPLE);
|
|
90
|
+
const channels = Number(format.channels ?? protocol.CHANNELS);
|
|
91
|
+
if (rate !== protocol.SAMPLE_RATE || bits !== protocol.BITS_PER_SAMPLE || channels !== protocol.CHANNELS) {
|
|
92
|
+
return voiceError(VOICE_ERRORS.INVALID_AUDIO, `音频格式必须是 ${protocol.SAMPLE_RATE} Hz / ${protocol.BITS_PER_SAMPLE}-bit / 单声道`);
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* 读整段请求:JSON 主路(契约 §2)或裸 WAV(本机调试)。
|
|
99
|
+
* 回 `{ ok:true, audio, lang }` 或 `{ ok:false, error }`。
|
|
100
|
+
*/
|
|
101
|
+
async function readTranscribeBody(req, queryLang) {
|
|
102
|
+
if (!isJsonBody(req)) {
|
|
103
|
+
let raw;
|
|
104
|
+
try {
|
|
105
|
+
raw = await readRawBody(req, MAX_WAV_BODY);
|
|
106
|
+
} catch {
|
|
107
|
+
raw = null;
|
|
108
|
+
}
|
|
109
|
+
if (raw === null) {
|
|
110
|
+
return { ok: false, error: voiceError(VOICE_ERRORS.TOO_LARGE, `音频超过上限(${Math.floor(GLOBAL_MAX_BYTES / 1024 / 1024)} MiB)`) };
|
|
111
|
+
}
|
|
112
|
+
if (!Buffer.isBuffer(raw) || raw.length === 0) {
|
|
113
|
+
return { ok: false, error: voiceError(VOICE_ERRORS.INVALID_AUDIO, '请求体里没有音频字节') };
|
|
114
|
+
}
|
|
115
|
+
return { ok: true, audio: raw, lang: queryLang };
|
|
116
|
+
}
|
|
117
|
+
const body = await readJsonBody(req, MAX_JSON_VOICE_BODY);
|
|
118
|
+
if (body === null) {
|
|
119
|
+
// readJsonBody 回 null 可能是超限,也可能是非法 JSON:两种都按体积 / 格式回一句能定位的。
|
|
120
|
+
return { ok: false, error: voiceError(VOICE_ERRORS.TOO_LARGE, '请求体超过上限(或不是合法 JSON)') };
|
|
121
|
+
}
|
|
122
|
+
const decoded = decodeBase64Audio(body && body.audio);
|
|
123
|
+
if (!decoded.ok) return { ok: false, error: voiceError(decoded.code, decoded.message) };
|
|
124
|
+
const formatError = formatErrorOf(body && body.format);
|
|
125
|
+
if (formatError) return { ok: false, error: formatError };
|
|
126
|
+
const lang = typeof body?.lang === 'string' && body.lang.trim() ? body.lang.trim() : queryLang;
|
|
127
|
+
return { ok: true, audio: decoded.audio, lang };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* GET /voice/capabilities
|
|
132
|
+
* → { ok, enabled, providers:[…], default, features, lang, limits }
|
|
133
|
+
*/
|
|
134
|
+
async function handleCapabilities(ctx, _req, res) {
|
|
135
|
+
noteContext(ctx);
|
|
136
|
+
let gateway;
|
|
137
|
+
try {
|
|
138
|
+
gateway = voiceGatewayFor(ctx);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
return sendJson(res, 500, { ok: false, error: { code: VOICE_ERRORS.FAILED, message: '语音服务没起来' } });
|
|
141
|
+
}
|
|
142
|
+
return sendJson(res, 200, gateway.capabilities());
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* POST /voice/transcribe?lang=auto|zh|…(body: WAV 字节,header: x-dsh-voice-provider 可选)
|
|
147
|
+
* → { ok, text, lang?, provider, durationMs, corrected }
|
|
148
|
+
*/
|
|
149
|
+
async function handleTranscribe(ctx, req, res) {
|
|
150
|
+
noteContext(ctx);
|
|
151
|
+
const url = new URL(req && req.url ? req.url : '/', 'http://x');
|
|
152
|
+
const providerId = headerOf(req, 'x-dsh-voice-provider') || (url.searchParams.get('provider') || '').trim();
|
|
153
|
+
const queryLang = (url.searchParams.get('lang') || 'auto').trim() || 'auto';
|
|
154
|
+
const read = await readTranscribeBody(req, queryLang);
|
|
155
|
+
if (!read.ok) {
|
|
156
|
+
return sendJson(res, httpStatusOf(read.error.code), { ok: false, error: errorPayload(read.error) });
|
|
157
|
+
}
|
|
158
|
+
let gateway;
|
|
159
|
+
try {
|
|
160
|
+
gateway = voiceGatewayFor(ctx);
|
|
161
|
+
} catch {
|
|
162
|
+
return sendJson(res, httpStatusOf(VOICE_ERRORS.FAILED), { ok: false, error: { code: VOICE_ERRORS.FAILED, message: '语音服务没起来' } });
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
const result = await gateway.transcribe({
|
|
166
|
+
audio: read.audio,
|
|
167
|
+
providerId: providerId || undefined,
|
|
168
|
+
lang: read.lang,
|
|
169
|
+
// HTTP 入口不接词库素材:契约里 body 只有 lang,热词 / 上下文留给流式 start 帧。
|
|
170
|
+
hints: {},
|
|
171
|
+
signal: undefined,
|
|
172
|
+
});
|
|
173
|
+
return sendJson(res, 200, { ok: true, ...result });
|
|
174
|
+
} catch (error) {
|
|
175
|
+
const payload = errorPayload(error);
|
|
176
|
+
return sendJson(res, httpStatusOf(payload.code), { ok: false, error: payload });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* POST /voice/lexicon/learn —— 自动学习词库。
|
|
182
|
+
*
|
|
183
|
+
* body:`{ messages?: string[], hotwords?: string[], corrections?: [{ heard, corrected }] }`。
|
|
184
|
+
* `messages` 是用户实际说/发出去的内容,这里用 lexicon 的同一套关键词规则整理成热词(不搬原句、
|
|
185
|
+
* 有上限);`corrections` 是明确的「听错 → 改对」映射,优先级最高。全部写在电脑侧,不外传整份。
|
|
186
|
+
* → `{ ok, hotwords, corrections }`(回条数,不回原文)。
|
|
187
|
+
*/
|
|
188
|
+
async function handleLexiconLearn(ctx, req, res) {
|
|
189
|
+
noteContext(ctx);
|
|
190
|
+
let body;
|
|
191
|
+
try {
|
|
192
|
+
body = await readJsonBody(req, 64 * 1024);
|
|
193
|
+
} catch {
|
|
194
|
+
return sendJson(res, 400, { ok: false, error: { code: VOICE_ERRORS.INVALID_AUDIO, message: 'body 读不出来' } });
|
|
195
|
+
}
|
|
196
|
+
const messages = Array.isArray(body && body.messages)
|
|
197
|
+
? body.messages.filter((item) => typeof item === 'string' && item.trim()).slice(0, 8)
|
|
198
|
+
: [];
|
|
199
|
+
const corrections = Array.isArray(body && body.corrections)
|
|
200
|
+
? body.corrections.filter((pair) => pair && typeof pair.heard === 'string' && typeof pair.corrected === 'string').slice(0, 50)
|
|
201
|
+
: [];
|
|
202
|
+
const explicit = Array.isArray(body && body.hotwords)
|
|
203
|
+
? body.hotwords.filter((word) => typeof word === 'string' && word.trim()).slice(0, 50)
|
|
204
|
+
: [];
|
|
205
|
+
let mined = [];
|
|
206
|
+
if (messages.length && lexiconModule && typeof lexiconModule.buildLexicon === 'function') {
|
|
207
|
+
try {
|
|
208
|
+
const built = lexiconModule.buildLexicon({ sessionMessages: messages });
|
|
209
|
+
if (built && Array.isArray(built.hotwords)) mined = built.hotwords;
|
|
210
|
+
} catch { /* 整理失败就当没学到新词,不影响识别 */ }
|
|
211
|
+
}
|
|
212
|
+
// 工作区术语:带 sessionId 时取会话的工作区,扫一遍(每个目录一个进程只扫一次,避开每句话扫盘)。
|
|
213
|
+
const sessionId = typeof body === 'object' && body && typeof body.sessionId === 'string' ? body.sessionId.trim() : '';
|
|
214
|
+
if (sessionId && lexiconModule && typeof lexiconModule.buildLexicon === 'function') {
|
|
215
|
+
try {
|
|
216
|
+
const cwd = await cwdOf(ctx, sessionId);
|
|
217
|
+
if (cwd && !minedCwds.has(cwd)) {
|
|
218
|
+
minedCwds.add(cwd);
|
|
219
|
+
const built = lexiconModule.buildLexicon({ cwd });
|
|
220
|
+
if (built && Array.isArray(built.hotwords)) mined = mined.concat(built.hotwords);
|
|
221
|
+
}
|
|
222
|
+
} catch { /* 工作区术语扫不出来不影响已学到的词 */ }
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
const store = lexiconStore();
|
|
226
|
+
store.learn({ hotwords: explicit.concat(mined), corrections });
|
|
227
|
+
const snap = store.snapshot();
|
|
228
|
+
return sendJson(res, 200, { ok: true, hotwords: snap.hotwords.length, corrections: snap.corrections.length });
|
|
229
|
+
} catch {
|
|
230
|
+
return sendJson(res, 500, { ok: false, error: { code: VOICE_ERRORS.FAILED, message: '词库没存下来' } });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** WebSocket 升级(鉴权在服务里做,拒绝发生在握手之前)。 */
|
|
235
|
+
let streamService = null;
|
|
236
|
+
function handleStreamUpgrade(req, socket, head, ctx) {
|
|
237
|
+
if (!streamService) streamService = createVoiceStreamService({ log });
|
|
238
|
+
return streamService.handleUpgrade(req, socket, head, ctx);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* 断开某台设备的语音流(凭据吊销 / 全量清理时由装配层调用)。
|
|
243
|
+
*
|
|
244
|
+
* 语音流和 SSE、mux 一样是「只有连接、没有请求」的长连接:吊销凭据时如果不主动断,
|
|
245
|
+
* 那条连接会带着已经作废的身份一直读下去。返回断掉的连接数,和另外两路一起汇总。
|
|
246
|
+
*/
|
|
247
|
+
function dropVoiceDeviceStreams(deviceId, instanceId) {
|
|
248
|
+
if (!streamService) return 0;
|
|
249
|
+
return deviceId ? streamService.dropDevice(deviceId, instanceId) : streamService.dropAll(instanceId);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** 测试用:换掉 / 读当前流服务实例。 */
|
|
253
|
+
function voiceStreamService() {
|
|
254
|
+
return streamService;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** 面板「语音」页(本机来源限制在 panel-api 里)。 */
|
|
258
|
+
async function handlePanelConfig(ctx, req, res) {
|
|
259
|
+
return panelApi.handleVoicePanelConfig(ctx, req, res);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
module.exports = {
|
|
264
|
+
handleCapabilities,
|
|
265
|
+
handleTranscribe,
|
|
266
|
+
handleLexiconLearn,
|
|
267
|
+
decodeBase64Audio,
|
|
268
|
+
readTranscribeBody,
|
|
269
|
+
handleStreamUpgrade,
|
|
270
|
+
dropVoiceDeviceStreams,
|
|
271
|
+
voiceStreamService,
|
|
272
|
+
handlePanelConfig,
|
|
273
|
+
MAX_WAV_BODY,
|
|
274
|
+
MAX_JSON_VOICE_BODY,
|
|
275
|
+
/** 只给测试:换一个流服务实例 / 读当前实例。 */
|
|
276
|
+
_streamService: () => streamService,
|
|
277
|
+
_setStreamServiceForTests: (service) => { streamService = service; },
|
|
278
|
+
};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// 2026-11-28:语音网关的运行时装配——每个插件 ctx 一份 store / registry / gateway;WS 升级的 ctx 已由装配层显式传入,这里只留兜底。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 运行时装配。
|
|
6
|
+
*
|
|
7
|
+
* 网关要三样东西:配置存储(电脑侧一份)、provider 注册表(host 适配器要问宿主的
|
|
8
|
+
* `ctx.speechToText`)、以及可选的 lang / lexicon / postprocess。
|
|
9
|
+
*
|
|
10
|
+
* HTTP 处理器每次都能拿到 `ctx`;**WebSocket 升级处理器拿不到**(宿主按
|
|
11
|
+
* `(req, socket, head)` 调)。现在的正路是装配层把 ctx 递进来:`lib/routes/mobile-api.js`
|
|
12
|
+
* 挂 `/voice/stream` 时包了一层,在升级那一刻用装配层给的取值器取到当前这一代 ctx,
|
|
13
|
+
* 作为第四参数传给 `voice.handleStreamUpgrade`(`stream.js` 的 `handleUpgrade(req, socket,
|
|
14
|
+
* head, ctx)`)。
|
|
15
|
+
*
|
|
16
|
+
* 这里做两件事:
|
|
17
|
+
* 1. 按 ctx 缓存一份网关(同一进程里 ctx 换了 = 换代,旧那份自然被 WeakMap 收走);
|
|
18
|
+
* 2. 保留「最近一次 HTTP 请求见过的 ctx」作为**兜底**:只有没传 ctx 的调用方才会走到
|
|
19
|
+
* (本机调试直接调 `handleStreamUpgrade`、测试里手工建流服务这类)。App 打开语音前
|
|
20
|
+
* 一定会先调 `/voice/capabilities`,所以兜底在正常时序下有值;但这已经不是主路,
|
|
21
|
+
* 传了 ctx 就只认传进来的那一个,不会被这里记下的值盖掉。
|
|
22
|
+
*
|
|
23
|
+
* `noteContext` 仍然由 HTTP 处理器(`routes.js` / `panel-api.js`)调用:兜底要有人记,
|
|
24
|
+
* 删掉它会让「没传 ctx」的旧调用方退化到 host 不可用的兜底网关。
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const { createVoiceSettingsStore } = require('./settings.js');
|
|
28
|
+
const { createProviderRegistry } = require('./providers/registry.js');
|
|
29
|
+
const { createVoiceGateway } = require('./gateway.js');
|
|
30
|
+
|
|
31
|
+
const gateways = new WeakMap();
|
|
32
|
+
let fallbackGateway = null;
|
|
33
|
+
let lastContext = null;
|
|
34
|
+
|
|
35
|
+
function log(...args) {
|
|
36
|
+
try { console.warn('[dsh-mobile-plugin] [voice]', ...args) } catch { /* 日志不反噬 */ }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function build(ctx) {
|
|
40
|
+
const store = createVoiceSettingsStore();
|
|
41
|
+
const registry = createProviderRegistry({ ctx: ctx || null, store, log });
|
|
42
|
+
return createVoiceGateway({ registry, store, log });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 兜底路径的记录点:HTTP 处理器顺手记下 ctx,留给**没传 ctx**的升级调用方。
|
|
47
|
+
* 装配层显式传 ctx 时,这里记下的值不参与选择(见 `voiceGatewayFor`)。
|
|
48
|
+
*/
|
|
49
|
+
function noteContext(ctx) {
|
|
50
|
+
if (ctx && typeof ctx === 'object') lastContext = ctx;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 取这一代(或最近见过的)ctx 对应的网关。
|
|
55
|
+
*
|
|
56
|
+
* 优先级:传了就用传进来的(`handleUpgrade` 的第四参数走这条);没传才用最近 HTTP 记下的;
|
|
57
|
+
* 都没有就建一份 host 不可用的兜底(厂商 provider 照旧)。
|
|
58
|
+
*/
|
|
59
|
+
function voiceGatewayFor(ctx) {
|
|
60
|
+
if (ctx && typeof ctx === 'object') {
|
|
61
|
+
let gateway = gateways.get(ctx);
|
|
62
|
+
if (!gateway) {
|
|
63
|
+
gateway = build(ctx);
|
|
64
|
+
gateways.set(ctx, gateway);
|
|
65
|
+
}
|
|
66
|
+
return gateway;
|
|
67
|
+
}
|
|
68
|
+
if (lastContext) return voiceGatewayFor(lastContext);
|
|
69
|
+
if (!fallbackGateway) fallbackGateway = build(null);
|
|
70
|
+
return fallbackGateway;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 当前有没有「知道宿主在哪」的 ctx(面板 / 诊断用;测试可据此断言时序)。 */
|
|
74
|
+
function hasContext() {
|
|
75
|
+
return lastContext !== null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 只给测试:清掉缓存,避免用例之间串 ctx / 配置。 */
|
|
79
|
+
function resetForTests() {
|
|
80
|
+
fallbackGateway = null;
|
|
81
|
+
lastContext = null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
module.exports = { voiceGatewayFor, noteContext, hasContext, resetForTests };
|