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,401 @@
1
+ // 阿里云实时语音识别适配器:先用 AccessKeyId/Secret 走 CreateToken 现换 NLS 令牌,再连 NLS WebSocket。
2
+ // 令牌按 AccessKeyId + 地域缓存到过期前 60 秒;热词要预先在控制台建词表,所以 hotwords 标 false。
3
+ 'use strict';
4
+
5
+ const crypto = require('node:crypto');
6
+ const http = require('node:http');
7
+ const https = require('node:https');
8
+ const WebSocket = require('ws');
9
+
10
+ const DEFAULT_TOKEN_ENDPOINT = 'https://nls-meta.cn-shanghai.aliyuncs.com/';
11
+ const DEFAULT_ENDPOINT = 'wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1';
12
+ const TOKEN_API_VERSION = '2019-02-28';
13
+ const CONNECT_TIMEOUT_MS = 10_000;
14
+ const IDLE_TIMEOUT_MS = 15_000;
15
+ const FINISH_TIMEOUT_MS = 10_000;
16
+ const TOKEN_TIMEOUT_MS = 10_000;
17
+ const TOKEN_SAFETY_MS = 60_000;
18
+
19
+ // token 缓存只存在进程内:换 Key 或换地域会落到不同 key,不会串用。
20
+ const tokenCache = new Map();
21
+
22
+ const configFields = [
23
+ { key: 'accessKeyId', label: 'AccessKeyId', secret: false, required: true },
24
+ { key: 'accessKeySecret', label: 'AccessKeySecret', secret: true, required: true },
25
+ { key: 'appKey', label: '项目 AppKey', secret: false, required: true },
26
+ { key: 'region', label: '地域', secret: false, required: false, placeholder: 'cn-shanghai' },
27
+ { key: 'tokenEndpoint', label: '令牌地址(可选)', secret: false, required: false, placeholder: DEFAULT_TOKEN_ENDPOINT },
28
+ { key: 'endpoint', label: '识别地址(可选)', secret: false, required: false, placeholder: DEFAULT_ENDPOINT },
29
+ ];
30
+
31
+ function voiceError(code, message, extra) {
32
+ const err = new Error(message);
33
+ err.code = code;
34
+ if (extra) Object.assign(err, extra);
35
+ return err;
36
+ }
37
+
38
+ function configReady(config) {
39
+ return Boolean(
40
+ config
41
+ && typeof config.accessKeyId === 'string' && config.accessKeyId.trim()
42
+ && typeof config.accessKeySecret === 'string' && config.accessKeySecret.trim()
43
+ && typeof config.appKey === 'string' && config.appKey.trim(),
44
+ );
45
+ }
46
+
47
+ function percentEncode(value) {
48
+ return encodeURIComponent(String(value))
49
+ .replace(/\+/g, '%20')
50
+ .replace(/\*/g, '%2A')
51
+ .replace(/%7E/g, '~');
52
+ }
53
+
54
+ // RPC 风格签名:参数按字典序拼接后 percentEncode,再用 "secret&" 做 HMAC-SHA1。
55
+ function rpcSignature(params, accessKeySecret) {
56
+ const canonical = Object.keys(params)
57
+ .sort()
58
+ .map((k) => `${percentEncode(k)}=${percentEncode(params[k])}`)
59
+ .join('&');
60
+ const stringToSign = `GET&${percentEncode('/')}&${percentEncode(canonical)}`;
61
+ const signature = crypto.createHmac('sha1', `${accessKeySecret}&`).update(stringToSign, 'utf8').digest('base64');
62
+ return { canonical, signature };
63
+ }
64
+
65
+ function mapAliyunError(status, text) {
66
+ if (status === 401 || status === 403) return 'voice-provider-unavailable';
67
+ if (status === 429) return 'voice-rate-limited';
68
+ if (/InvalidAccessKey|SignatureDoesNotMatch|Forbidden/i.test(text)) return 'voice-provider-unavailable';
69
+ if (/quota|limit|exceed/i.test(text)) return 'voice-quota';
70
+ if (/Throttling|限流|流量/i.test(text)) return 'voice-rate-limited';
71
+ return 'voice-failed';
72
+ }
73
+
74
+ function mapTaskStatus(status, text) {
75
+ if (status === 401 || status === 403) return 'voice-provider-unavailable';
76
+ if (status === 429) return 'voice-rate-limited';
77
+ if (status >= 500) return 'voice-failed';
78
+ if (/quota|limit|exceed/i.test(text || '')) return 'voice-quota';
79
+ if (/token|auth|forbidden/i.test(text || '')) return 'voice-provider-unavailable';
80
+ if (status === 400) return 'voice-invalid-audio';
81
+ return 'voice-failed';
82
+ }
83
+
84
+ function requestHttp(urlString, { headers, body, signal, timeoutMs }) {
85
+ return new Promise((resolve, reject) => {
86
+ let url = null;
87
+ try { url = new URL(urlString); } catch { reject(voiceError('voice-provider-unavailable', '令牌地址不可用')); return; }
88
+ const mod = url.protocol === 'https:' ? https : http;
89
+ const payload = Buffer.from(body || '', 'utf8');
90
+ const reqHeaders = { ...headers, 'content-length': payload.length };
91
+ let settled = false;
92
+ const finish = (fn, value) => {
93
+ if (settled) return;
94
+ settled = true;
95
+ clearTimeout(timer);
96
+ if (signal) signal.removeEventListener('abort', onAbort);
97
+ fn(value);
98
+ };
99
+ const req = mod.request({
100
+ method: 'POST',
101
+ hostname: url.hostname,
102
+ port: url.port || undefined,
103
+ path: `${url.pathname}${url.search}`,
104
+ headers: reqHeaders,
105
+ }, (res) => {
106
+ const chunks = [];
107
+ res.on('data', (chunk) => chunks.push(chunk));
108
+ res.on('end', () => finish(resolve, { status: res.statusCode || 0, body: Buffer.concat(chunks).toString('utf8') }));
109
+ });
110
+ req.on('error', () => finish(reject, voiceError('voice-provider-unavailable', '阿里云连接失败')));
111
+ const timer = setTimeout(() => {
112
+ req.destroy();
113
+ finish(reject, voiceError('voice-timeout', '阿里云请求超时'));
114
+ }, timeoutMs);
115
+ const onAbort = () => {
116
+ req.destroy();
117
+ finish(reject, voiceError('voice-failed', '已取消', { cancelled: true }));
118
+ };
119
+ if (signal) {
120
+ if (signal.aborted) { onAbort(); return; }
121
+ signal.addEventListener('abort', onAbort, { once: true });
122
+ }
123
+ req.end(payload);
124
+ });
125
+ }
126
+
127
+ function tokenCacheKey(cfg) {
128
+ return `${cfg.accessKeyId.trim()}|${String(cfg.region || '').trim() || 'cn-shanghai'}`;
129
+ }
130
+
131
+ async function fetchToken(cfg, { signal } = {}) {
132
+ const accessKeyId = cfg.accessKeyId.trim();
133
+ const region = String(cfg.region || '').trim() || 'cn-shanghai';
134
+ const cacheKey = tokenCacheKey(cfg);
135
+ const cached = tokenCache.get(cacheKey);
136
+ if (cached && cached.expire - TOKEN_SAFETY_MS > Date.now()) return cached.id;
137
+
138
+ const params = {
139
+ AccessKeyId: accessKeyId,
140
+ Action: 'CreateToken',
141
+ Format: 'JSON',
142
+ RegionId: region,
143
+ SignatureMethod: 'HMAC-SHA1',
144
+ SignatureNonce: crypto.randomUUID(),
145
+ SignatureVersion: '1.0',
146
+ Timestamp: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
147
+ Version: TOKEN_API_VERSION,
148
+ };
149
+ const { canonical, signature } = rpcSignature(params, cfg.accessKeySecret.trim());
150
+ const body = `${canonical}&Signature=${percentEncode(signature)}`;
151
+ const endpoint = String(cfg.tokenEndpoint || '').trim() || DEFAULT_TOKEN_ENDPOINT;
152
+
153
+ const res = await requestHttp(endpoint, {
154
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
155
+ body,
156
+ signal,
157
+ timeoutMs: TOKEN_TIMEOUT_MS,
158
+ });
159
+ let data = null;
160
+ try { data = JSON.parse(res.body); } catch { data = null; }
161
+ const token = data && data.Token ? data.Token : null;
162
+ if (res.status >= 400 || !token || !token.Id) {
163
+ const code = data && data.Code ? data.Code : '';
164
+ throw voiceError(mapAliyunError(res.status, `${code} ${(data && data.Message) || ''}`), `阿里云令牌获取失败 ${res.status}${code ? ` ${code}` : ''}`);
165
+ }
166
+ const expire = Number(token.ExpireTime) || 0;
167
+ const expireMs = expire > 10_000_000_000 ? expire : expire * 1000;
168
+ tokenCache.set(cacheKey, { id: token.Id, expire: expireMs });
169
+ return token.Id;
170
+ }
171
+
172
+ module.exports = {
173
+ id: 'aliyun',
174
+ name: '阿里云实时语音识别',
175
+ kind: 'cn',
176
+ batch: false,
177
+ streaming: true,
178
+ languages: ['zh', 'en'],
179
+ hotwords: false,
180
+ maxSeconds: 300,
181
+ maxBytes: 8 * 1024 * 1024,
182
+ configFields,
183
+
184
+ ready(config) {
185
+ return configReady(config);
186
+ },
187
+
188
+ async transcribe({ config } = {}) {
189
+ if (!configReady(config)) throw voiceError('voice-provider-unavailable', '阿里云未配置 AccessKey / AppKey');
190
+ throw voiceError('voice-provider-unavailable', '阿里云实时语音识别只提供流式识别,请走流式入口');
191
+ },
192
+
193
+ stream({ config, hints, signal, onPartial, onFinal, onError } = {}) {
194
+ const cfg = config && typeof config === 'object' ? config : {};
195
+ const h = hints && typeof hints === 'object' ? hints : {};
196
+ const emitPartial = typeof onPartial === 'function' ? onPartial : () => {};
197
+ const emitFinal = typeof onFinal === 'function' ? onFinal : () => {};
198
+ const emitError = typeof onError === 'function' ? onError : () => {};
199
+ const noop = { push() {}, finish() {}, cancel() {} };
200
+
201
+ if (!configReady(cfg)) {
202
+ queueMicrotask(() => emitError(voiceError('voice-provider-unavailable', '阿里云未配置 AccessKey / AppKey')));
203
+ return noop;
204
+ }
205
+ if (signal && signal.aborted) {
206
+ queueMicrotask(() => emitError(voiceError('voice-failed', '已取消', { cancelled: true })));
207
+ return noop;
208
+ }
209
+
210
+ const appKey = cfg.appKey.trim();
211
+ const langKey = String(h.lang || 'auto').toLowerCase();
212
+ const endpoint = String(cfg.endpoint || '').trim() || DEFAULT_ENDPOINT;
213
+
214
+ let socket = null;
215
+ let opened = false;
216
+ let settled = false;
217
+ let finishRequested = false;
218
+ let lastText = '';
219
+ let finalPart = '';
220
+ const pendingAudio = [];
221
+ let idleTimer = null;
222
+ let finishTimer = null;
223
+ let tokenRequest = null;
224
+
225
+ const connectTimer = setTimeout(() => fail(voiceError('voice-timeout', '连接阿里云超时')), CONNECT_TIMEOUT_MS);
226
+
227
+ function clearTimers() {
228
+ clearTimeout(connectTimer);
229
+ clearTimeout(idleTimer);
230
+ clearTimeout(finishTimer);
231
+ idleTimer = null;
232
+ finishTimer = null;
233
+ }
234
+
235
+ function closeSocket() {
236
+ if (!socket) return;
237
+ try { socket.removeAllListeners(); } catch {}
238
+ try { socket.close(); } catch {}
239
+ try { socket.terminate(); } catch {}
240
+ socket = null;
241
+ }
242
+
243
+ function detachAbort() {
244
+ if (signal) signal.removeEventListener('abort', onAbort);
245
+ }
246
+
247
+ function fail(err) {
248
+ if (settled) return;
249
+ settled = true;
250
+ clearTimers();
251
+ detachAbort();
252
+ closeSocket();
253
+ emitError(err);
254
+ }
255
+
256
+ function succeed() {
257
+ if (settled) return;
258
+ settled = true;
259
+ clearTimers();
260
+ detachAbort();
261
+ closeSocket();
262
+ const langOut = langKey === 'zh' || langKey === 'en' ? langKey : undefined;
263
+ emitFinal(lastText.trim(), langOut ? { lang: langOut } : undefined);
264
+ }
265
+
266
+ function armIdle() {
267
+ clearTimeout(idleTimer);
268
+ idleTimer = setTimeout(() => fail(voiceError('voice-timeout', '阿里云长时间没有返回结果')), IDLE_TIMEOUT_MS);
269
+ }
270
+
271
+ function onAbort() {
272
+ if (settled) return;
273
+ settled = true;
274
+ clearTimers();
275
+ closeSocket();
276
+ emitError(voiceError('voice-failed', '已取消', { cancelled: true }));
277
+ }
278
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
279
+
280
+ function stopTask() {
281
+ if (!socket || socket.readyState !== WebSocket.OPEN) return;
282
+ socket.send(JSON.stringify({ header: { message_id: crypto.randomUUID(), task: 'stop' } }));
283
+ }
284
+
285
+ function handleMessage(raw) {
286
+ let msg = null;
287
+ try { msg = JSON.parse(typeof raw === 'string' ? raw : raw.toString('utf8')); } catch { return; }
288
+ const header = msg && msg.header ? msg.header : null;
289
+ if (!header) return;
290
+ const payload = msg.payload && typeof msg.payload === 'object' ? msg.payload : {};
291
+ const name = header.name || '';
292
+ const status = Number(header.status) || 0;
293
+ if (name === 'TaskFailed' || (status && status !== 20_000_000)) {
294
+ const code = mapTaskStatus(status, `${header.status_text || ''}`);
295
+ // 服务端拒了令牌(过期/吊销)就把它从缓存里摘掉,下一轮重新现换。
296
+ if (code === 'voice-provider-unavailable') tokenCache.delete(tokenCacheKey(cfg));
297
+ fail(voiceError(code, `阿里云识别失败 ${status}`));
298
+ return;
299
+ }
300
+ if (name === 'RecognitionResultChanged') {
301
+ if (typeof payload.output === 'string' && payload.output) {
302
+ if (payload.sentence_end === true) {
303
+ finalPart += payload.output;
304
+ lastText = finalPart;
305
+ } else {
306
+ lastText = finalPart + payload.output;
307
+ }
308
+ try { emitPartial(lastText); } catch {}
309
+ }
310
+ armIdle();
311
+ return;
312
+ }
313
+ if (name === 'RecognitionCompleted') {
314
+ if (typeof payload.output === 'string' && payload.output) lastText = payload.output;
315
+ succeed();
316
+ return;
317
+ }
318
+ armIdle();
319
+ }
320
+
321
+ function startSocket(token) {
322
+ if (settled) return;
323
+ const sep = endpoint.includes('?') ? '&' : '?';
324
+ const url = `${endpoint}${sep}token=${encodeURIComponent(token)}`;
325
+ try {
326
+ socket = new WebSocket(url, { handshakeTimeout: CONNECT_TIMEOUT_MS });
327
+ } catch {
328
+ fail(voiceError('voice-provider-unavailable', '阿里云识别地址不可用'));
329
+ return;
330
+ }
331
+ socket.on('open', () => {
332
+ opened = true;
333
+ clearTimeout(connectTimer);
334
+ socket.send(JSON.stringify({
335
+ header: {
336
+ appkey: appKey,
337
+ message_id: crypto.randomUUID(),
338
+ task: 'start',
339
+ format: 'pcm',
340
+ sample_rate: 16000,
341
+ enable_intermediate_result: true,
342
+ enable_punctuation_prediction: true,
343
+ enable_inverse_text_normalization: true,
344
+ },
345
+ }));
346
+ for (const pcm of pendingAudio) socket.send(pcm);
347
+ pendingAudio.length = 0;
348
+ if (finishRequested) stopTask();
349
+ armIdle();
350
+ });
351
+ socket.on('message', (data) => {
352
+ if (settled) return;
353
+ armIdle();
354
+ handleMessage(data);
355
+ });
356
+ socket.on('error', () => fail(voiceError('voice-provider-unavailable', '阿里云识别连接失败')));
357
+ socket.on('close', () => {
358
+ if (settled) return;
359
+ if (finishRequested) succeed();
360
+ else fail(voiceError('voice-provider-unavailable', '阿里云识别连接被关闭'));
361
+ });
362
+ }
363
+
364
+ tokenRequest = fetchToken(cfg, { signal });
365
+ tokenRequest.then((token) => {
366
+ if (settled) return;
367
+ startSocket(token);
368
+ }).catch((err) => {
369
+ if (settled) return;
370
+ fail(err);
371
+ });
372
+
373
+ return {
374
+ push(pcmBuf, _seq) {
375
+ if (settled || !pcmBuf || !pcmBuf.length) return;
376
+ const pcm = Buffer.isBuffer(pcmBuf) ? pcmBuf : Buffer.from(pcmBuf);
377
+ if (!opened) {
378
+ pendingAudio.push(pcm);
379
+ return;
380
+ }
381
+ if (socket && socket.readyState === WebSocket.OPEN) socket.send(pcm);
382
+ },
383
+ finish() {
384
+ if (settled || finishRequested) return;
385
+ finishRequested = true;
386
+ if (!opened) return;
387
+ stopTask();
388
+ clearTimeout(idleTimer);
389
+ finishTimer = setTimeout(() => succeed(), FINISH_TIMEOUT_MS);
390
+ },
391
+ cancel() {
392
+ if (settled) return;
393
+ settled = true;
394
+ clearTimers();
395
+ detachAbort();
396
+ if (tokenRequest && typeof tokenRequest.catch === 'function') tokenRequest.catch(() => {});
397
+ closeSocket();
398
+ },
399
+ };
400
+ },
401
+ };