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,366 @@
1
+ // Deepgram 适配器:Nova-3 整段 + 流式(/v1/listen),Flux 只走流式(/v2/listen,TurnInfo 事件)。
2
+ // 鉴权头 Authorization: Token <key>;音频 16 kHz 线性 PCM 或整段 WAV,结果在适配器内解析成契约文本。
3
+ 'use strict';
4
+
5
+ const {
6
+ CODES,
7
+ VoiceError,
8
+ httpJson,
9
+ openWs,
10
+ baseLang,
11
+ cleanHotwords,
12
+ safeLog,
13
+ scrub,
14
+ closeWs,
15
+ waitForClose,
16
+ } = require('./_common');
17
+
18
+ const DEFAULT_BASE_URL = 'https://api.deepgram.com';
19
+ const DEFAULT_WS_URL = 'wss://api.deepgram.com';
20
+ const DEFAULT_MODEL = 'nova-3';
21
+ const SAMPLE_RATE = 16000;
22
+
23
+ const LANGUAGES = [
24
+ 'en', 'zh', 'ja', 'ko', 'es', 'fr', 'de', 'it', 'pt', 'nl', 'hi',
25
+ 'ru', 'pl', 'tr', 'uk', 'id', 'vi', 'th', 'sv', 'da', 'no', 'fi',
26
+ 'auto',
27
+ ];
28
+
29
+ const CONFIG_FIELDS = [
30
+ { key: 'apiKey', label: 'API Key', secret: true, required: true },
31
+ {
32
+ key: 'model',
33
+ type: 'select',
34
+ label: '模型',
35
+ secret: false,
36
+ required: false,
37
+ default: DEFAULT_MODEL,
38
+ options: ['nova-3', 'nova-3-general', 'flux-general-multi', 'flux-general-en'],
39
+ },
40
+ { key: 'baseUrl', label: 'API 地址(可选)', secret: false, required: false, placeholder: DEFAULT_BASE_URL },
41
+ { key: 'wsUrl', label: '流式地址(可选)', secret: false, required: false, placeholder: DEFAULT_WS_URL },
42
+ ];
43
+
44
+ function trimSlash(value) {
45
+ return String(value || '').replace(/\/+$/, '');
46
+ }
47
+
48
+ function keyOf(config) {
49
+ return String((config && config.apiKey) || '').trim();
50
+ }
51
+
52
+ function modelOf(config) {
53
+ return String((config && config.model) || DEFAULT_MODEL).trim();
54
+ }
55
+
56
+ function isFlux(model) {
57
+ return /^flux/i.test(model);
58
+ }
59
+
60
+ function baseUrlOf(config) {
61
+ return trimSlash((config && config.baseUrl) || DEFAULT_BASE_URL);
62
+ }
63
+
64
+ function wsUrlOf(config) {
65
+ return trimSlash((config && config.wsUrl) || DEFAULT_WS_URL);
66
+ }
67
+
68
+ function ready(config) {
69
+ return Boolean(keyOf(config));
70
+ }
71
+
72
+ function timeoutOf(config, fallback) {
73
+ const value = Number(config && config.timeoutMs);
74
+ return Number.isFinite(value) && value > 0 ? value : fallback;
75
+ }
76
+
77
+ /** 整段:POST /v1/listen,返回 results.channels[0].alternatives[0].transcript。 */
78
+ async function transcribe({ config, audio, hints, signal, log } = {}) {
79
+ const cfg = config || {};
80
+ const key = keyOf(cfg);
81
+ if (!key) throw new VoiceError(CODES.UNAVAILABLE, 'Deepgram 未配置 API Key');
82
+ if (!audio || !audio.length) throw new VoiceError(CODES.INVALID_AUDIO, 'Deepgram 收到空音频');
83
+ const model = modelOf(cfg);
84
+ // Flux 是会话式流式模型,只挂在 /v2/listen 上;整段请换 Nova。
85
+ if (isFlux(model)) {
86
+ throw new VoiceError(CODES.UNAVAILABLE, `Deepgram ${model} 只支持流式,整段识别请把模型改为 nova-3`);
87
+ }
88
+
89
+ const lang = baseLang(hints && hints.lang);
90
+ const params = new URLSearchParams();
91
+ params.set('model', model);
92
+ params.set('smart_format', 'true');
93
+ params.set('punctuate', 'true');
94
+ if (lang === 'auto') {
95
+ // 预录音频用 detect_language,不能再同时塞 language(两者互斥)
96
+ params.set('detect_language', 'true');
97
+ } else {
98
+ params.set('language', lang);
99
+ }
100
+ const hotwords = cleanHotwords(hints && hints.hotwords);
101
+ const keytermParam = /^nova-3/i.test(model) ? 'keyterm' : 'keywords';
102
+ for (const word of hotwords) params.append(keytermParam, word);
103
+
104
+ safeLog(log, `Deepgram 整段识别:model=${model} lang=${lang} hotwords=${hotwords.length}`);
105
+ const res = await httpJson(`${baseUrlOf(cfg)}/v1/listen?${params.toString()}`, {
106
+ headers: { Authorization: `Token ${key}`, 'Content-Type': 'audio/wav' },
107
+ body: audio,
108
+ timeoutMs: timeoutOf(cfg, 60000),
109
+ label: 'Deepgram 识别',
110
+ secrets: [key],
111
+ signal,
112
+ });
113
+
114
+ const channels = (res.json && res.json.results && res.json.results.channels) || [];
115
+ const alternative = (channels[0] && channels[0].alternatives && channels[0].alternatives[0]) || {};
116
+ const text = String(alternative.transcript || '').trim();
117
+ if (!text) throw new VoiceError(CODES.INVALID_AUDIO, 'Deepgram 没有识别到语音内容');
118
+ const detected = channels[0] && channels[0].detected_language;
119
+ const durationSeconds = Number(res.json && res.json.metadata && res.json.metadata.duration);
120
+ return {
121
+ text,
122
+ lang: detected ? baseLang(detected) : undefined,
123
+ durationMs: Number.isFinite(durationSeconds) && durationSeconds > 0 ? Math.round(durationSeconds * 1000) : undefined,
124
+ };
125
+ }
126
+
127
+ /** 流式:Nova 走 /v1/listen + CloseStream;Flux 走 /v2/listen + TurnInfo。 */
128
+ function stream({ config, hints, signal, onPartial, onFinal, onError } = {}) {
129
+ const cfg = config || {};
130
+ const key = keyOf(cfg);
131
+ const model = modelOf(cfg);
132
+ const flux = isFlux(model);
133
+ const lang = baseLang(hints && hints.lang);
134
+ const hotwords = cleanHotwords(hints && hints.hotwords);
135
+
136
+ let ws = null;
137
+ let finished = false;
138
+ let cancelled = false;
139
+ let failed = false;
140
+ const pending = [];
141
+ let pendingBytes = 0;
142
+ const PENDING_LIMIT = 4 * 1024 * 1024;
143
+
144
+ function emitPartial(text) {
145
+ if (cancelled || failed) return;
146
+ const value = String(text || '').trim();
147
+ if (!value) return;
148
+ if (typeof onPartial === 'function') {
149
+ try {
150
+ onPartial(value);
151
+ } catch {
152
+ // 回调抛错不能影响连接
153
+ }
154
+ }
155
+ }
156
+
157
+ function emitFinal(text) {
158
+ if (cancelled || failed) return;
159
+ const value = String(text || '').trim();
160
+ if (!value) return;
161
+ if (typeof onFinal === 'function') {
162
+ try {
163
+ onFinal(value);
164
+ } catch {
165
+ // 同上
166
+ }
167
+ }
168
+ }
169
+
170
+ function emitError(err) {
171
+ if (cancelled || failed) return;
172
+ failed = true;
173
+ if (typeof onError === 'function') {
174
+ try {
175
+ onError(err);
176
+ } catch {
177
+ // 同上
178
+ }
179
+ }
180
+ }
181
+
182
+ function buildStreamUrl() {
183
+ const params = new URLSearchParams();
184
+ params.set('encoding', 'linear16');
185
+ params.set('sample_rate', String(SAMPLE_RATE));
186
+ params.set('channels', '1');
187
+ params.set('model', model);
188
+ if (flux) {
189
+ // Flux 用 keyterm + language_hint;只有多语模型认 language_hint。
190
+ for (const word of hotwords) params.append('keyterm', word);
191
+ if (lang !== 'auto' && /multi/i.test(model)) params.append('language_hint', lang);
192
+ } else {
193
+ params.set('interim_results', 'true');
194
+ params.set('punctuate', 'true');
195
+ params.set('smart_format', 'true');
196
+ params.set('language', lang === 'auto' ? 'multi' : lang);
197
+ // Nova-3 的热词参数是 keyterm,旧的 keywords 参数在 nova-3 上已不生效。
198
+ for (const word of hotwords) params.append('keyterm', word);
199
+ }
200
+ const path = flux ? '/v2/listen' : '/v1/listen';
201
+ return `${wsUrlOf(cfg)}${path}?${params.toString()}`;
202
+ }
203
+
204
+ function handleNova(message) {
205
+ const type = message.type;
206
+ if (type === 'Results' || (type === undefined && message.is_final !== undefined)) {
207
+ const channel = message.channel || (message.channels && message.channels[0]) || {};
208
+ const alternative = (channel.alternatives && channel.alternatives[0]) || {};
209
+ const text = alternative.transcript || '';
210
+ if (message.is_final || message.speech_final) emitFinal(text);
211
+ else emitPartial(text);
212
+ return;
213
+ }
214
+ if (type === 'Error') {
215
+ const detail = scrub((message.description || message.message || message.reason || '未知错误'), [key]);
216
+ emitError(new VoiceError(CODES.FAILED, `Deepgram 流式错误:${detail}`));
217
+ return;
218
+ }
219
+ if (type === 'Metadata' && message.metadata && message.metadata.request_id) {
220
+ safeLog(null, `Deepgram 流式请求 ${message.metadata.request_id}`);
221
+ }
222
+ }
223
+
224
+ function handleFlux(message) {
225
+ const type = message.type;
226
+ if (type === 'TurnInfo') {
227
+ const text = message.transcript || '';
228
+ if (message.event === 'EndOfTurn') emitFinal(text);
229
+ else if (message.event === 'Update' || message.event === 'StartOfTurn' || message.event === 'TurnResumed') emitPartial(text);
230
+ // EagerEndOfTurn 只是可能结束,按部分结果处理(不上屏定稿)
231
+ else if (message.event === 'EagerEndOfTurn') emitPartial(text);
232
+ return;
233
+ }
234
+ if (type === 'Error') {
235
+ const code = String(message.code || '');
236
+ const mapped = /UNAUTH|FORBIDDEN|ACCESS/i.test(code) ? CODES.UNAVAILABLE : CODES.FAILED;
237
+ emitError(new VoiceError(mapped, `Deepgram Flux 错误:${scrub(message.description || code || '未知错误', [key])}`));
238
+ return;
239
+ }
240
+ if (type === 'ConfigureFailure') {
241
+ emitError(new VoiceError(CODES.UNAVAILABLE, `Deepgram Flux 配置被拒绝:${scrub(message.description || message.code || '', [key])}`));
242
+ return;
243
+ }
244
+ }
245
+
246
+ const readyPromise = (async () => {
247
+ if (!key) throw new VoiceError(CODES.UNAVAILABLE, 'Deepgram 未配置 API Key');
248
+ if (signal && signal.aborted) throw new VoiceError(CODES.CANCELLED, 'Deepgram 流式已取消', { cancelled: true });
249
+ const url = buildStreamUrl();
250
+ ws = await openWs(url, {
251
+ headers: { Authorization: `Token ${key}` },
252
+ signal,
253
+ timeoutMs: timeoutOf(cfg, 15000),
254
+ label: 'Deepgram 流式连接',
255
+ secrets: [key],
256
+ });
257
+ if (signal) {
258
+ // 契约要求 signal 能停掉已连上的会话;网关取消时还会再调一次 cancel()。
259
+ const onAbort = () => {
260
+ cancelled = true;
261
+ finished = true;
262
+ try {
263
+ ws.terminate();
264
+ } catch {
265
+ // 已经断了
266
+ }
267
+ };
268
+ signal.addEventListener('abort', onAbort, { once: true });
269
+ ws.once('close', () => signal.removeEventListener('abort', onAbort));
270
+ }
271
+ ws.on('message', (data, isBinary) => {
272
+ if (isBinary) return;
273
+ let message = null;
274
+ try {
275
+ message = JSON.parse(data.toString('utf8'));
276
+ } catch {
277
+ return;
278
+ }
279
+ if (flux) handleFlux(message);
280
+ else handleNova(message);
281
+ });
282
+ ws.on('error', (err) => {
283
+ emitError(new VoiceError(CODES.FAILED, `Deepgram 流式连接中断:${scrub(err && err.message, [key])}`));
284
+ });
285
+ ws.on('close', (code, reason) => {
286
+ if (finished || cancelled || failed) return;
287
+ const detail = scrub(reason ? reason.toString('utf8') : '', [key]);
288
+ emitError(new VoiceError(CODES.UNAVAILABLE, `Deepgram 流式连接被关闭(${code}${detail ? `:${detail}` : ''})`));
289
+ });
290
+ for (const chunk of pending.splice(0)) ws.send(chunk);
291
+ pendingBytes = 0;
292
+ return true;
293
+ })();
294
+
295
+ // readyPromise 的错误交给 onError 收口;push/finish 仍可安全调用。
296
+ readyPromise.catch((err) => {
297
+ if (cancelled) return;
298
+ emitError(err instanceof VoiceError ? err : new VoiceError(CODES.FAILED, scrub(err && err.message, [key])));
299
+ });
300
+
301
+ return {
302
+ ready: readyPromise,
303
+ push(pcm) {
304
+ if (cancelled || failed || finished) return;
305
+ if (!pcm || !pcm.length) return;
306
+ const chunk = Buffer.isBuffer(pcm) ? pcm : Buffer.from(pcm);
307
+ if (ws && ws.readyState === 1) {
308
+ ws.send(chunk);
309
+ return;
310
+ }
311
+ if (pendingBytes + chunk.length > PENDING_LIMIT) return; // 连不上就别无限攒内存
312
+ pending.push(chunk);
313
+ pendingBytes += chunk.length;
314
+ },
315
+ async finish() {
316
+ if (finished) return;
317
+ finished = true;
318
+ try {
319
+ await readyPromise;
320
+ } catch {
321
+ return; // 连接没建起来,错误已经发过
322
+ }
323
+ if (!ws) return;
324
+ try {
325
+ ws.send(JSON.stringify({ type: 'CloseStream' }));
326
+ } catch {
327
+ // 连接已断
328
+ }
329
+ await waitForClose(ws, timeoutOf(cfg, 5000), signal);
330
+ await closeWs(ws);
331
+ },
332
+ async cancel() {
333
+ if (cancelled) return;
334
+ cancelled = true;
335
+ finished = true;
336
+ pending.length = 0;
337
+ if (ws) {
338
+ try {
339
+ ws.terminate();
340
+ } catch {
341
+ // 已经断了
342
+ }
343
+ }
344
+ },
345
+ /** 测试与网关都用不到,仅排障时看连接状态。 */
346
+ get socket() {
347
+ return ws;
348
+ },
349
+ };
350
+ }
351
+
352
+ module.exports = {
353
+ id: 'deepgram',
354
+ name: 'Deepgram',
355
+ kind: 'intl',
356
+ batch: true,
357
+ streaming: true,
358
+ languages: LANGUAGES,
359
+ hotwords: true,
360
+ maxSeconds: 600,
361
+ maxBytes: 25 * 1024 * 1024,
362
+ configFields: CONFIG_FIELDS,
363
+ ready,
364
+ transcribe,
365
+ stream,
366
+ };