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.
Files changed (37) 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/lib/zeronews/runner.cjs +7 -4
  36. package/lib/zeronews/wiring.cjs +36 -43
  37. package/package.json +14 -15
@@ -0,0 +1,353 @@
1
+ // AssemblyAI 适配器:整段走 REST(upload → transcript → 轮询),流式走 Universal-Streaming(/v3/ws)。
2
+ // 鉴权:Authorization 头直接放 API key(没有 Bearer 前缀)。流式结果是 Turn 事件,end_of_turn 才是终稿。
3
+ 'use strict';
4
+
5
+ const {
6
+ CODES,
7
+ VoiceError,
8
+ httpJson,
9
+ openWs,
10
+ baseLang,
11
+ cleanHotwords,
12
+ safeLog,
13
+ scrub,
14
+ backoff,
15
+ closeWs,
16
+ waitForClose,
17
+ } = require('./_common');
18
+
19
+ const DEFAULT_BASE_URL = 'https://api.assemblyai.com';
20
+ const DEFAULT_STREAM_URL = 'wss://streaming.assemblyai.com/v3/ws';
21
+ const DEFAULT_MODEL = 'universal-streaming-english';
22
+ const SAMPLE_RATE = 16000;
23
+
24
+ const LANGUAGES = [
25
+ 'en', 'es', 'fr', 'de', 'it', 'pt', 'nl', 'hi', 'ja', 'zh', 'ko',
26
+ 'ru', 'pl', 'tr', 'uk', 'vi', 'id', 'th', 'ar', 'he', 'fa', 'ur',
27
+ 'auto',
28
+ ];
29
+
30
+ const CONFIG_FIELDS = [
31
+ { key: 'apiKey', label: 'API Key', secret: true, required: true },
32
+ {
33
+ key: 'model',
34
+ type: 'select',
35
+ label: '流式模型',
36
+ secret: false,
37
+ required: false,
38
+ default: DEFAULT_MODEL,
39
+ options: ['universal-streaming-english', 'universal-streaming-multilingual', 'assemblyai-stt-3-7-realtime-agent'],
40
+ },
41
+ { key: 'baseUrl', label: 'API 地址(可选)', secret: false, required: false, placeholder: DEFAULT_BASE_URL },
42
+ { key: 'streamUrl', label: '流式地址(可选)', secret: false, required: false, placeholder: DEFAULT_STREAM_URL },
43
+ ];
44
+
45
+ function trimSlash(value) {
46
+ return String(value || '').replace(/\/+$/, '');
47
+ }
48
+
49
+ function keyOf(config) {
50
+ return String((config && config.apiKey) || '').trim();
51
+ }
52
+
53
+ function modelOf(config) {
54
+ return String((config && config.model) || DEFAULT_MODEL).trim();
55
+ }
56
+
57
+ function baseUrlOf(config) {
58
+ return trimSlash((config && config.baseUrl) || DEFAULT_BASE_URL);
59
+ }
60
+
61
+ function streamUrlOf(config) {
62
+ return trimSlash((config && config.streamUrl) || DEFAULT_STREAM_URL);
63
+ }
64
+
65
+ function timeoutOf(config, fallback) {
66
+ const value = Number(config && config.timeoutMs);
67
+ return Number.isFinite(value) && value > 0 ? value : fallback;
68
+ }
69
+
70
+ function ready(config) {
71
+ return Boolean(keyOf(config));
72
+ }
73
+
74
+ /** 上传 + 建任务 + 轮询;AssemblyAI 的整段是异步任务接口。 */
75
+ async function transcribe({ config, audio, hints, signal, log } = {}) {
76
+ const cfg = config || {};
77
+ const key = keyOf(cfg);
78
+ if (!key) throw new VoiceError(CODES.UNAVAILABLE, 'AssemblyAI 未配置 API Key');
79
+ if (!audio || !audio.length) throw new VoiceError(CODES.INVALID_AUDIO, 'AssemblyAI 收到空音频');
80
+
81
+ const lang = baseLang(hints && hints.lang);
82
+ const hotwords = cleanHotwords(hints && hints.hotwords);
83
+ const timeoutMs = timeoutOf(cfg, 90000);
84
+
85
+ safeLog(log, `AssemblyAI 整段识别:lang=${lang} hotwords=${hotwords.length} bytes=${audio.length}`);
86
+ const upload = await httpJson(`${baseUrlOf(cfg)}/v2/upload`, {
87
+ headers: { authorization: key, 'content-type': 'application/octet-stream' },
88
+ body: audio,
89
+ timeoutMs: Math.min(timeoutMs, 60000),
90
+ label: 'AssemblyAI 音频上传',
91
+ secrets: [key],
92
+ signal,
93
+ });
94
+ const uploadUrl = upload.json && upload.json.upload_url;
95
+ if (!uploadUrl) throw new VoiceError(CODES.FAILED, 'AssemblyAI 上传没有返回音频地址');
96
+
97
+ const payload = {
98
+ audio_url: uploadUrl,
99
+ punctuate: true,
100
+ format_text: true,
101
+ };
102
+ if (lang === 'auto') payload.language_detection = true;
103
+ else payload.language_code = lang;
104
+ if (hotwords.length) payload.keyterms_prompt = hotwords;
105
+
106
+ const created = await httpJson(`${baseUrlOf(cfg)}/v2/transcript`, {
107
+ headers: { authorization: key, 'content-type': 'application/json' },
108
+ body: JSON.stringify(payload),
109
+ timeoutMs: 30000,
110
+ label: 'AssemblyAI 建立识别任务',
111
+ secrets: [key],
112
+ signal,
113
+ });
114
+ const transcriptId = created.json && created.json.id;
115
+ if (!transcriptId) throw new VoiceError(CODES.FAILED, 'AssemblyAI 没有返回任务 id');
116
+
117
+ const deadline = Date.now() + timeoutMs;
118
+ const pollMs = Math.max(200, Math.min(5000, Number(cfg.pollMs) || 500));
119
+ for (;;) {
120
+ const res = await httpJson(`${baseUrlOf(cfg)}/v2/transcript/${encodeURIComponent(transcriptId)}`, {
121
+ method: 'GET',
122
+ headers: { authorization: key },
123
+ timeoutMs: 30000,
124
+ label: 'AssemblyAI 查询识别结果',
125
+ secrets: [key],
126
+ signal,
127
+ });
128
+ const body = res.json || {};
129
+ if (body.status === 'completed') {
130
+ const text = String(body.text || '').trim();
131
+ if (!text) throw new VoiceError(CODES.INVALID_AUDIO, 'AssemblyAI 没有识别到语音内容');
132
+ const durationMs = Number.isFinite(Number(body.audio_duration)) ? Math.round(Number(body.audio_duration) * 1000) : undefined;
133
+ return { text, lang: body.language_code ? baseLang(body.language_code) : undefined, durationMs };
134
+ }
135
+ if (body.status === 'error') {
136
+ throw new VoiceError(CODES.FAILED, `AssemblyAI 识别失败:${scrub(body.error || '未知错误', [key])}`);
137
+ }
138
+ if (Date.now() > deadline) throw new VoiceError(CODES.TIMEOUT, 'AssemblyAI 识别超时');
139
+ await backoff(pollMs, signal);
140
+ }
141
+ }
142
+
143
+ /** 流式:Universal-Streaming V3;Begin/Turn/SpeechStarted/Termination。 */
144
+ function stream({ config, hints, signal, onPartial, onFinal, onError } = {}) {
145
+ const cfg = config || {};
146
+ const key = keyOf(cfg);
147
+ const model = modelOf(cfg);
148
+ const lang = baseLang(hints && hints.lang);
149
+ const hotwords = cleanHotwords(hints && hints.hotwords, { max: 30 });
150
+
151
+ let ws = null;
152
+ let finished = false;
153
+ let cancelled = false;
154
+ let failed = false;
155
+ let terminated = false;
156
+ const pending = [];
157
+ let pendingBytes = 0;
158
+ const PENDING_LIMIT = 4 * 1024 * 1024;
159
+
160
+ function emitPartial(text) {
161
+ if (cancelled || failed) return;
162
+ const value = String(text || '').trim();
163
+ if (!value) return;
164
+ if (typeof onPartial === 'function') {
165
+ try {
166
+ onPartial(value);
167
+ } catch {
168
+ // 回调抛错不影响连接
169
+ }
170
+ }
171
+ }
172
+
173
+ function emitFinal(text) {
174
+ if (cancelled || failed) return;
175
+ const value = String(text || '').trim();
176
+ if (!value) return;
177
+ if (typeof onFinal === 'function') {
178
+ try {
179
+ onFinal(value);
180
+ } catch {
181
+ // 同上
182
+ }
183
+ }
184
+ }
185
+
186
+ function emitError(err) {
187
+ if (cancelled || failed) return;
188
+ failed = true;
189
+ if (typeof onError === 'function') {
190
+ try {
191
+ onError(err);
192
+ } catch {
193
+ // 同上
194
+ }
195
+ }
196
+ }
197
+
198
+ function buildStreamUrl() {
199
+ const params = new URLSearchParams();
200
+ params.set('sample_rate', String(SAMPLE_RATE));
201
+ params.set('encoding', 'pcm_s16le');
202
+ params.set('speech_model', model);
203
+ params.set('format_turns', 'true');
204
+ if (lang !== 'auto') params.set('language_code', lang);
205
+ // 热词通过 keyterms_prompt 连接参数传;多语言流式模型才吃英文以外的词。
206
+ if (hotwords.length) params.set('keyterms_prompt', hotwords.join(','));
207
+ return `${streamUrlOf(cfg)}?${params.toString()}`;
208
+ }
209
+
210
+ function handleMessage(message) {
211
+ const type = message.type;
212
+ if (type === 'Turn') {
213
+ const text = message.transcript || '';
214
+ if (message.end_of_turn) emitFinal(text);
215
+ else emitPartial(text);
216
+ return;
217
+ }
218
+ if (type === 'Error') {
219
+ const code = Number(message.error_code) || 0;
220
+ const mapped = code >= 4000 ? CODES.UNAVAILABLE : CODES.FAILED;
221
+ emitError(new VoiceError(mapped, `AssemblyAI 流式错误(${code}):${scrub(message.error || '未知错误', [key])}`));
222
+ return;
223
+ }
224
+ if (type === 'Termination') {
225
+ terminated = true;
226
+ return;
227
+ }
228
+ // Begin / SpeechStarted / Heartbeat 不需要处理
229
+ }
230
+
231
+ const readyPromise = (async () => {
232
+ if (!key) throw new VoiceError(CODES.UNAVAILABLE, 'AssemblyAI 未配置 API Key');
233
+ if (signal && signal.aborted) throw new VoiceError(CODES.CANCELLED, 'AssemblyAI 流式已取消', { cancelled: true });
234
+ ws = await openWs(buildStreamUrl(), {
235
+ headers: { authorization: key },
236
+ signal,
237
+ timeoutMs: timeoutOf(cfg, 15000),
238
+ label: 'AssemblyAI 流式连接',
239
+ secrets: [key],
240
+ });
241
+ if (signal) {
242
+ // 契约要求 signal 能停掉已连上的会话;网关取消时还会再调一次 cancel()。
243
+ const onAbort = () => {
244
+ cancelled = true;
245
+ finished = true;
246
+ try {
247
+ ws.terminate();
248
+ } catch {
249
+ // 已经断了
250
+ }
251
+ };
252
+ signal.addEventListener('abort', onAbort, { once: true });
253
+ ws.once('close', () => signal.removeEventListener('abort', onAbort));
254
+ }
255
+ ws.on('message', (data, isBinary) => {
256
+ if (isBinary) return;
257
+ let message = null;
258
+ try {
259
+ message = JSON.parse(data.toString('utf8'));
260
+ } catch {
261
+ return;
262
+ }
263
+ handleMessage(message);
264
+ });
265
+ ws.on('error', (err) => {
266
+ emitError(new VoiceError(CODES.FAILED, `AssemblyAI 流式连接中断:${scrub(err && err.message, [key])}`));
267
+ });
268
+ ws.on('close', (code, reason) => {
269
+ if (canceledOrDone()) return;
270
+ if (terminated) return;
271
+ const detail = scrub(reason ? reason.toString('utf8') : '', [key]);
272
+ emitError(new VoiceError(CODES.UNAVAILABLE, `AssemblyAI 流式连接被关闭(${code}${detail ? `:${detail}` : ''})`));
273
+ });
274
+ for (const chunk of pending.splice(0)) ws.send(chunk);
275
+ pendingBytes = 0;
276
+ return true;
277
+ })();
278
+
279
+ function canceledOrDone() {
280
+ return cancelled || failed || finished;
281
+ }
282
+
283
+ readyPromise.catch((err) => {
284
+ if (cancelled) return;
285
+ emitError(err instanceof VoiceError ? err : new VoiceError(CODES.FAILED, scrub(err && err.message, [key])));
286
+ });
287
+
288
+ return {
289
+ ready: readyPromise,
290
+ push(pcm) {
291
+ if (cancelled || failed || finished) return;
292
+ if (!pcm || !pcm.length) return;
293
+ const chunk = Buffer.isBuffer(pcm) ? pcm : Buffer.from(pcm);
294
+ if (ws && ws.readyState === 1) {
295
+ ws.send(chunk);
296
+ return;
297
+ }
298
+ if (pendingBytes + chunk.length > PENDING_LIMIT) return;
299
+ pending.push(chunk);
300
+ pendingBytes += chunk.length;
301
+ },
302
+ async finish() {
303
+ if (finished) return;
304
+ finished = true;
305
+ try {
306
+ await readyPromise;
307
+ } catch {
308
+ return;
309
+ }
310
+ if (!ws) return;
311
+ try {
312
+ ws.send(JSON.stringify({ type: 'Terminate' }));
313
+ } catch {
314
+ return;
315
+ }
316
+ // Terminate 之后还要继续读,直到 Termination,否则最后一段终稿会丢。
317
+ await waitForClose(ws, timeoutOf(cfg, 8000), signal);
318
+ await closeWs(ws);
319
+ },
320
+ async cancel() {
321
+ if (cancelled) return;
322
+ cancelled = true;
323
+ finished = true;
324
+ pending.length = 0;
325
+ if (ws) {
326
+ try {
327
+ ws.terminate();
328
+ } catch {
329
+ // 已经断了
330
+ }
331
+ }
332
+ },
333
+ get socket() {
334
+ return ws;
335
+ },
336
+ };
337
+ }
338
+
339
+ module.exports = {
340
+ id: 'assemblyai',
341
+ name: 'AssemblyAI',
342
+ kind: 'intl',
343
+ batch: true,
344
+ streaming: true,
345
+ languages: LANGUAGES,
346
+ hotwords: true,
347
+ maxSeconds: 600,
348
+ maxBytes: 25 * 1024 * 1024,
349
+ configFields: CONFIG_FIELDS,
350
+ ready,
351
+ transcribe,
352
+ stream,
353
+ };