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,328 @@
1
+ // 火山引擎豆包大模型流式 ASR 适配器:双向 WebSocket + 二进制帧,热词走 corpus.context 直传。
2
+ // 只做流式(batch:false);整段入口由网关用支持批量识别的 provider,不在这里硬凑。
3
+ 'use strict';
4
+
5
+ const crypto = require('node:crypto');
6
+ const WebSocket = require('ws');
7
+
8
+ const DEFAULT_ENDPOINT = 'wss://openspeech.bytedance.com/api/v3/sauc/bigmodel';
9
+ const DEFAULT_RESOURCE_ID = 'volc.bigasr.sauc.duration';
10
+ const CONNECT_TIMEOUT_MS = 10_000;
11
+ const IDLE_TIMEOUT_MS = 15_000;
12
+ const FINISH_TIMEOUT_MS = 10_000;
13
+
14
+ // 帧头:协议版本 1、头长 1 字(4 字节)、消息类型、flags、序列化 JSON / 音频原样。
15
+ const MSG_FULL_CLIENT = 0x1;
16
+ const MSG_AUDIO_ONLY = 0x2;
17
+ const MSG_FULL_SERVER = 0x9;
18
+ const MSG_ERROR = 0xf;
19
+ const FLAG_LAST = 0x2;
20
+
21
+ const LANG_MAP = { zh: 'zh-CN', en: 'en-US', ja: 'ja-JP', ko: 'ko-KR', yue: 'yue-CN' };
22
+
23
+ const configFields = [
24
+ { key: 'apiKey', label: 'API Key', secret: true, required: true },
25
+ { key: 'resourceId', label: '资源 ID', secret: false, required: false, placeholder: DEFAULT_RESOURCE_ID },
26
+ { key: 'endpoint', label: '服务地址(可选)', secret: false, required: false, placeholder: DEFAULT_ENDPOINT },
27
+ ];
28
+
29
+ function voiceError(code, message, extra) {
30
+ const err = new Error(message);
31
+ err.code = code;
32
+ if (extra) Object.assign(err, extra);
33
+ return err;
34
+ }
35
+
36
+ function buildFrame(messageType, flags, serialization, payload) {
37
+ const header = Buffer.from([0x11, (messageType << 4) | flags, (serialization << 4) | 0x00, 0x00]);
38
+ const size = Buffer.alloc(4);
39
+ size.writeUInt32BE(payload.length, 0);
40
+ return Buffer.concat([header, size, payload]);
41
+ }
42
+
43
+ // 服务端错误帧:4 字节错误码 + 4 字节消息长度 + 消息正文。
44
+ function parseErrorFrame(buf, headerSize) {
45
+ if (buf.length < headerSize + 8) return { type: 'error', code: -1, message: '' };
46
+ const code = buf.readUInt32BE(headerSize);
47
+ const len = buf.readUInt32BE(headerSize + 4);
48
+ const start = headerSize + 8;
49
+ return { type: 'error', code, message: buf.subarray(start, start + len).toString('utf8') };
50
+ }
51
+
52
+ function parseServerFrame(buf) {
53
+ if (!Buffer.isBuffer(buf) || buf.length < 4) return null;
54
+ const headerSize = (buf[0] & 0x0f) * 4;
55
+ const messageType = (buf[1] >> 4) & 0x0f;
56
+ const flags = buf[1] & 0x0f;
57
+ if (buf.length < headerSize + 4) return null;
58
+ if (messageType === MSG_ERROR) return parseErrorFrame(buf, headerSize);
59
+ // 服务端的帧比客户端多一个 4 字节 sequence:`[header][sequence][size][payload]`。
60
+ // 少跳这 4 字节就会把 sequence 当成 payload 长度,读到半截 JSON 或整段解不出来 —— 表现是
61
+ // 会话连上、音频也发完了,但终稿永远是空字符串(真实账号联调时就是这么卡住的)。
62
+ if (buf.length < headerSize + 8) return null;
63
+ const sequence = buf.readUInt32BE(headerSize);
64
+ const size = buf.readUInt32BE(headerSize + 4);
65
+ const payload = buf.subarray(headerSize + 8, headerSize + 8 + size);
66
+ return { type: messageType === MSG_FULL_SERVER ? 'result' : 'unknown', flags, sequence, payload };
67
+ }
68
+
69
+ // 火山错误码:45000001 参数、45000002 静音/空音频、45000081 并发/限流、45000151 鉴权。
70
+ function mapErrorCode(code, message) {
71
+ const raw = String(message || '');
72
+ if (code === 45000081 || code === 45000101) return 'voice-rate-limited';
73
+ if (code === 45000002) return 'voice-invalid-audio';
74
+ if (code === 45000151 || code === 45000005) return 'voice-provider-unavailable';
75
+ if (code === 45000003) return 'voice-timeout';
76
+ if (/quota|余额|配额|限流|超过|并发/i.test(raw)) return 'voice-quota';
77
+ if (/timeout|超时/i.test(raw)) return 'voice-timeout';
78
+ return 'voice-failed';
79
+ }
80
+
81
+ function configReady(config) {
82
+ return Boolean(config && typeof config.apiKey === 'string' && config.apiKey.trim());
83
+ }
84
+
85
+ function pickLang(lang) {
86
+ const key = String(lang || '').toLowerCase();
87
+ return LANG_MAP[key] || '';
88
+ }
89
+
90
+ // 热词/上下文共用 corpus.context:火山要的是 JSON 字符串,内容取 context 优先、否则逗号拼热词。
91
+ function buildCorpus(hints) {
92
+ const h = hints && typeof hints === 'object' ? hints : {};
93
+ const hotwords = Array.isArray(h.hotwords) ? h.hotwords.filter((w) => typeof w === 'string' && w.trim()) : [];
94
+ const context = typeof h.context === 'string' ? h.context.trim() : '';
95
+ const body = [context, hotwords.join(',')].filter(Boolean).join(',').slice(0, 5000);
96
+ return body ? JSON.stringify({ context: body }) : '';
97
+ }
98
+
99
+ module.exports = {
100
+ id: 'volc',
101
+ name: '火山引擎豆包',
102
+ kind: 'cn',
103
+ batch: false,
104
+ streaming: true,
105
+ languages: ['zh', 'en', 'ja', 'ko', 'auto'],
106
+ hotwords: true,
107
+ maxSeconds: 300,
108
+ maxBytes: 8 * 1024 * 1024,
109
+ configFields,
110
+
111
+ ready(config) {
112
+ return configReady(config);
113
+ },
114
+
115
+ async transcribe({ config } = {}) {
116
+ if (!configReady(config)) throw voiceError('voice-provider-unavailable', '火山引擎未配置 API Key');
117
+ throw voiceError('voice-provider-unavailable', '火山引擎豆包只提供流式识别,请走流式入口');
118
+ },
119
+
120
+ stream({ config, hints, signal, onPartial, onFinal, onError } = {}) {
121
+ const cfg = config && typeof config === 'object' ? config : {};
122
+ const h = hints && typeof hints === 'object' ? hints : {};
123
+ const emitPartial = typeof onPartial === 'function' ? onPartial : () => {};
124
+ const emitFinal = typeof onFinal === 'function' ? onFinal : () => {};
125
+ const emitError = typeof onError === 'function' ? onError : () => {};
126
+
127
+ const noop = { push() {}, finish() {}, cancel() {} };
128
+
129
+ if (!configReady(cfg)) {
130
+ queueMicrotask(() => emitError(voiceError('voice-provider-unavailable', '火山引擎未配置 API Key')));
131
+ return noop;
132
+ }
133
+ if (signal && signal.aborted) {
134
+ queueMicrotask(() => emitError(voiceError('voice-failed', '已取消', { cancelled: true })));
135
+ return noop;
136
+ }
137
+
138
+ const apiKey = cfg.apiKey.trim();
139
+ const endpoint = String(cfg.endpoint || '').trim() || DEFAULT_ENDPOINT;
140
+ const resourceId = String(cfg.resourceId || '').trim() || DEFAULT_RESOURCE_ID;
141
+ const lang = pickLang(h.lang);
142
+ const corpus = buildCorpus(h);
143
+
144
+ const requestJson = {
145
+ user: { uid: 'dsh-mobile' },
146
+ audio: { format: 'pcm', codec: 'raw', rate: 16000, bits: 16, channel: 1 },
147
+ request: {
148
+ model_name: 'bigmodel',
149
+ enable_punc: true,
150
+ enable_itn: true,
151
+ show_utterances: true,
152
+ end_window_size: 800,
153
+ },
154
+ };
155
+ if (lang) requestJson.audio.language = lang;
156
+ if (corpus) requestJson.request.corpus = { context: corpus };
157
+
158
+ let socket = null;
159
+ let opened = false;
160
+ let settled = false;
161
+ let finishRequested = false;
162
+ let lastText = '';
163
+ let resultLang = '';
164
+ const pendingAudio = [];
165
+ let idleTimer = null;
166
+ let finishTimer = null;
167
+
168
+ const connectTimer = setTimeout(() => {
169
+ fail(voiceError('voice-timeout', '连接火山引擎超时'));
170
+ }, CONNECT_TIMEOUT_MS);
171
+
172
+ function clearTimers() {
173
+ clearTimeout(connectTimer);
174
+ clearTimeout(idleTimer);
175
+ clearTimeout(finishTimer);
176
+ idleTimer = null;
177
+ finishTimer = null;
178
+ }
179
+
180
+ function closeSocket() {
181
+ if (!socket) return;
182
+ try { socket.removeAllListeners(); } catch {}
183
+ try { socket.close(); } catch {}
184
+ try { socket.terminate(); } catch {}
185
+ socket = null;
186
+ }
187
+
188
+ function detachAbort() {
189
+ if (signal) signal.removeEventListener('abort', onAbort);
190
+ }
191
+
192
+ function fail(err) {
193
+ if (settled) return;
194
+ settled = true;
195
+ clearTimers();
196
+ detachAbort();
197
+ closeSocket();
198
+ emitError(err);
199
+ }
200
+
201
+ function succeed() {
202
+ if (settled) return;
203
+ settled = true;
204
+ clearTimers();
205
+ detachAbort();
206
+ closeSocket();
207
+ const langOut = resultLang || (typeof h.lang === 'string' && h.lang !== 'auto' ? h.lang : undefined);
208
+ emitFinal(lastText, langOut ? { lang: langOut } : undefined);
209
+ }
210
+
211
+ function armIdle() {
212
+ clearTimeout(idleTimer);
213
+ idleTimer = setTimeout(() => fail(voiceError('voice-timeout', '火山引擎长时间没有返回结果')), IDLE_TIMEOUT_MS);
214
+ }
215
+
216
+ function sendFrame(frame) {
217
+ if (!socket || socket.readyState !== WebSocket.OPEN) return;
218
+ socket.send(frame);
219
+ }
220
+
221
+ function onAbort() {
222
+ if (settled) return;
223
+ settled = true;
224
+ clearTimers();
225
+ closeSocket();
226
+ emitError(voiceError('voice-failed', '已取消', { cancelled: true }));
227
+ }
228
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
229
+
230
+ function handleServerFrame(buf) {
231
+ const frame = parseServerFrame(buf);
232
+ if (!frame) return;
233
+ if (frame.type === 'error') {
234
+ fail(voiceError(mapErrorCode(frame.code, frame.message), `火山引擎返回错误 ${frame.code}`));
235
+ return;
236
+ }
237
+ if (frame.type !== 'result') return;
238
+ let data = null;
239
+ try { data = JSON.parse(frame.payload.toString('utf8')); } catch { return; }
240
+ const result = data && data.result ? data.result : {};
241
+ if (typeof result.text === 'string') lastText = result.text;
242
+ if (typeof result.language === 'string' && result.language) resultLang = result.language;
243
+ const isFinal = (frame.flags & FLAG_LAST) === FLAG_LAST || data.sequence === -1 || data.is_final === true;
244
+ if (isFinal) {
245
+ succeed();
246
+ return;
247
+ }
248
+ if (lastText) {
249
+ try { emitPartial(lastText); } catch {}
250
+ }
251
+ armIdle();
252
+ }
253
+
254
+ try {
255
+ socket = new WebSocket(endpoint, {
256
+ handshakeTimeout: CONNECT_TIMEOUT_MS,
257
+ headers: {
258
+ 'X-Api-Key': apiKey,
259
+ 'X-Api-Resource-Id': resourceId,
260
+ 'X-Api-Request-Id': crypto.randomUUID(),
261
+ 'X-Api-Sequence': '-1',
262
+ },
263
+ });
264
+ } catch {
265
+ clearTimers();
266
+ detachAbort();
267
+ queueMicrotask(() => fail(voiceError('voice-provider-unavailable', '火山引擎地址不可用')));
268
+ return noop;
269
+ }
270
+
271
+ socket.on('open', () => {
272
+ opened = true;
273
+ clearTimeout(connectTimer);
274
+ const payload = Buffer.from(JSON.stringify(requestJson), 'utf8');
275
+ sendFrame(buildFrame(MSG_FULL_CLIENT, 0x0, 0x1, payload));
276
+ for (const pcm of pendingAudio) sendFrame(buildFrame(MSG_AUDIO_ONLY, 0x0, 0x0, pcm));
277
+ pendingAudio.length = 0;
278
+ if (finishRequested) {
279
+ sendFrame(buildFrame(MSG_AUDIO_ONLY, FLAG_LAST, 0x0, Buffer.alloc(0)));
280
+ }
281
+ armIdle();
282
+ });
283
+
284
+ socket.on('message', (data) => {
285
+ if (settled) return;
286
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
287
+ armIdle();
288
+ handleServerFrame(buf);
289
+ });
290
+
291
+ socket.on('error', () => {
292
+ fail(voiceError('voice-provider-unavailable', '火山引擎连接失败:检查 API Key 是否有效、资源 ID 是否与开通的产品一致(1.0 是 volc.bigasr.sauc.duration,2.0 是 volc.seedasr.sauc.duration)'));
293
+ });
294
+
295
+ socket.on('close', () => {
296
+ if (settled) return;
297
+ if (finishRequested) succeed();
298
+ else fail(voiceError('voice-provider-unavailable', '火山引擎连接被关闭:检查 API Key 与资源 ID 是否匹配开通的产品'));
299
+ });
300
+
301
+ return {
302
+ push(pcmBuf, _seq) {
303
+ if (settled || !pcmBuf || !pcmBuf.length) return;
304
+ const pcm = Buffer.isBuffer(pcmBuf) ? pcmBuf : Buffer.from(pcmBuf);
305
+ if (!opened) {
306
+ pendingAudio.push(pcm);
307
+ return;
308
+ }
309
+ sendFrame(buildFrame(MSG_AUDIO_ONLY, 0x0, 0x0, pcm));
310
+ },
311
+ finish() {
312
+ if (settled || finishRequested) return;
313
+ finishRequested = true;
314
+ if (!opened) return;
315
+ sendFrame(buildFrame(MSG_AUDIO_ONLY, FLAG_LAST, 0x0, Buffer.alloc(0)));
316
+ clearTimeout(idleTimer);
317
+ finishTimer = setTimeout(() => succeed(), FINISH_TIMEOUT_MS);
318
+ },
319
+ cancel() {
320
+ if (settled) return;
321
+ settled = true;
322
+ clearTimers();
323
+ detachAbort();
324
+ closeSocket();
325
+ },
326
+ };
327
+ },
328
+ };
@@ -0,0 +1,290 @@
1
+ // 讯飞实时语音转写(RTASR)适配器:WebSocket + appid/ts/signa 签名,音频 base64 帧上送。
2
+ // 签名在插件侧完成(Base64(HmacSHA1(MD5(appid+ts), apiKey))),手机和面板都拿不到 apiKey。
3
+ 'use strict';
4
+
5
+ const crypto = require('node:crypto');
6
+ const WebSocket = require('ws');
7
+
8
+ const DEFAULT_ENDPOINT = 'wss://rtasr.xfyun.cn/v1/ws';
9
+ const CONNECT_TIMEOUT_MS = 10_000;
10
+ const IDLE_TIMEOUT_MS = 15_000;
11
+ const FINISH_TIMEOUT_MS = 10_000;
12
+
13
+ const LANG_MAP = { zh: 'cn', en: 'en' };
14
+
15
+ const configFields = [
16
+ { key: 'appId', label: 'AppID', secret: false, required: true },
17
+ { key: 'apiKey', label: 'APIKey', secret: true, required: true },
18
+ { key: 'endpoint', label: '服务地址(可选)', secret: false, required: false, placeholder: DEFAULT_ENDPOINT },
19
+ ];
20
+
21
+ function voiceError(code, message, extra) {
22
+ const err = new Error(message);
23
+ err.code = code;
24
+ if (extra) Object.assign(err, extra);
25
+ return err;
26
+ }
27
+
28
+ function md5Hex(text) {
29
+ return crypto.createHash('md5').update(text, 'utf8').digest('hex');
30
+ }
31
+
32
+ // signa = Base64(HmacSHA1(key = apiKey, message = MD5(appid + ts) 的十六进制串))
33
+ function signaOf(appId, apiKey, ts) {
34
+ const digest = md5Hex(String(appId) + String(ts));
35
+ return crypto.createHmac('sha1', apiKey).update(digest, 'utf8').digest('base64');
36
+ }
37
+
38
+ function mapErrorCode(code, desc) {
39
+ const text = `${code} ${desc || ''}`;
40
+ if (/限流|并发|频繁|too many|rate/i.test(text)) return 'voice-rate-limited';
41
+ if (/配额|余额|额度|超量|quota/i.test(text)) return 'voice-quota';
42
+ if (/超时|timeout/i.test(text)) return 'voice-timeout';
43
+ if (/签名|鉴权|授权|未授权|appid|unauthorized|auth/i.test(text)) return 'voice-provider-unavailable';
44
+ if (/音频|格式|audio|invalid/i.test(text)) return 'voice-invalid-audio';
45
+ return 'voice-failed';
46
+ }
47
+
48
+ function configReady(config) {
49
+ return Boolean(
50
+ config
51
+ && typeof config.appId === 'string' && config.appId.trim()
52
+ && typeof config.apiKey === 'string' && config.apiKey.trim(),
53
+ );
54
+ }
55
+
56
+ function sentenceText(item) {
57
+ const words = item && Array.isArray(item.cw) ? item.cw : [];
58
+ return words.map((cw) => (cw && typeof cw.w === 'string' ? cw.w : '')).join('');
59
+ }
60
+
61
+ // 讯飞结果:data 是 JSON 字符串,st.type=0 为中间句、1 为整句确定,ws 里是逐字结果。
62
+ function readResultPayload(raw) {
63
+ let data = raw;
64
+ if (typeof raw === 'string') {
65
+ try { data = JSON.parse(raw); } catch { return null; }
66
+ }
67
+ if (!data || typeof data !== 'object') return null;
68
+ const sentences = Array.isArray(data.ws) ? data.ws.map(sentenceText).join('') : '';
69
+ const type = data.st && (data.st.type === '1' || data.st.type === 1) ? '1' : '0';
70
+ return { text: sentences, definite: type === '1' };
71
+ }
72
+
73
+ module.exports = {
74
+ id: 'xfyun',
75
+ name: '讯飞实时语音转写',
76
+ kind: 'cn',
77
+ batch: false,
78
+ streaming: true,
79
+ languages: ['zh', 'en'],
80
+ hotwords: true,
81
+ maxSeconds: 300,
82
+ maxBytes: 8 * 1024 * 1024,
83
+ configFields,
84
+
85
+ ready(config) {
86
+ return configReady(config);
87
+ },
88
+
89
+ async transcribe({ config } = {}) {
90
+ if (!configReady(config)) throw voiceError('voice-provider-unavailable', '讯飞未配置 AppID / APIKey');
91
+ throw voiceError('voice-provider-unavailable', '讯飞实时语音转写只提供流式识别,请走流式入口');
92
+ },
93
+
94
+ stream({ config, hints, signal, onPartial, onFinal, onError } = {}) {
95
+ const cfg = config && typeof config === 'object' ? config : {};
96
+ const h = hints && typeof hints === 'object' ? hints : {};
97
+ const emitPartial = typeof onPartial === 'function' ? onPartial : () => {};
98
+ const emitFinal = typeof onFinal === 'function' ? onFinal : () => {};
99
+ const emitError = typeof onError === 'function' ? onError : () => {};
100
+ const noop = { push() {}, finish() {}, cancel() {} };
101
+
102
+ if (!configReady(cfg)) {
103
+ queueMicrotask(() => emitError(voiceError('voice-provider-unavailable', '讯飞未配置 AppID / APIKey')));
104
+ return noop;
105
+ }
106
+ if (signal && signal.aborted) {
107
+ queueMicrotask(() => emitError(voiceError('voice-failed', '已取消', { cancelled: true })));
108
+ return noop;
109
+ }
110
+
111
+ const appId = cfg.appId.trim();
112
+ const apiKey = cfg.apiKey.trim();
113
+ const endpoint = String(cfg.endpoint || '').trim() || DEFAULT_ENDPOINT;
114
+ const langKey = String(h.lang || 'zh').toLowerCase();
115
+ const lang = LANG_MAP[langKey] || LANG_MAP.zh;
116
+
117
+ const ts = String(Date.now());
118
+ const params = new URLSearchParams({
119
+ appid: appId,
120
+ ts,
121
+ signa: signaOf(appId, apiKey, ts),
122
+ lang,
123
+ roleType: '0',
124
+ });
125
+ const hotwords = Array.isArray(h.hotwords)
126
+ ? h.hotwords.filter((w) => typeof w === 'string' && w.trim()).slice(0, 100)
127
+ : [];
128
+ if (hotwords.length) params.set('hotwd', hotwords.join(','));
129
+ const url = `${endpoint}${endpoint.includes('?') ? '&' : '?'}${params.toString()}`;
130
+
131
+ let socket = null;
132
+ let opened = false;
133
+ let settled = false;
134
+ let finishRequested = false;
135
+ let finalText = '';
136
+ let current = '';
137
+ const pendingAudio = [];
138
+ let idleTimer = null;
139
+ let finishTimer = null;
140
+
141
+ const connectTimer = setTimeout(() => fail(voiceError('voice-timeout', '连接讯飞超时')), CONNECT_TIMEOUT_MS);
142
+
143
+ function clearTimers() {
144
+ clearTimeout(connectTimer);
145
+ clearTimeout(idleTimer);
146
+ clearTimeout(finishTimer);
147
+ idleTimer = null;
148
+ finishTimer = null;
149
+ }
150
+
151
+ function closeSocket() {
152
+ if (!socket) return;
153
+ try { socket.removeAllListeners(); } catch {}
154
+ try { socket.close(); } catch {}
155
+ try { socket.terminate(); } catch {}
156
+ socket = null;
157
+ }
158
+
159
+ function detachAbort() {
160
+ if (signal) signal.removeEventListener('abort', onAbort);
161
+ }
162
+
163
+ function fail(err) {
164
+ if (settled) return;
165
+ settled = true;
166
+ clearTimers();
167
+ detachAbort();
168
+ closeSocket();
169
+ emitError(err);
170
+ }
171
+
172
+ function succeed() {
173
+ if (settled) return;
174
+ settled = true;
175
+ clearTimers();
176
+ detachAbort();
177
+ closeSocket();
178
+ const text = (finalText + current).trim();
179
+ const langOut = langKey === 'zh' ? 'zh' : langKey === 'en' ? 'en' : undefined;
180
+ emitFinal(text, langOut ? { lang: langOut } : undefined);
181
+ }
182
+
183
+ function armIdle() {
184
+ clearTimeout(idleTimer);
185
+ idleTimer = setTimeout(() => fail(voiceError('voice-timeout', '讯飞长时间没有返回结果')), IDLE_TIMEOUT_MS);
186
+ }
187
+
188
+ function sendJson(payload) {
189
+ if (!socket || socket.readyState !== WebSocket.OPEN) return;
190
+ socket.send(JSON.stringify(payload));
191
+ }
192
+
193
+ function sendAudio(pcm) {
194
+ sendJson({ data: pcm.toString('base64') });
195
+ }
196
+
197
+ function onAbort() {
198
+ if (settled) return;
199
+ settled = true;
200
+ clearTimers();
201
+ closeSocket();
202
+ emitError(voiceError('voice-failed', '已取消', { cancelled: true }));
203
+ }
204
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
205
+
206
+ function handleMessage(raw) {
207
+ let msg = null;
208
+ try { msg = JSON.parse(typeof raw === 'string' ? raw : raw.toString('utf8')); } catch { return; }
209
+ if (!msg || typeof msg !== 'object') return;
210
+ if (msg.action === 'error') {
211
+ const code = msg.code == null ? '' : String(msg.code);
212
+ fail(voiceError(mapErrorCode(code, msg.desc), `讯飞返回错误 ${code}`));
213
+ return;
214
+ }
215
+ if (msg.action !== 'result') return;
216
+ const parsed = readResultPayload(msg.data);
217
+ if (!parsed) return;
218
+ current = parsed.text;
219
+ if (parsed.definite) {
220
+ finalText += parsed.text;
221
+ current = '';
222
+ try { emitPartial(finalText); } catch {}
223
+ } else if (current) {
224
+ try { emitPartial(finalText + current); } catch {}
225
+ }
226
+ armIdle();
227
+ }
228
+
229
+ try {
230
+ socket = new WebSocket(url, { handshakeTimeout: CONNECT_TIMEOUT_MS });
231
+ } catch {
232
+ clearTimers();
233
+ detachAbort();
234
+ queueMicrotask(() => fail(voiceError('voice-provider-unavailable', '讯飞地址不可用')));
235
+ return noop;
236
+ }
237
+
238
+ socket.on('open', () => {
239
+ opened = true;
240
+ clearTimeout(connectTimer);
241
+ for (const pcm of pendingAudio) sendAudio(pcm);
242
+ pendingAudio.length = 0;
243
+ if (finishRequested) sendJson({ data: JSON.stringify({ end: true }) });
244
+ armIdle();
245
+ });
246
+
247
+ socket.on('message', (data) => {
248
+ if (settled) return;
249
+ armIdle();
250
+ handleMessage(data);
251
+ });
252
+
253
+ socket.on('error', () => {
254
+ fail(voiceError('voice-provider-unavailable', '讯飞连接失败'));
255
+ });
256
+
257
+ socket.on('close', () => {
258
+ if (settled) return;
259
+ if (finishRequested) succeed();
260
+ else fail(voiceError('voice-provider-unavailable', '讯飞连接被关闭'));
261
+ });
262
+
263
+ return {
264
+ push(pcmBuf, _seq) {
265
+ if (settled || !pcmBuf || !pcmBuf.length) return;
266
+ const pcm = Buffer.isBuffer(pcmBuf) ? pcmBuf : Buffer.from(pcmBuf);
267
+ if (!opened) {
268
+ pendingAudio.push(pcm);
269
+ return;
270
+ }
271
+ sendAudio(pcm);
272
+ },
273
+ finish() {
274
+ if (settled || finishRequested) return;
275
+ finishRequested = true;
276
+ if (!opened) return;
277
+ sendJson({ data: JSON.stringify({ end: true }) });
278
+ clearTimeout(idleTimer);
279
+ finishTimer = setTimeout(() => succeed(), FINISH_TIMEOUT_MS);
280
+ },
281
+ cancel() {
282
+ if (settled) return;
283
+ settled = true;
284
+ clearTimers();
285
+ detachAbort();
286
+ closeSocket();
287
+ },
288
+ };
289
+ },
290
+ };