dsh-mobile-plugin 0.5.137 → 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.
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/pairing.md +2 -2
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/port-conflict.md +4 -4
- package/lib/impl.js +10 -6
- 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 +22 -22
- 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/wiring.cjs +17 -6
- package/package.json +14 -15
|
@@ -0,0 +1,746 @@
|
|
|
1
|
+
// 2026-11-29:把自动学到的词库(热词 + 听错→改对)叠进 hints,见 lexicon-store.js。
|
|
2
|
+
// 2026-11-28:语音网关编排——能力表、整段识别、流式会话(含批量 provider 的降级)、限额与错误映射。
|
|
3
|
+
// 2026-11-28:只读能力条目(端侧)只显示、不可选;选择路径明确拒绝,不把它当远端 provider。
|
|
4
|
+
// 2026-11-28:能力表新增 `features.streamE2ee`,声明流式帧支持逐帧加密(见 `frames.js`)。
|
|
5
|
+
'use strict';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 语音网关:手机只跟它说话,它负责挑 provider、判限额、映射错误、挂语言 / 词库 / 后处理。
|
|
9
|
+
*
|
|
10
|
+
* 三件事按契约分开:
|
|
11
|
+
* 1. `capabilities()`:唯一让 App 做分支的依据。provider 不支持流式也照旧出现在表里,
|
|
12
|
+
* `/stream` 仍然可用 —— 网关内部攒整段、只发 final,App 按「没有部分结果」自然降级。
|
|
13
|
+
* 2. `transcribe()`:整段入口。body 是 WAV 字节,这里校验格式 / 时长 / 大小 / 配额,
|
|
14
|
+
* 再交给适配器。适配器抛出的码优先,裸错统一收成 `voice-failed`。
|
|
15
|
+
* 3. `openStream()`:一条流式会话。**会话对象归连接所有**,不挂模块级单例;断开就 cancel。
|
|
16
|
+
*
|
|
17
|
+
* 语言 / 词库 / 后处理由语言组负责,可能还没落地:这里用可选加载,缺了就整段跳过,
|
|
18
|
+
* 绝不因为某个可选模块不在就让识别失败。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const path = require('node:path');
|
|
22
|
+
|
|
23
|
+
const protocol = require('./protocol.js');
|
|
24
|
+
const { PROVIDER_STATUS, providerConfigView } = require('./voice-provider.js');
|
|
25
|
+
|
|
26
|
+
const { VOICE_ERRORS, voiceError, httpStatusOf, buildWav, parseWav, errorPayload, DEFAULT_MAX_SECONDS, DEFAULT_MAX_BYTES } = protocol;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 可选模块加载器。
|
|
30
|
+
*
|
|
31
|
+
* 只加载「存在才用」的三个模块(`lang.js` / `lexicon.js` / `postprocess.js`)。它们属于语言组,
|
|
32
|
+
* 与网关并行开发,任何时刻都可能还不存在;这里缓存**成功**结果,缺失时每次重试一次
|
|
33
|
+
* require(Node 的 require 失败很便宜,且文件落地后下一次请求就能用上,不用等插件重载)。
|
|
34
|
+
*/
|
|
35
|
+
const optionalCache = new Map();
|
|
36
|
+
function optionalModule(relative) {
|
|
37
|
+
const key = relative;
|
|
38
|
+
if (optionalCache.has(key)) return optionalCache.get(key);
|
|
39
|
+
try {
|
|
40
|
+
const mod = require(path.join(__dirname, relative));
|
|
41
|
+
if (mod && typeof mod === 'object') { optionalCache.set(key, mod); return mod; }
|
|
42
|
+
} catch { /* 还没落地 / 形状不对:跳过 */ }
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 网关的硬上限(安全阀,不是产品默认):只挡「某家声明一个荒唐的数字」。
|
|
48
|
+
* 单次真正能用多少由 **provider 自己的 maxSeconds / maxBytes** 决定(官方云端是 120 秒 /
|
|
49
|
+
* 8 MiB,写在 host 适配器里;各家云厂商各有自己的边界),这里只是总闸。
|
|
50
|
+
*/
|
|
51
|
+
const GLOBAL_MAX_SECONDS = 600;
|
|
52
|
+
const GLOBAL_MAX_BYTES = 25 * 1024 * 1024;
|
|
53
|
+
/** 单次调用上游的超时:官方云端 ASR 就是 30 秒,适配器都不做重试(弱网重连归 App / 网关)。 */
|
|
54
|
+
const DEFAULT_TRANSCRIBE_TIMEOUT_MS = 30_000;
|
|
55
|
+
/** 每个 provider 每分钟最多几次请求。默认宽松,挡的是失控客户端不是正常用户。 */
|
|
56
|
+
const RATE_LIMIT_WINDOW_MS = 60_000;
|
|
57
|
+
const DEFAULT_RATE_LIMIT_PER_MINUTE = Number(process.env.DSH_MOBILE_VOICE_RPM) || 30;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 一次识别的实际上限:取 provider 自己的上限与全局上限的较小者。
|
|
61
|
+
* (比如 tencent 一句话识别 60 秒,就在 120 秒的全局口径内再收一次。)
|
|
62
|
+
*/
|
|
63
|
+
function limitsOf(provider) {
|
|
64
|
+
return {
|
|
65
|
+
maxSeconds: Math.min(
|
|
66
|
+
Number.isFinite(provider && provider.maxSeconds) ? provider.maxSeconds : GLOBAL_MAX_SECONDS,
|
|
67
|
+
GLOBAL_MAX_SECONDS,
|
|
68
|
+
),
|
|
69
|
+
maxBytes: Math.min(
|
|
70
|
+
Number.isFinite(provider && provider.maxBytes) ? provider.maxBytes : GLOBAL_MAX_BYTES,
|
|
71
|
+
GLOBAL_MAX_BYTES,
|
|
72
|
+
),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 把上游抛出的错误收敛成契约错误码;裸错一律 `voice-failed`,不把内部细节回给手机。 */
|
|
77
|
+
function normalizeProviderError(error, name) {
|
|
78
|
+
if (error && error.cancelled === true) {
|
|
79
|
+
const cancelled = voiceError(VOICE_ERRORS.FAILED, '识别已取消');
|
|
80
|
+
cancelled.cancelled = true;
|
|
81
|
+
return cancelled;
|
|
82
|
+
}
|
|
83
|
+
const code = error && typeof error.code === 'string' && protocol.VOICE_ERROR_HTTP[error.code]
|
|
84
|
+
? error.code
|
|
85
|
+
: VOICE_ERRORS.FAILED;
|
|
86
|
+
const message = error && typeof error.message === 'string' && error.message
|
|
87
|
+
? error.message
|
|
88
|
+
: `${name || '语音服务'}识别失败`;
|
|
89
|
+
return voiceError(code, message);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 建网关。
|
|
94
|
+
*
|
|
95
|
+
* @param {object} options
|
|
96
|
+
* @param {object} options.registry provider 注册表(见 providers/registry.js)
|
|
97
|
+
* @param {object} options.store 配置存储(见 settings.js)
|
|
98
|
+
* @param {() => Date} [options.now]
|
|
99
|
+
* @param {(msg: string, ...rest: any[]) => void} [options.log]
|
|
100
|
+
* @param {object} [options.lang] / [options.lexicon] / [options.postprocess] 显式注入(测试用)
|
|
101
|
+
* @param {object} [options.registry]
|
|
102
|
+
*/
|
|
103
|
+
function createVoiceGateway(options = {}) {
|
|
104
|
+
const registry = options.registry;
|
|
105
|
+
const store = options.store;
|
|
106
|
+
const log = typeof options.log === 'function' ? options.log : () => {};
|
|
107
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
108
|
+
const transcribeTimeoutMs = Number.isFinite(options.transcribeTimeoutMs) && options.transcribeTimeoutMs > 0
|
|
109
|
+
? options.transcribeTimeoutMs
|
|
110
|
+
: DEFAULT_TRANSCRIBE_TIMEOUT_MS;
|
|
111
|
+
const rateLimitPerMinute = Number.isFinite(options.rateLimitPerMinute) && options.rateLimitPerMinute > 0
|
|
112
|
+
? options.rateLimitPerMinute
|
|
113
|
+
: DEFAULT_RATE_LIMIT_PER_MINUTE;
|
|
114
|
+
/** providerId → 最近一分钟的请求时刻。进程内状态,插件重载即清(不需要落盘)。 */
|
|
115
|
+
const rateBuckets = new Map();
|
|
116
|
+
|
|
117
|
+
const langModule = options.lang !== undefined ? options.lang : optionalModule('lang.js');
|
|
118
|
+
const lexiconModule = options.lexicon !== undefined ? options.lexicon : optionalModule('lexicon.js');
|
|
119
|
+
const postprocessModule = options.postprocess !== undefined ? options.postprocess : optionalModule('postprocess.js');
|
|
120
|
+
// 自动学习到的词库(电脑侧落盘,单例)。缺模块时按没有学过的词处理,识别照常。
|
|
121
|
+
const lexiconStoreModule = options.lexiconStore !== undefined ? null : optionalModule('lexicon-store.js');
|
|
122
|
+
const learnedStore = options.lexiconStore !== undefined
|
|
123
|
+
? options.lexiconStore
|
|
124
|
+
: (lexiconStoreModule && typeof lexiconStoreModule.lexiconStore === 'function' ? lexiconStoreModule.lexiconStore() : null);
|
|
125
|
+
|
|
126
|
+
if (!registry || typeof registry.capabilities !== 'function') {
|
|
127
|
+
throw new Error('语音网关需要 registry');
|
|
128
|
+
}
|
|
129
|
+
if (!store) throw new Error('语音网关需要配置存储');
|
|
130
|
+
|
|
131
|
+
function moduleAvailable(module, names) {
|
|
132
|
+
if (!module || typeof module !== 'object') return false;
|
|
133
|
+
return names.every((name) => typeof module[name] === 'function');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const features = {
|
|
137
|
+
// 标点与 ITN 都靠后处理模块;它不在时这两格为 false,App 不画对应选项。
|
|
138
|
+
punctuation: moduleAvailable(postprocessModule, ['normalize']),
|
|
139
|
+
itn: moduleAvailable(postprocessModule, ['normalize']),
|
|
140
|
+
langDetect: moduleAvailable(langModule, ['detectLang']),
|
|
141
|
+
// 声纹 / 说话人分离第三阶段才做,当前恒 false(契约允许)。
|
|
142
|
+
diarization: false,
|
|
143
|
+
// 流式帧能不能逐帧加密(`start.enc:"v2"`,字节口径见 `frames.js`)。App 只看这一格决定
|
|
144
|
+
// 加不加密;恒 true —— 这一侧是网关自己的能力,与 provider 无关。
|
|
145
|
+
streamE2ee: true,
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
function langView() {
|
|
149
|
+
// 只读条目(端侧)的语种不进聚合:这一格是给「网关能接哪种语言」用的,端侧不由网关执行。
|
|
150
|
+
const providers = registry.capabilities().filter((row) => row.status === PROVIDER_STATUS.AVAILABLE && row.selectable !== false);
|
|
151
|
+
const available = [];
|
|
152
|
+
for (const row of providers) {
|
|
153
|
+
for (const code of row.languages || []) {
|
|
154
|
+
if (code !== 'auto' && !available.includes(code)) available.push(code);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return { auto: true, available };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* 当前限额 + 已用量:面板与 App 都读这一格,不在客户端写死数字。
|
|
162
|
+
*
|
|
163
|
+
* 单次上限取**当前默认 provider** 的那一档:App 拿它决定最长录多久;给全局 600 秒会让
|
|
164
|
+
* host(官方云端 120 秒)那一路录到一半被上游拒掉。一个可用 provider 都没有时才回全局闸。
|
|
165
|
+
*/
|
|
166
|
+
function limitsView() {
|
|
167
|
+
const daily = typeof store.limits === 'function' ? store.limits() : { dailySeconds: 0, dailyRequests: 0 };
|
|
168
|
+
const usage = typeof store.usage === 'function' ? store.usage() : { seconds: 0, requests: 0 };
|
|
169
|
+
const defaultId = registry.defaultId();
|
|
170
|
+
const provider = defaultId ? registry.get(defaultId) : null;
|
|
171
|
+
const active = provider && registry.statusOf(provider.id) === PROVIDER_STATUS.AVAILABLE ? limitsOf(provider) : null;
|
|
172
|
+
return {
|
|
173
|
+
maxSeconds: active ? active.maxSeconds : GLOBAL_MAX_SECONDS,
|
|
174
|
+
maxBytes: active ? active.maxBytes : GLOBAL_MAX_BYTES,
|
|
175
|
+
dailySecondsUsed: usage.seconds || 0,
|
|
176
|
+
dailySecondsLimit: daily.dailySeconds || 0,
|
|
177
|
+
dailyRequestsUsed: usage.requests || 0,
|
|
178
|
+
dailyRequestsLimit: daily.dailyRequests || 0,
|
|
179
|
+
// 每分钟请求数上限:挡「一句话拆几十段猛刷」把上游次数打爆,与每日额度是两把闸。
|
|
180
|
+
requestsPerMinute: rateLimitPerMinute,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* 能力表。形状严格按契约,另加 lead 要求的一格 `limits`(单次上限 + 每日已用 / 上限)。
|
|
186
|
+
* `providers` 里每一行都带 `status`;不可用的 provider 不进可用项(App 只认 available)。
|
|
187
|
+
*/
|
|
188
|
+
function capabilities() {
|
|
189
|
+
return {
|
|
190
|
+
ok: true,
|
|
191
|
+
enabled: store.enabled() === true,
|
|
192
|
+
providers: registry.capabilities(),
|
|
193
|
+
// 一家都可用时 `default` 为 null:App 据此不画语音按钮,而不是画一个点了就 503 的按钮。
|
|
194
|
+
default: registry.availableIds().length > 0 ? (registry.defaultId() || null) : null,
|
|
195
|
+
features,
|
|
196
|
+
lang: { auto: true, available: langView().available },
|
|
197
|
+
limits: limitsView(),
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** 配额检查:超了回 `voice-quota`(429)。 */
|
|
202
|
+
function ensureQuota() {
|
|
203
|
+
const limits = limitsView();
|
|
204
|
+
if (limits.dailySecondsLimit > 0 && limits.dailySecondsUsed >= limits.dailySecondsLimit) {
|
|
205
|
+
throw voiceError(VOICE_ERRORS.QUOTA, '今天的语音识别时长已用完');
|
|
206
|
+
}
|
|
207
|
+
if (limits.dailyRequestsLimit > 0 && limits.dailyRequestsUsed >= limits.dailyRequestsLimit) {
|
|
208
|
+
throw voiceError(VOICE_ERRORS.QUOTA, '今天的语音识别次数已用完');
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* 每分钟请求数限流(按 provider 分开算)。
|
|
214
|
+
*
|
|
215
|
+
* 只有**真正要打上游**的调用才走它:被配额 / 参数挡下的请求不算一次。
|
|
216
|
+
*/
|
|
217
|
+
function ensureRateLimit(providerId) {
|
|
218
|
+
if (rateLimitPerMinute <= 0) return;
|
|
219
|
+
const nowMs = now().getTime();
|
|
220
|
+
const hits = (rateBuckets.get(providerId) || []).filter((at) => nowMs - at < RATE_LIMIT_WINDOW_MS);
|
|
221
|
+
if (hits.length >= rateLimitPerMinute) {
|
|
222
|
+
rateBuckets.set(providerId, hits);
|
|
223
|
+
throw voiceError(VOICE_ERRORS.RATE_LIMITED, '语音识别请求太频繁,请稍后再试');
|
|
224
|
+
}
|
|
225
|
+
hits.push(nowMs);
|
|
226
|
+
rateBuckets.set(providerId, hits);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* 带超时地调一次上游。
|
|
231
|
+
*
|
|
232
|
+
* 适配器内部不重试(各家的口径),但**必须有上限**:弱网下上游不返回时,不设超时等于把
|
|
233
|
+
* 手机的等待和网关的并发槽一起占住。超时后通知适配器取消(signal),错误收成
|
|
234
|
+
* `voice-timeout`(502),与契约一致。
|
|
235
|
+
*/
|
|
236
|
+
async function callProvider(provider, { config, audio, hints, signal }) {
|
|
237
|
+
const controller = new AbortController();
|
|
238
|
+
let timer = null;
|
|
239
|
+
const timeout = new Promise((_, reject) => {
|
|
240
|
+
timer = setTimeout(() => {
|
|
241
|
+
try { controller.abort(); } catch { /* ignore */ }
|
|
242
|
+
reject(voiceError(VOICE_ERRORS.TIMEOUT, `${provider.name}识别超时`));
|
|
243
|
+
}, transcribeTimeoutMs);
|
|
244
|
+
timer.unref?.();
|
|
245
|
+
});
|
|
246
|
+
// 适配器可能不认 signal:光 abort 不够,必须让「等太久了」这条自己先把 Promise 判负。
|
|
247
|
+
const running = Promise.resolve().then(() => provider.transcribe({
|
|
248
|
+
config,
|
|
249
|
+
audio,
|
|
250
|
+
hints,
|
|
251
|
+
signal: controller.signal,
|
|
252
|
+
log,
|
|
253
|
+
}));
|
|
254
|
+
// 输了竞速之后 running 仍可能再抛(上游迟到的失败):吞掉,别变成未处理拒绝。
|
|
255
|
+
running.catch(() => {});
|
|
256
|
+
const onAbort = () => { try { controller.abort(); } catch { /* ignore */ } };
|
|
257
|
+
if (signal && typeof signal.addEventListener === 'function') {
|
|
258
|
+
if (signal.aborted) onAbort();
|
|
259
|
+
else signal.addEventListener('abort', onAbort, { once: true });
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
return await Promise.race([running, timeout]);
|
|
263
|
+
} finally {
|
|
264
|
+
clearTimeout(timer);
|
|
265
|
+
if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* 选 provider:显式指定的必须存在且可用;没指定就用默认。
|
|
271
|
+
*
|
|
272
|
+
* 「不静默换家」(契约 §5.2):手机指定了某家而它不可用时直接报错,不要偷偷改用别家 ——
|
|
273
|
+
* 用户以为在用自己的 key,其实在花官方额度,这种账没人算得清。
|
|
274
|
+
*/
|
|
275
|
+
function resolveProvider(providerId) {
|
|
276
|
+
const wanted = typeof providerId === 'string' ? providerId.trim() : '';
|
|
277
|
+
const id = wanted || registry.defaultId();
|
|
278
|
+
if (!id) throw voiceError(VOICE_ERRORS.PROVIDER_MISSING, '还没有可用的语音识别服务');
|
|
279
|
+
const provider = registry.get(id);
|
|
280
|
+
if (!provider) throw voiceError(VOICE_ERRORS.PROVIDER_MISSING, `没有叫 ${id} 的语音服务`);
|
|
281
|
+
// 端侧识别在手机上跑:能力表里有一行只是为了显示,不能把它当远端 provider「调用」。
|
|
282
|
+
// 「不静默换家」同样适用:显式点名它就直接报错,不偷偷改去别家。
|
|
283
|
+
if (provider.capabilityOnly === true) {
|
|
284
|
+
throw voiceError(VOICE_ERRORS.PROVIDER_UNAVAILABLE, `${provider.name}只能在手机本地执行,电脑侧不能调用`);
|
|
285
|
+
}
|
|
286
|
+
const status = registry.statusOf(id);
|
|
287
|
+
if (status === PROVIDER_STATUS.UNCONFIGURED) {
|
|
288
|
+
throw voiceError(VOICE_ERRORS.PROVIDER_UNAVAILABLE, `${provider.name}还没配置好`);
|
|
289
|
+
}
|
|
290
|
+
if (status !== PROVIDER_STATUS.AVAILABLE) {
|
|
291
|
+
throw voiceError(VOICE_ERRORS.PROVIDER_UNAVAILABLE, `${provider.name}现在不可用`);
|
|
292
|
+
}
|
|
293
|
+
return provider;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* 语言码归一:按**目标 provider 自己**的 `languages` 折算。
|
|
298
|
+
*
|
|
299
|
+
* 不能用能力表聚合出来的并集:那是给面板渲染用的,聚合后的 `auto` 塞给只认具体语种的
|
|
300
|
+
* 适配器(如 Azure 短音频接口)会被明确拒掉。`lang.pickProviderLang` 支持传单个 provider
|
|
301
|
+
* 对象,这里就传它,不另写一套折算表。
|
|
302
|
+
*/
|
|
303
|
+
function pickLang(provider, requested) {
|
|
304
|
+
const wanted = typeof requested === 'string' && requested.trim() ? requested.trim() : 'auto';
|
|
305
|
+
if (langModule && typeof langModule.pickProviderLang === 'function') {
|
|
306
|
+
try {
|
|
307
|
+
return langModule.pickProviderLang(provider, wanted);
|
|
308
|
+
} catch { /* 语言模块自己炸了不该挡住识别,走下面的朴素判定 */ }
|
|
309
|
+
}
|
|
310
|
+
if (wanted === 'auto') return 'auto';
|
|
311
|
+
const languages = Array.isArray(provider.languages) ? provider.languages : [];
|
|
312
|
+
return languages.includes(wanted) ? wanted : 'auto';
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** 工作区词库的进程内缓存:cwd → { at, value }。按短 TTL 失效,别每句都扫一次盘。 */
|
|
316
|
+
const lexiconCache = new Map();
|
|
317
|
+
const LEXICON_TTL_MS = 60_000;
|
|
318
|
+
const LEXICON_CACHE_MAX = 32;
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* 取工作区词库(带缓存)。
|
|
322
|
+
*
|
|
323
|
+
* 词库的工作区那一层要枚举目录、读几个文件头,**每句都现场扫太贵**(一次听写可能十几句)。
|
|
324
|
+
* 按 cwd 缓存 60 秒:同一目录里连续说话共用一份;换目录 / 过了 TTL 自然重扫。缓存只存
|
|
325
|
+
* 「工作区术语」这一层 —— 用户改错映射与会话上下文是每句都可能变的,走下面那份即时生成。
|
|
326
|
+
*/
|
|
327
|
+
function workspaceLexicon(cwd) {
|
|
328
|
+
if (typeof cwd !== 'string' || !cwd) return null;
|
|
329
|
+
const nowMs = now().getTime();
|
|
330
|
+
const hit = lexiconCache.get(cwd);
|
|
331
|
+
if (hit && nowMs - hit.at < LEXICON_TTL_MS) return hit.value;
|
|
332
|
+
let value = null;
|
|
333
|
+
try {
|
|
334
|
+
value = lexiconModule.buildLexicon({ cwd }) || null;
|
|
335
|
+
} catch { /* 词库生成失败不影响识别 */ }
|
|
336
|
+
if (lexiconCache.size >= LEXICON_CACHE_MAX) {
|
|
337
|
+
// 简单按插入顺序淘汰最老的一条:cwd 数量本来就少,不值得为它做 LRU。
|
|
338
|
+
const oldest = lexiconCache.keys().next().value;
|
|
339
|
+
if (oldest !== undefined) lexiconCache.delete(oldest);
|
|
340
|
+
}
|
|
341
|
+
lexiconCache.set(cwd, { at: nowMs, value });
|
|
342
|
+
return value;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** 合并两层词库:去重(大小写不敏感)后限长。 */
|
|
346
|
+
function mergeHotwords(...lists) {
|
|
347
|
+
const out = [];
|
|
348
|
+
const seen = new Set();
|
|
349
|
+
for (const list of lists) {
|
|
350
|
+
if (!Array.isArray(list)) continue;
|
|
351
|
+
for (const word of list) {
|
|
352
|
+
if (typeof word !== 'string' || !word.trim()) continue;
|
|
353
|
+
const key = word.trim().toLowerCase();
|
|
354
|
+
if (seen.has(key)) continue;
|
|
355
|
+
seen.add(key);
|
|
356
|
+
out.push(word.trim());
|
|
357
|
+
if (out.length >= 200) return out;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return out;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* 词库:调用方给了生成素材(cwd / 会话消息 / 用户词)才生成;缺模块就原样返回。
|
|
365
|
+
*
|
|
366
|
+
* 返回的 `corrections` 是「听错 → 改对」的精确映射,会原样传给后处理 —— 少了它只能退回
|
|
367
|
+
* 近音纠错,用户自己改过的词下次还会错(语言组的口径,见 `lexicon.buildLexicon`)。
|
|
368
|
+
*/
|
|
369
|
+
function buildHints(provider, input) {
|
|
370
|
+
const source = input && typeof input === 'object' ? input : {};
|
|
371
|
+
const hints = {
|
|
372
|
+
lang: pickLang(provider, source.lang),
|
|
373
|
+
hotwords: Array.isArray(source.hotwords) ? source.hotwords.filter((word) => typeof word === 'string').slice(0, 200) : [],
|
|
374
|
+
context: typeof source.context === 'string' ? source.context.slice(0, 4000) : '',
|
|
375
|
+
corrections: [],
|
|
376
|
+
userDict: source.userDict,
|
|
377
|
+
};
|
|
378
|
+
if (!lexiconModule || typeof lexiconModule.buildLexicon !== 'function' || !(source.cwd || source.userDict || source.sessionMessages)) {
|
|
379
|
+
return hints;
|
|
380
|
+
}
|
|
381
|
+
const workspaceLexiconOf = workspaceLexicon(source.cwd);
|
|
382
|
+
let dynamic = null;
|
|
383
|
+
try {
|
|
384
|
+
// 只带会变的那两层:用户改错与会话最近几条消息,不碰磁盘。
|
|
385
|
+
dynamic = lexiconModule.buildLexicon({ userDict: source.userDict, sessionMessages: source.sessionMessages }) || null;
|
|
386
|
+
} catch { /* 词库生成失败不影响识别 */ }
|
|
387
|
+
hints.hotwords = mergeHotwords(
|
|
388
|
+
dynamic && dynamic.hotwords,
|
|
389
|
+
workspaceLexiconOf && workspaceLexiconOf.hotwords,
|
|
390
|
+
hints.hotwords,
|
|
391
|
+
);
|
|
392
|
+
const context = (workspaceLexiconOf && workspaceLexiconOf.context) || (dynamic && dynamic.context) || hints.context;
|
|
393
|
+
if (typeof context === 'string' && context) hints.context = context.slice(0, 4000);
|
|
394
|
+
if (dynamic && Array.isArray(dynamic.corrections)) hints.corrections = dynamic.corrections.slice(0, 200);
|
|
395
|
+
if (!hints.corrections.length && workspaceLexiconOf && Array.isArray(workspaceLexiconOf.corrections)) {
|
|
396
|
+
hints.corrections = workspaceLexiconOf.corrections.slice(0, 200);
|
|
397
|
+
}
|
|
398
|
+
return hints;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* 在 `buildHints` 之上叠一层「自动学到的词库」:热词并进 hints,听错→改对映射并进
|
|
403
|
+
* corrections(按 heard 去重,已有优先)。没学过东西时原样返回,与没有这层完全一致。
|
|
404
|
+
*/
|
|
405
|
+
function mergeLearnedHints(provider, input) {
|
|
406
|
+
const hints = buildHints(provider, input);
|
|
407
|
+
const learned = learnedStore && typeof learnedStore.snapshot === 'function' ? learnedStore.snapshot() : null;
|
|
408
|
+
if (!learned) return hints;
|
|
409
|
+
if (Array.isArray(learned.hotwords) && learned.hotwords.length) {
|
|
410
|
+
hints.hotwords = mergeHotwords(learned.hotwords, hints.hotwords);
|
|
411
|
+
}
|
|
412
|
+
if (Array.isArray(learned.corrections) && learned.corrections.length) {
|
|
413
|
+
const merged = Array.isArray(hints.corrections) ? hints.corrections.slice() : [];
|
|
414
|
+
const seen = new Set(merged.map((pair) => String(pair && pair.heard || '').toLowerCase()));
|
|
415
|
+
for (const pair of learned.corrections) {
|
|
416
|
+
if (!pair || typeof pair.heard !== 'string' || typeof pair.corrected !== 'string') continue;
|
|
417
|
+
const key = pair.heard.toLowerCase();
|
|
418
|
+
if (!key || seen.has(key)) continue;
|
|
419
|
+
seen.add(key);
|
|
420
|
+
merged.push({ heard: pair.heard, corrected: pair.corrected });
|
|
421
|
+
}
|
|
422
|
+
if (merged.length) hints.corrections = merged.slice(0, 200);
|
|
423
|
+
}
|
|
424
|
+
return hints;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** 后处理:有模块才跑;它抛错就用原文(定稿失败不该比没有后处理更糟)。 */
|
|
428
|
+
function postprocess(raw, context) {
|
|
429
|
+
const result = {
|
|
430
|
+
text: typeof raw.text === 'string' ? raw.text : '',
|
|
431
|
+
lang: raw.lang,
|
|
432
|
+
corrected: false,
|
|
433
|
+
};
|
|
434
|
+
if (!postprocessModule || typeof postprocessModule.normalize !== 'function') return result;
|
|
435
|
+
try {
|
|
436
|
+
const normalized = postprocessModule.normalize(result.text, {
|
|
437
|
+
lang: result.lang || context.hints.lang,
|
|
438
|
+
hotwords: context.hints.hotwords,
|
|
439
|
+
// 用户「听错 → 改对」的精确映射必须一起带上,否则只剩近音纠错(见 lexicon 文件头)。
|
|
440
|
+
corrections: Array.isArray(context.hints.corrections) ? context.hints.corrections : [],
|
|
441
|
+
userDict: context.hints.userDict,
|
|
442
|
+
punctuation: true,
|
|
443
|
+
itn: true,
|
|
444
|
+
filler: true,
|
|
445
|
+
});
|
|
446
|
+
if (normalized && typeof normalized.text === 'string') {
|
|
447
|
+
result.text = normalized.text;
|
|
448
|
+
result.corrected = normalized.corrected === true;
|
|
449
|
+
if (!result.lang && typeof normalized.lang === 'string' && normalized.lang) result.lang = normalized.lang;
|
|
450
|
+
}
|
|
451
|
+
} catch { /* 用原文 */ }
|
|
452
|
+
return result;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** 语言兜底:provider 没报语种、又有本地判断时补一格(官方云端只报 auto)。 */
|
|
456
|
+
function detectLang(text, current) {
|
|
457
|
+
if (current && current !== 'auto') return current;
|
|
458
|
+
if (!langModule || typeof langModule.detectLang !== 'function') return current;
|
|
459
|
+
try {
|
|
460
|
+
const detected = langModule.detectLang(text);
|
|
461
|
+
if (detected && typeof detected.lang === 'string' && detected.lang && detected.lang !== 'auto') return detected.lang;
|
|
462
|
+
return current;
|
|
463
|
+
} catch {
|
|
464
|
+
return current;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* 整段识别。
|
|
470
|
+
*
|
|
471
|
+
* @param {{ audio: Buffer, providerId?: string, lang?: string, hints?: object, signal?: AbortSignal }} request
|
|
472
|
+
* @returns {Promise<{ text: string, lang?: string, provider: string, durationMs: number, corrected: boolean }>}
|
|
473
|
+
*/
|
|
474
|
+
async function transcribe(request) {
|
|
475
|
+
if (store.enabled() !== true) throw voiceError(VOICE_ERRORS.DISABLED, '语音输入已关闭');
|
|
476
|
+
if (!request || !Buffer.isBuffer(request.audio)) {
|
|
477
|
+
throw voiceError(VOICE_ERRORS.INVALID_AUDIO, '需要 WAV 音频字节');
|
|
478
|
+
}
|
|
479
|
+
const provider = resolveProvider(request.providerId);
|
|
480
|
+
if (provider.batch !== true || typeof provider.transcribe !== 'function') {
|
|
481
|
+
throw voiceError(VOICE_ERRORS.PROVIDER_UNAVAILABLE, `${provider.name}不支持整段识别`);
|
|
482
|
+
}
|
|
483
|
+
const limits = limitsOf(provider);
|
|
484
|
+
if (request.audio.length > limits.maxBytes) {
|
|
485
|
+
throw voiceError(VOICE_ERRORS.TOO_LARGE, `音频超过上限(${Math.floor(limits.maxBytes / 1024 / 1024)} MiB)`);
|
|
486
|
+
}
|
|
487
|
+
const parsed = parseWav(request.audio);
|
|
488
|
+
if (!parsed.ok) throw voiceError(parsed.code, parsed.message);
|
|
489
|
+
if (parsed.durationMs > limits.maxSeconds * 1000) {
|
|
490
|
+
throw voiceError(VOICE_ERRORS.TOO_LONG, `音频超过上限(${limits.maxSeconds} 秒)`);
|
|
491
|
+
}
|
|
492
|
+
ensureQuota();
|
|
493
|
+
// 流式降级那条路在 openStream 里已经记过一次限流,不要一句话算两次。
|
|
494
|
+
if (request.skipRateLimit !== true) ensureRateLimit(provider.id);
|
|
495
|
+
const hints = mergeLearnedHints(provider, { ...(request.hints || {}), lang: request.lang });
|
|
496
|
+
const config = registry.configOf(provider.id);
|
|
497
|
+
let raw;
|
|
498
|
+
try {
|
|
499
|
+
raw = await callProvider(provider, { config, audio: request.audio, hints, signal: request.signal });
|
|
500
|
+
} catch (error) {
|
|
501
|
+
throw normalizeProviderError(error, provider.name);
|
|
502
|
+
}
|
|
503
|
+
const processed = postprocess(raw, { hints });
|
|
504
|
+
const lang = detectLang(processed.text, processed.lang);
|
|
505
|
+
if (typeof store.noteUsage === 'function') store.noteUsage({ seconds: Math.round(parsed.durationMs / 1000), requests: 1 });
|
|
506
|
+
return {
|
|
507
|
+
text: processed.text,
|
|
508
|
+
...(lang ? { lang } : {}),
|
|
509
|
+
provider: provider.id,
|
|
510
|
+
durationMs: parsed.durationMs,
|
|
511
|
+
corrected: processed.corrected === true,
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* 开一条流式会话。
|
|
517
|
+
*
|
|
518
|
+
* provider 支持流式 → 直接把 PCM 塞给适配器,`partial` / `final` 原样转发(final 再过一遍
|
|
519
|
+
* 后处理与用量记账)。
|
|
520
|
+
* provider 只支持整段(宿主官方两家就是这样)→ 网关内部把 PCM 攒起来,`finish()` 时
|
|
521
|
+
* 包成 WAV 走一次 `transcribe`,只发 `final`。这是契约规定的降级,不是错误。
|
|
522
|
+
*
|
|
523
|
+
* @param {object} request
|
|
524
|
+
* @param {string} [request.providerId]
|
|
525
|
+
* @param {string} [request.lang]
|
|
526
|
+
* @param {object} [request.hints]
|
|
527
|
+
* @param {(info: {streaming: boolean, provider: string}) => void} request.onReady
|
|
528
|
+
* @param {(text: string) => void} [request.onPartial]
|
|
529
|
+
* @param {(result: object) => void} [request.onFinal]
|
|
530
|
+
* @param {(error: object) => void} [request.onError]
|
|
531
|
+
* @returns {object} 会话:`{ providerId, streaming, push(pcm, seq), finish(), cancel(), bytes }`
|
|
532
|
+
*/
|
|
533
|
+
function openStream(request) {
|
|
534
|
+
if (store.enabled() !== true) throw voiceError(VOICE_ERRORS.DISABLED, '语音输入已关闭');
|
|
535
|
+
const provider = resolveProvider(request && request.providerId);
|
|
536
|
+
ensureRateLimit(provider.id);
|
|
537
|
+
const hints = mergeLearnedHints(provider, { ...(request.hints || {}), lang: request.lang });
|
|
538
|
+
const limits = limitsOf(provider);
|
|
539
|
+
const config = registry.configOf(provider.id);
|
|
540
|
+
const abort = new AbortController();
|
|
541
|
+
let closed = false;
|
|
542
|
+
let bytes = 0;
|
|
543
|
+
let startedAt = now().getTime();
|
|
544
|
+
const chunks = [];
|
|
545
|
+
let adapter = null;
|
|
546
|
+
|
|
547
|
+
const fail = (error) => {
|
|
548
|
+
if (closed) return;
|
|
549
|
+
closed = true;
|
|
550
|
+
const normalized = normalizeProviderError(error, provider.name);
|
|
551
|
+
try { request.onError?.(normalized); } catch { /* 回调抛错不该反噬连接 */ }
|
|
552
|
+
};
|
|
553
|
+
|
|
554
|
+
const finishBatch = async (seq) => {
|
|
555
|
+
if (closed) return;
|
|
556
|
+
try {
|
|
557
|
+
const pcm = Buffer.concat(chunks);
|
|
558
|
+
if (pcm.length === 0) throw voiceError(VOICE_ERRORS.INVALID_AUDIO, '没有收到音频');
|
|
559
|
+
const wav = buildWav(pcm);
|
|
560
|
+
const result = await transcribe({
|
|
561
|
+
audio: wav,
|
|
562
|
+
providerId: provider.id,
|
|
563
|
+
lang: hints.lang,
|
|
564
|
+
hints: { hotwords: hints.hotwords, context: hints.context, corrections: hints.corrections, userDict: hints.userDict },
|
|
565
|
+
signal: abort.signal,
|
|
566
|
+
skipRateLimit: true,
|
|
567
|
+
});
|
|
568
|
+
if (closed) return;
|
|
569
|
+
closed = true;
|
|
570
|
+
try { request.onFinal?.({ ...result, streaming: false }); } catch { /* ignore */ }
|
|
571
|
+
} catch (error) {
|
|
572
|
+
fail(error);
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
|
|
576
|
+
if (provider.streaming === true && typeof provider.stream === 'function') {
|
|
577
|
+
adapter = provider.stream({
|
|
578
|
+
config,
|
|
579
|
+
hints,
|
|
580
|
+
signal: abort.signal,
|
|
581
|
+
onPartial: (text) => {
|
|
582
|
+
if (closed || typeof text !== 'string' || !text) return;
|
|
583
|
+
try { request.onPartial?.(text); } catch { /* ignore */ }
|
|
584
|
+
},
|
|
585
|
+
onFinal: (text, info) => {
|
|
586
|
+
if (closed) return;
|
|
587
|
+
const raw = { text: typeof text === 'string' ? text : '', lang: info && typeof info.lang === 'string' ? info.lang : undefined };
|
|
588
|
+
const processed = postprocess(raw, { hints });
|
|
589
|
+
const lang = detectLang(processed.text, processed.lang);
|
|
590
|
+
// 用量按真实收到的 PCM 算,不用墙上时钟:网络慢不等于用户说了那么久。
|
|
591
|
+
const seconds = Math.round(bytes / protocol.BYTES_PER_SECOND);
|
|
592
|
+
if (typeof store.noteUsage === 'function') store.noteUsage({ seconds: Math.max(0, seconds), requests: 1 });
|
|
593
|
+
closed = true;
|
|
594
|
+
try {
|
|
595
|
+
request.onFinal?.({
|
|
596
|
+
text: processed.text,
|
|
597
|
+
...(lang ? { lang } : {}),
|
|
598
|
+
provider: provider.id,
|
|
599
|
+
durationMs: Math.max(0, now().getTime() - startedAt),
|
|
600
|
+
corrected: processed.corrected === true,
|
|
601
|
+
streaming: true,
|
|
602
|
+
});
|
|
603
|
+
} catch { /* ignore */ }
|
|
604
|
+
},
|
|
605
|
+
onError: (error) => {
|
|
606
|
+
// 取消是客户端主动的:网关层不把它当失败帧(WS 层自己会忽略)。
|
|
607
|
+
if (error && error.cancelled === true) { closed = true; return; }
|
|
608
|
+
fail(error);
|
|
609
|
+
},
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
try {
|
|
614
|
+
request.onReady?.({ streaming: provider.streaming === true, provider: provider.id });
|
|
615
|
+
} catch { /* ignore */ }
|
|
616
|
+
|
|
617
|
+
return {
|
|
618
|
+
providerId: provider.id,
|
|
619
|
+
streaming: provider.streaming === true,
|
|
620
|
+
limits,
|
|
621
|
+
get bytes() { return bytes; },
|
|
622
|
+
get startedAt() { return startedAt; },
|
|
623
|
+
/**
|
|
624
|
+
* 塞一包 PCM。超时长 / 超体积立刻报错并关会话(不然会一直收,手机那边看着像卡死)。
|
|
625
|
+
*/
|
|
626
|
+
push(pcm, seq) {
|
|
627
|
+
if (closed) return;
|
|
628
|
+
const chunk = Buffer.isBuffer(pcm) ? pcm : Buffer.alloc(0);
|
|
629
|
+
if (chunk.length === 0) return;
|
|
630
|
+
bytes += chunk.length;
|
|
631
|
+
if (bytes > limits.maxBytes) { fail(voiceError(VOICE_ERRORS.TOO_LARGE, '音频超过上限')); return; }
|
|
632
|
+
if ((now().getTime() - startedAt) / 1000 > limits.maxSeconds) {
|
|
633
|
+
fail(voiceError(VOICE_ERRORS.TOO_LONG, `音频超过上限(${limits.maxSeconds} 秒)`));
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
if (adapter && typeof adapter.push === 'function') {
|
|
637
|
+
try {
|
|
638
|
+
adapter.push(chunk, seq);
|
|
639
|
+
} catch (error) {
|
|
640
|
+
fail(error);
|
|
641
|
+
}
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
chunks.push(chunk);
|
|
645
|
+
},
|
|
646
|
+
/** 结束:流式适配器走它自己的 finish,整段降级在这里现包 WAV 再识别。 */
|
|
647
|
+
async finish() {
|
|
648
|
+
if (closed) return;
|
|
649
|
+
if (adapter && typeof adapter.finish === 'function') {
|
|
650
|
+
try {
|
|
651
|
+
await adapter.finish();
|
|
652
|
+
} catch (error) {
|
|
653
|
+
fail(error);
|
|
654
|
+
}
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
await finishBatch();
|
|
658
|
+
},
|
|
659
|
+
/** 取消:先安静下来,再通知适配器收资源;之后任何回调都不再发。 */
|
|
660
|
+
cancel() {
|
|
661
|
+
if (closed) return;
|
|
662
|
+
closed = true;
|
|
663
|
+
try { abort.abort(); } catch { /* ignore */ }
|
|
664
|
+
try { adapter?.cancel?.(); } catch { /* ignore */ }
|
|
665
|
+
},
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* 面板用的总览:provider 列表(含配置字段与回显)+ 当前默认 + 限额用量。
|
|
671
|
+
*
|
|
672
|
+
* 这里会**带上每个 provider 的字段定义**;密钥只回 `set: true/false`(见 providerConfigView),
|
|
673
|
+
* 面板据此画 secret 输入框。
|
|
674
|
+
*/
|
|
675
|
+
function panelView() {
|
|
676
|
+
const rows = registry.list().map((provider) => {
|
|
677
|
+
const status = registry.statusOf(provider.id);
|
|
678
|
+
const view = providerConfigView(provider, registry.configOf(provider.id));
|
|
679
|
+
return {
|
|
680
|
+
...view,
|
|
681
|
+
batch: provider.batch === true,
|
|
682
|
+
streaming: provider.streaming === true,
|
|
683
|
+
languages: Array.isArray(provider.languages) ? provider.languages.slice() : [],
|
|
684
|
+
hotwords: provider.hotwords === true,
|
|
685
|
+
maxSeconds: provider.maxSeconds,
|
|
686
|
+
maxBytes: provider.maxBytes,
|
|
687
|
+
status,
|
|
688
|
+
// 只读条目(端侧)在面板里要标「仅手机本地」:不填配置、不选默认、不能删。
|
|
689
|
+
...(provider.capabilityOnly === true
|
|
690
|
+
? {
|
|
691
|
+
capabilityOnly: true,
|
|
692
|
+
selectable: false,
|
|
693
|
+
localOnly: true,
|
|
694
|
+
execution: typeof provider.execution === 'string' && provider.execution ? provider.execution : 'on-device',
|
|
695
|
+
requiresKey: false,
|
|
696
|
+
requiresHostConfig: false,
|
|
697
|
+
}
|
|
698
|
+
: {}),
|
|
699
|
+
};
|
|
700
|
+
});
|
|
701
|
+
return {
|
|
702
|
+
ok: true,
|
|
703
|
+
enabled: store.enabled() === true,
|
|
704
|
+
default: registry.defaultId() || '',
|
|
705
|
+
providers: rows,
|
|
706
|
+
features,
|
|
707
|
+
limits: limitsView(),
|
|
708
|
+
usage: typeof store.usage === 'function' ? store.usage() : { seconds: 0, requests: 0 },
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
return {
|
|
713
|
+
capabilities,
|
|
714
|
+
transcribe,
|
|
715
|
+
openStream,
|
|
716
|
+
panelView,
|
|
717
|
+
resolveProvider,
|
|
718
|
+
features,
|
|
719
|
+
limitsView,
|
|
720
|
+
// 面板写侧用(读侧走 panelView)。校验都收在这里,面板路由只搬结果。
|
|
721
|
+
setDefault(id) {
|
|
722
|
+
const provider = registry.get(id);
|
|
723
|
+
if (!provider) throw voiceError(VOICE_ERRORS.PROVIDER_MISSING, '没有这个语音服务');
|
|
724
|
+
if (provider.capabilityOnly === true) {
|
|
725
|
+
throw voiceError(VOICE_ERRORS.PROVIDER_UNAVAILABLE, `${provider.name}只能在手机本地执行,不能设为电脑侧默认`);
|
|
726
|
+
}
|
|
727
|
+
return store.setDefault(provider.id);
|
|
728
|
+
},
|
|
729
|
+
setEnabled(enabled) {
|
|
730
|
+
return store.setEnabled(enabled === true);
|
|
731
|
+
},
|
|
732
|
+
setProviderConfig(id, patch) {
|
|
733
|
+
const provider = registry.get(id);
|
|
734
|
+
if (!provider) throw voiceError(VOICE_ERRORS.PROVIDER_MISSING, '没有这个语音服务');
|
|
735
|
+
const { pickConfig } = require('./voice-provider.js');
|
|
736
|
+
return store.setConfig(provider.id, pickConfig(provider, patch));
|
|
737
|
+
},
|
|
738
|
+
store,
|
|
739
|
+
registry,
|
|
740
|
+
// 方便路由层直接转 HTTP 状态。
|
|
741
|
+
httpStatusOf,
|
|
742
|
+
errorPayload,
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
module.exports = { createVoiceGateway, limitsOf, normalizeProviderError, optionalModule, GLOBAL_MAX_SECONDS, GLOBAL_MAX_BYTES };
|