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,389 @@
1
+ // OpenAI 适配器:整段走 /v1/audio/transcriptions(multipart),流式走 Realtime 转录会话
2
+ // (gpt-live-transcribe;官方建议先在服务端换 ephemeral token,也允许直接用 API key 连)。
3
+ 'use strict';
4
+
5
+ const {
6
+ CODES,
7
+ VoiceError,
8
+ httpJson,
9
+ openWs,
10
+ baseLang,
11
+ cleanHotwords,
12
+ cleanContext,
13
+ safeLog,
14
+ scrub,
15
+ closeWs,
16
+ } = require('./_common');
17
+
18
+ const DEFAULT_BASE_URL = 'https://api.openai.com';
19
+ const DEFAULT_WS_URL = 'wss://api.openai.com';
20
+ const DEFAULT_BATCH_MODEL = 'gpt-transcribe';
21
+ const DEFAULT_STREAM_MODEL = 'gpt-live-transcribe';
22
+ const REALTIME_RATE = 24000; // Realtime 转录会话约定 24 kHz PCM16;网关送的是 16 kHz,适配器内部线性升采样。
23
+ const GATEWAY_RATE = 16000;
24
+
25
+ const LANGUAGES = [
26
+ 'en', 'zh', 'ja', 'ko', 'es', 'fr', 'de', 'it', 'pt', 'nl', 'ru',
27
+ 'ar', 'hi', 'pl', 'tr', 'uk', 'vi', 'th', 'id', 'sv', 'da', 'no',
28
+ 'fi', 'auto',
29
+ ];
30
+
31
+ const CONFIG_FIELDS = [
32
+ { key: 'apiKey', label: 'API Key', secret: true, required: true },
33
+ {
34
+ key: 'model',
35
+ type: 'select',
36
+ label: '整段模型',
37
+ secret: false,
38
+ required: false,
39
+ default: DEFAULT_BATCH_MODEL,
40
+ options: ['gpt-transcribe', 'gpt-4o-transcribe', 'gpt-4o-mini-transcribe', 'whisper-1'],
41
+ },
42
+ {
43
+ key: 'streamingModel',
44
+ type: 'select',
45
+ label: '流式模型',
46
+ secret: false,
47
+ required: false,
48
+ default: DEFAULT_STREAM_MODEL,
49
+ options: ['gpt-live-transcribe', 'gpt-4o-transcribe'],
50
+ },
51
+ { key: 'ephemeral', type: 'boolean', label: '流式用 ephemeral token(官方建议开)', secret: false, required: false, default: true },
52
+ { key: 'baseUrl', label: 'API 地址(可选)', secret: false, required: false, placeholder: DEFAULT_BASE_URL },
53
+ { key: 'wsUrl', label: '流式地址(可选)', secret: false, required: false, placeholder: DEFAULT_WS_URL },
54
+ ];
55
+
56
+ function trimSlash(value) {
57
+ return String(value || '').replace(/\/+$/, '');
58
+ }
59
+
60
+ function keyOf(config) {
61
+ return String((config && config.apiKey) || '').trim();
62
+ }
63
+
64
+ function baseUrlOf(config) {
65
+ return trimSlash((config && config.baseUrl) || DEFAULT_BASE_URL);
66
+ }
67
+
68
+ function wsUrlOf(config) {
69
+ return trimSlash((config && config.wsUrl) || DEFAULT_WS_URL);
70
+ }
71
+
72
+ function batchModelOf(config) {
73
+ return String((config && config.model) || DEFAULT_BATCH_MODEL).trim();
74
+ }
75
+
76
+ function streamModelOf(config) {
77
+ return String((config && config.streamingModel) || DEFAULT_STREAM_MODEL).trim();
78
+ }
79
+
80
+ function useEphemeral(config) {
81
+ return !(config && String(config.ephemeral).toLowerCase() === 'false');
82
+ }
83
+
84
+ function timeoutOf(config, fallback) {
85
+ const value = Number(config && config.timeoutMs);
86
+ return Number.isFinite(value) && value > 0 ? value : fallback;
87
+ }
88
+
89
+ function ready(config) {
90
+ return Boolean(keyOf(config));
91
+ }
92
+
93
+ /** 整段:multipart 上传 WAV,模型直接返回 {text}。 */
94
+ async function transcribe({ config, audio, hints, signal, log } = {}) {
95
+ const cfg = config || {};
96
+ const key = keyOf(cfg);
97
+ if (!key) throw new VoiceError(CODES.UNAVAILABLE, 'OpenAI 未配置 API Key');
98
+ if (!audio || !audio.length) throw new VoiceError(CODES.INVALID_AUDIO, 'OpenAI 收到空音频');
99
+
100
+ const model = batchModelOf(cfg);
101
+ const lang = baseLang(hints && hints.lang);
102
+ const hotwords = cleanHotwords(hints && hints.hotwords);
103
+ const context = cleanContext(hints && hints.context, 200);
104
+ const prompt = [...hotwords, context].filter(Boolean).join(',').slice(0, 400);
105
+
106
+ const form = new FormData();
107
+ form.append('file', new Blob([audio], { type: 'audio/wav' }), 'audio.wav');
108
+ form.append('model', model);
109
+ form.append('response_format', 'json');
110
+ if (lang !== 'auto') form.append('language', lang);
111
+ if (prompt) form.append('prompt', prompt);
112
+
113
+ safeLog(log, `OpenAI 整段识别:model=${model} lang=${lang} hotwords=${hotwords.length}`);
114
+ const res = await httpJson(`${baseUrlOf(cfg)}/v1/audio/transcriptions`, {
115
+ headers: { authorization: `Bearer ${key}` },
116
+ body: form,
117
+ timeoutMs: timeoutOf(cfg, 60000),
118
+ label: 'OpenAI 识别',
119
+ secrets: [key],
120
+ signal,
121
+ });
122
+ const text = String((res.json && res.json.text) || '').trim();
123
+ if (!text) throw new VoiceError(CODES.INVALID_AUDIO, 'OpenAI 没有识别到语音内容');
124
+ return { text };
125
+ }
126
+
127
+ /**
128
+ * Realtime 转录会话:换 ephemeral token → 连 WS → session.update → append 音频 → commit → 收 completed。
129
+ * 返回的 push 接收 16 kHz PCM16,内部升到 24 kHz 再发。
130
+ */
131
+ function stream({ config, hints, signal, onPartial, onFinal, onError } = {}) {
132
+ const cfg = config || {};
133
+ const key = keyOf(cfg);
134
+ const model = streamModelOf(cfg);
135
+ const lang = baseLang(hints && hints.lang);
136
+ const hotwords = cleanHotwords(hints && hints.hotwords);
137
+ const context = cleanContext(hints && hints.context, 200);
138
+ const partials = new Map();
139
+
140
+ let ws = null;
141
+ let finished = false;
142
+ let cancelled = false;
143
+ let failed = false;
144
+ let completedCount = 0;
145
+
146
+ function emitPartial(text) {
147
+ if (cancelled || failed) return;
148
+ const value = String(text || '').trim();
149
+ if (!value) return;
150
+ if (typeof onPartial === 'function') {
151
+ try {
152
+ onPartial(value);
153
+ } catch {
154
+ // 回调抛错不影响连接
155
+ }
156
+ }
157
+ }
158
+
159
+ function emitFinal(text) {
160
+ if (cancelled || failed) return;
161
+ const value = String(text || '').trim();
162
+ if (!value) return;
163
+ if (typeof onFinal === 'function') {
164
+ try {
165
+ onFinal(value);
166
+ } catch {
167
+ // 同上
168
+ }
169
+ }
170
+ }
171
+
172
+ function emitError(err) {
173
+ if (cancelled || failed) return;
174
+ failed = true;
175
+ if (typeof onError === 'function') {
176
+ try {
177
+ onError(err);
178
+ } catch {
179
+ // 同上
180
+ }
181
+ }
182
+ }
183
+
184
+ function sessionPayload() {
185
+ const transcription = { model };
186
+ if (lang !== 'auto') transcription.language = lang;
187
+ if (hotwords.length) transcription.prompt = [...hotwords, context].filter(Boolean).join(',').slice(0, 400);
188
+ return {
189
+ type: 'session.update',
190
+ session: {
191
+ type: 'transcription',
192
+ audio: {
193
+ input: {
194
+ format: { type: 'audio/pcm', rate: REALTIME_RATE },
195
+ transcription,
196
+ // 转录会话不走服务端 VAD:由网关/端侧决定什么时候停,适配器收到 finish 再 commit。
197
+ turn_detection: null,
198
+ },
199
+ },
200
+ },
201
+ };
202
+ }
203
+
204
+ async function mintEphemeralToken() {
205
+ const res = await httpJson(`${baseUrlOf(cfg)}/v1/realtime/client_secrets`, {
206
+ headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
207
+ body: JSON.stringify({ session: sessionPayload().session }),
208
+ timeoutMs: timeoutOf(cfg, 15000),
209
+ label: 'OpenAI 换取临时令牌',
210
+ secrets: [key],
211
+ signal,
212
+ });
213
+ const body = res.json || {};
214
+ const token = body.value || (body.client_secret && body.client_secret.value);
215
+ if (!token) throw new VoiceError(CODES.UNAVAILABLE, 'OpenAI 没有返回临时令牌');
216
+ return token;
217
+ }
218
+
219
+ function handleMessage(message) {
220
+ const type = message.type;
221
+ if (type === 'conversation.item.input_audio_transcription.delta') {
222
+ const itemId = message.item_id || 'default';
223
+ const next = `${partials.get(itemId) || ''}${message.delta || ''}`;
224
+ partials.set(itemId, next);
225
+ emitPartial(next);
226
+ return;
227
+ }
228
+ if (type === 'conversation.item.input_audio_transcription.completed') {
229
+ const itemId = message.item_id || 'default';
230
+ partials.delete(itemId);
231
+ completedCount += 1;
232
+ emitFinal(message.transcript || '');
233
+ return;
234
+ }
235
+ if (type === 'conversation.item.input_audio_transcription.failed') {
236
+ const error = message.error || {};
237
+ const mapped = /auth|permission|token/i.test(String(error.code || error.type || '')) ? CODES.UNAVAILABLE : CODES.FAILED;
238
+ emitError(new VoiceError(mapped, `OpenAI 转录失败:${scrub(error.message || '未知错误', [key])}`));
239
+ return;
240
+ }
241
+ if (type === 'error') {
242
+ const error = message.error || {};
243
+ const mapped = /auth|permission|token|invalid_api_key/i.test(String(error.code || error.type || '')) ? CODES.UNAVAILABLE : CODES.FAILED;
244
+ emitError(new VoiceError(mapped, `OpenAI Realtime 错误:${scrub(error.message || '未知错误', [key])}`));
245
+ return;
246
+ }
247
+ // session.created / session.updated / input_audio_buffer.committed 不需要处理
248
+ }
249
+
250
+ const readyPromise = (async () => {
251
+ if (!key) throw new VoiceError(CODES.UNAVAILABLE, 'OpenAI 未配置 API Key');
252
+ if (signal && signal.aborted) throw new VoiceError(CODES.CANCELLED, 'OpenAI 流式已取消', { cancelled: true });
253
+ const token = useEphemeral(cfg) ? await mintEphemeralToken() : key;
254
+ ws = await openWs(`${wsUrlOf(cfg)}/v1/realtime?intent=transcription`, {
255
+ headers: { authorization: `Bearer ${token}` },
256
+ signal,
257
+ timeoutMs: timeoutOf(cfg, 15000),
258
+ label: 'OpenAI 流式连接',
259
+ secrets: [key, token],
260
+ });
261
+ if (signal) {
262
+ // 契约要求 signal 能停掉已连上的会话;网关取消时还会再调一次 cancel()。
263
+ const onAbort = () => {
264
+ cancelled = true;
265
+ finished = true;
266
+ try {
267
+ ws.terminate();
268
+ } catch {
269
+ // 已经断了
270
+ }
271
+ };
272
+ signal.addEventListener('abort', onAbort, { once: true });
273
+ ws.once('close', () => signal.removeEventListener('abort', onAbort));
274
+ }
275
+ ws.on('message', (data, isBinary) => {
276
+ if (isBinary) return;
277
+ let message = null;
278
+ try {
279
+ message = JSON.parse(data.toString('utf8'));
280
+ } catch {
281
+ return;
282
+ }
283
+ handleMessage(message);
284
+ });
285
+ ws.on('error', (err) => {
286
+ emitError(new VoiceError(CODES.FAILED, `OpenAI 流式连接中断:${scrub(err && err.message, [key])}`));
287
+ });
288
+ ws.on('close', (code, reason) => {
289
+ if (cancelled || failed || finished) return;
290
+ const detail = scrub(reason ? reason.toString('utf8') : '', [key]);
291
+ emitError(new VoiceError(CODES.UNAVAILABLE, `OpenAI 流式连接被关闭(${code}${detail ? `:${detail}` : ''})`));
292
+ });
293
+ ws.send(JSON.stringify(sessionPayload()));
294
+ return true;
295
+ })();
296
+
297
+ readyPromise.catch((err) => {
298
+ if (cancelled) return;
299
+ emitError(err instanceof VoiceError ? err : new VoiceError(CODES.FAILED, scrub(err && err.message, [key])));
300
+ });
301
+
302
+ return {
303
+ ready: readyPromise,
304
+ push(pcm) {
305
+ if (cancelled || failed || finished) return;
306
+ if (!pcm || !pcm.length) return;
307
+ if (!ws || ws.readyState !== 1) return;
308
+ const chunk = Buffer.isBuffer(pcm) ? pcm : Buffer.from(pcm);
309
+ const frame = upsamplePcm16(chunk, GATEWAY_RATE, REALTIME_RATE);
310
+ ws.send(JSON.stringify({ type: 'input_audio_buffer.append', audio: frame.toString('base64') }));
311
+ },
312
+ async finish() {
313
+ if (finished) return;
314
+ finished = true;
315
+ try {
316
+ await readyPromise;
317
+ } catch {
318
+ return;
319
+ }
320
+ if (!ws) return;
321
+ const before = completedCount;
322
+ try {
323
+ ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));
324
+ } catch {
325
+ return;
326
+ }
327
+ // 等最后一条完成事件;服务端不保证立刻回来,超时就收尾。
328
+ const timeoutMs = timeoutOf(cfg, 8000);
329
+ const startedAt = Date.now();
330
+ while (Date.now() - startedAt < timeoutMs) {
331
+ if (completedCount > before) break;
332
+ await new Promise((resolve) => setTimeout(resolve, 50));
333
+ }
334
+ await closeWs(ws);
335
+ },
336
+ async cancel() {
337
+ if (cancelled) return;
338
+ cancelled = true;
339
+ finished = true;
340
+ if (ws) {
341
+ try {
342
+ ws.terminate();
343
+ } catch {
344
+ // 已经断了
345
+ }
346
+ }
347
+ },
348
+ get socket() {
349
+ return ws;
350
+ },
351
+ };
352
+ }
353
+
354
+ /** 16 kHz → 24 kHz 线性插值;Realtime 转录会话只收 24 kHz PCM16。 */
355
+ function upsamplePcm16(input, fromRate, toRate) {
356
+ if (fromRate === toRate) return input;
357
+ const inSamples = Math.floor(input.length / 2);
358
+ if (inSamples === 0) return Buffer.alloc(0);
359
+ const outSamples = Math.max(1, Math.round((inSamples * toRate) / fromRate));
360
+ const out = Buffer.alloc(outSamples * 2);
361
+ const ratio = fromRate / toRate;
362
+ for (let i = 0; i < outSamples; i += 1) {
363
+ const pos = i * ratio;
364
+ const i0 = Math.min(inSamples - 1, Math.floor(pos));
365
+ const i1 = Math.min(inSamples - 1, i0 + 1);
366
+ const frac = pos - Math.floor(pos);
367
+ const s0 = input.readInt16LE(i0 * 2);
368
+ const s1 = input.readInt16LE(i1 * 2);
369
+ const value = Math.max(-32768, Math.min(32767, Math.round(s0 + (s1 - s0) * frac)));
370
+ out.writeInt16LE(value, i * 2);
371
+ }
372
+ return out;
373
+ }
374
+
375
+ module.exports = {
376
+ id: 'openai',
377
+ name: 'OpenAI',
378
+ kind: 'intl',
379
+ batch: true,
380
+ streaming: true,
381
+ languages: LANGUAGES,
382
+ hotwords: true,
383
+ maxSeconds: 600,
384
+ maxBytes: 25 * 1024 * 1024,
385
+ configFields: CONFIG_FIELDS,
386
+ ready,
387
+ transcribe,
388
+ stream,
389
+ };