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.
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/pairing.md +2 -2
- package/lib/impl.js +8 -5
- package/lib/mobile/permissions.js +10 -0
- package/lib/mobile/session-step.js +17 -11
- package/lib/mobile/voice/frames.js +198 -0
- package/lib/mobile/voice/gateway.js +746 -0
- package/lib/mobile/voice/lang.js +347 -0
- package/lib/mobile/voice/lexicon-store.js +189 -0
- package/lib/mobile/voice/lexicon.js +508 -0
- package/lib/mobile/voice/panel-api.js +88 -0
- package/lib/mobile/voice/postprocess.js +551 -0
- package/lib/mobile/voice/protocol.js +306 -0
- package/lib/mobile/voice/providers/cn/aliyun.js +401 -0
- package/lib/mobile/voice/providers/cn/tencent.js +402 -0
- package/lib/mobile/voice/providers/cn/volc.js +328 -0
- package/lib/mobile/voice/providers/cn/xfyun.js +290 -0
- package/lib/mobile/voice/providers/host.js +190 -0
- package/lib/mobile/voice/providers/intl/_common.js +346 -0
- package/lib/mobile/voice/providers/intl/assemblyai.js +353 -0
- package/lib/mobile/voice/providers/intl/azure.js +444 -0
- package/lib/mobile/voice/providers/intl/deepgram.js +366 -0
- package/lib/mobile/voice/providers/intl/openai.js +389 -0
- package/lib/mobile/voice/providers/intl/speechmatics.js +405 -0
- package/lib/mobile/voice/providers/local/ondevice.js +129 -0
- package/lib/mobile/voice/providers/registry.js +277 -0
- package/lib/mobile/voice/routes.js +278 -0
- package/lib/mobile/voice/runtime.js +84 -0
- package/lib/mobile/voice/settings.js +206 -0
- package/lib/mobile/voice/stream.js +415 -0
- package/lib/mobile/voice/voice-provider.js +268 -0
- package/lib/panel/index.html +17 -17
- package/lib/routes/control-plane.js +19 -0
- package/lib/routes/mobile-api.js +33 -1
- package/lib/sidecar-facade-worker.cjs +1 -1
- package/package.json +13 -14
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// 2026-11-28:内置 host 适配器——委托宿主已装载的官方语音识别(零配置那一路)。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `host` provider:把识别交给**宿主已经装好的**语音包。
|
|
6
|
+
*
|
|
7
|
+
* 官方 DSH 的 `ctx.speechToText` 是「provider 注册制、`resolve()` 固定选一家」:已发布的两家
|
|
8
|
+
* 是 `sensevoice-local`(本地、带语种识别)与 `deepseek-asr`(云端、走账号,无需单独配置)。
|
|
9
|
+
* 插件这边不复刻它们的鉴权与重试,只做一次转交 —— 这样用户**登录了 DeepSeek 就能用语音**,
|
|
10
|
+
* 不需要在面板里填任何 key;宿主侧换了实现(换了 provider 或模型)插件也不用跟着改。
|
|
11
|
+
*
|
|
12
|
+
* 宿主没装语音包时 `ready()` 回 false,能力表里这一格是 `unavailable`,面板据此显示
|
|
13
|
+
* 「宿主未安装语音识别」,不画填 key 的输入框(它没有可填的东西)。
|
|
14
|
+
*
|
|
15
|
+
* ## 为什么留一层 bridge 而不是直接摸 ctx
|
|
16
|
+
*
|
|
17
|
+
* 适配器契约里没有 ctx(`transcribe({config, audio, hints, signal})`),而宿主服务是
|
|
18
|
+
* 运行时对象。`createHostBridge(ctx)` 把「怎么问宿主」收在一个小对象里,适配器本体就是
|
|
19
|
+
* 纯逻辑、测试可以用假的 bridge 整段仿真,不碰真宿主。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const { VOICE_ERRORS, voiceError } = require('../protocol.js');
|
|
23
|
+
const { PROVIDER_STATUS } = require('../voice-provider.js');
|
|
24
|
+
|
|
25
|
+
/** 官方两家 provider 的展示名。认不出来(将来换了实现)就用宿主那家自己的 id。 */
|
|
26
|
+
const HOST_PROVIDER_NAMES = Object.freeze({
|
|
27
|
+
'sensevoice-local': '本机 SenseVoice',
|
|
28
|
+
'deepseek-asr': 'DeepSeek 云端识别',
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 从插件 ctx 取宿主语音服务。
|
|
33
|
+
*
|
|
34
|
+
* 两种取法都试:0.2.x 之后服务走 `ctx.get(name)`;老宿主 / 测试里也可能直接挂在 ctx 上。
|
|
35
|
+
* 取不到就是 null —— 「宿主没装语音包」是正常状态,不是错误。
|
|
36
|
+
*/
|
|
37
|
+
function hostSpeechService(ctx) {
|
|
38
|
+
if (!ctx) return null;
|
|
39
|
+
try {
|
|
40
|
+
if (typeof ctx.get === 'function') {
|
|
41
|
+
const service = ctx.get('speechToText');
|
|
42
|
+
if (service) return service;
|
|
43
|
+
}
|
|
44
|
+
} catch { /* 服务不存在时 ctx.get 会抛,按没有处理 */ }
|
|
45
|
+
// 本插件没有声明 `speechToText` 的注入(它是可选服务:声明了会变成「宿主没装就永远起不来」),
|
|
46
|
+
// 于是自己这个 fiber 上 `ctx.get` / `ctx.speechToText` 都会被 cordis 拒。根上下文不受这条
|
|
47
|
+
// 限制,服务本身注册在根上,从那里取一次。
|
|
48
|
+
try {
|
|
49
|
+
const root = ctx.root;
|
|
50
|
+
if (root && typeof root.get === 'function') {
|
|
51
|
+
const service = root.get('speechToText');
|
|
52
|
+
if (service) return service;
|
|
53
|
+
}
|
|
54
|
+
} catch { /* 取不到就是没有 */ }
|
|
55
|
+
// 直接读属性这条只在没声明 inject 的上下文里会抛(cordis 的
|
|
56
|
+
// “cannot get property … without inject”)。宿主没装语音包是正常状态,
|
|
57
|
+
// 但没声明 inject 是取法的问题:两种都要按「没有」处理,不能让面板整页 400。
|
|
58
|
+
try {
|
|
59
|
+
const direct = ctx.speechToText;
|
|
60
|
+
return direct && typeof direct === 'object' ? direct : null;
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 宿主语音服务的传输口。
|
|
68
|
+
*
|
|
69
|
+
* 宿主契约(见 `docs/voice-input-plan.md` §1.2)只说了 `resolve()` 固定选一家、两家都只支持
|
|
70
|
+
* 整段;具体方法签名在插件这一侧不可靠,所以这里按「先问服务、再问 provider」的顺序取:
|
|
71
|
+
* 服务自己有 `transcribe` 就调服务,否则 `resolve()` 拿到 provider 再调它的。**只做这一层
|
|
72
|
+
* 适配,不做重试**(宿主自己已经处理好超时与失败语义)。
|
|
73
|
+
*
|
|
74
|
+
* @param {object} ctx 插件 ctx
|
|
75
|
+
* @param {(msg: string, ...rest: any[]) => void} [log]
|
|
76
|
+
*/
|
|
77
|
+
function createHostBridge(ctx, log = () => {}) {
|
|
78
|
+
const service = hostSpeechService(ctx);
|
|
79
|
+
const available = Boolean(service) && (
|
|
80
|
+
typeof service.transcribe === 'function'
|
|
81
|
+
|| typeof service.resolve === 'function'
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
/** 选中的宿主 provider(懒解析、失败缓存;宿主服务是进程级对象,不会中途换)。 */
|
|
85
|
+
let resolved = null;
|
|
86
|
+
let resolveFailed = false;
|
|
87
|
+
async function resolveProvider() {
|
|
88
|
+
if (resolved || resolveFailed) return resolved;
|
|
89
|
+
try {
|
|
90
|
+
const picked = typeof service.resolve === 'function' ? await service.resolve() : service;
|
|
91
|
+
if (!picked) { resolveFailed = true; return null; }
|
|
92
|
+
resolved = picked;
|
|
93
|
+
return resolved;
|
|
94
|
+
} catch (error) {
|
|
95
|
+
resolveFailed = true;
|
|
96
|
+
log('语音:宿主 speechToText.resolve() 失败', error && error.message ? error.message : error);
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function providerIdOf(provider) {
|
|
102
|
+
if (!provider || typeof provider !== 'object') return '';
|
|
103
|
+
return typeof provider.id === 'string' && provider.id ? provider.id : '';
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
available,
|
|
108
|
+
/** 宿主那边的 provider id(官方两家是 sensevoice-local / deepseek-asr,未知时为空串)。 */
|
|
109
|
+
async providerId() {
|
|
110
|
+
return providerIdOf(await resolveProvider());
|
|
111
|
+
},
|
|
112
|
+
/**
|
|
113
|
+
* 整段识别。`audio` 是 WAV Buffer;回 `{ text, lang? }`。
|
|
114
|
+
*
|
|
115
|
+
* 宿主没装语音包 / 解析不出 provider → `voice-provider-unavailable`;宿主自己抛出的错
|
|
116
|
+
* 原样往上抛(网关按 `code` 映射,宿主没给码就落到 `voice-failed`)。
|
|
117
|
+
*/
|
|
118
|
+
async transcribe({ audio, signal }) {
|
|
119
|
+
if (!available) throw voiceError(VOICE_ERRORS.PROVIDER_UNAVAILABLE, '宿主没有安装语音识别');
|
|
120
|
+
const provider = await resolveProvider();
|
|
121
|
+
const target = provider && typeof provider.transcribe === 'function' ? provider : service;
|
|
122
|
+
if (!target || typeof target.transcribe !== 'function') {
|
|
123
|
+
throw voiceError(VOICE_ERRORS.PROVIDER_UNAVAILABLE, '宿主语音识别的 provider 不可用');
|
|
124
|
+
}
|
|
125
|
+
// 取消要能传下去:宿主 provider 若认 signal 就跟着停,不认也只是多跑完一次。
|
|
126
|
+
const result = await target.transcribe(audio, signal ? { signal } : {});
|
|
127
|
+
return normalizeHostResult(result);
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 宿主回包形状收敛:`{text}` / `{result:{text}}` / 字符串三种都见过,统一成契约形状。 */
|
|
133
|
+
function normalizeHostResult(result) {
|
|
134
|
+
const raw = result && typeof result === 'object' ? result : {};
|
|
135
|
+
const text = typeof result === 'string'
|
|
136
|
+
? result
|
|
137
|
+
: (typeof raw.text === 'string' ? raw.text : (raw.result && typeof raw.result.text === 'string' ? raw.result.text : ''));
|
|
138
|
+
if (!text) throw voiceError(VOICE_ERRORS.FAILED, '宿主语音识别没有返回文本');
|
|
139
|
+
const lang = typeof raw.lang === 'string' && raw.lang ? raw.lang
|
|
140
|
+
: (raw.result && typeof raw.result.lang === 'string' && raw.result.lang ? raw.result.lang : undefined);
|
|
141
|
+
return { text, ...(lang ? { lang } : {}) };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* 造 host 适配器。registry 每次建网关时调一次,bridge 里已经钉住了这一代的 ctx。
|
|
146
|
+
*
|
|
147
|
+
* @param {ReturnType<typeof createHostBridge>} bridge
|
|
148
|
+
*/
|
|
149
|
+
function createHostProvider(bridge) {
|
|
150
|
+
const hostBridge = bridge || { available: false };
|
|
151
|
+
return {
|
|
152
|
+
id: 'host',
|
|
153
|
+
name: '宿主语音识别',
|
|
154
|
+
kind: 'host',
|
|
155
|
+
// 官方两家都只支持整段:`stream` 那条由网关内部攒成整段再送、只发 final(契约 §2)。
|
|
156
|
+
batch: true,
|
|
157
|
+
streaming: false,
|
|
158
|
+
// 语言由宿主 provider 自判;官方云端只报 auto,本地 SenseVoice 带语种识别。
|
|
159
|
+
languages: ['auto', 'zh', 'en', 'ja', 'ko'],
|
|
160
|
+
// 官方两家都不支持热词 / 上下文(`docs/voice-input-plan.md` §1.2),别假装支持。
|
|
161
|
+
hotwords: false,
|
|
162
|
+
maxSeconds: 120,
|
|
163
|
+
maxBytes: 8 * 1024 * 1024,
|
|
164
|
+
// 没有任何需要用户填的配置:登录 DeepSeek 或装本地语音包就可用。
|
|
165
|
+
configFields: [],
|
|
166
|
+
ready() {
|
|
167
|
+
return hostBridge.available === true;
|
|
168
|
+
},
|
|
169
|
+
async transcribe({ audio, signal, log }) {
|
|
170
|
+
const result = await hostBridge.transcribe({ audio, signal });
|
|
171
|
+
if (typeof log === 'function') log(`语音:host 识别 ${result.text.length} 字`);
|
|
172
|
+
return result;
|
|
173
|
+
},
|
|
174
|
+
/** 不支持流式;给一个明确的失败而不是让网关误以为能走 `stream`。 */
|
|
175
|
+
stream() {
|
|
176
|
+
throw voiceError(VOICE_ERRORS.PROVIDER_UNAVAILABLE, '宿主语音识别不支持流式');
|
|
177
|
+
},
|
|
178
|
+
/** 面板要展示「现在绑到了宿主哪一家」(认不出来就是空串)。 */
|
|
179
|
+
hostProviderId: () => (typeof hostBridge.providerId === 'function' ? hostBridge.providerId() : Promise.resolve('')),
|
|
180
|
+
status: () => (hostBridge.available ? PROVIDER_STATUS.AVAILABLE : PROVIDER_STATUS.UNAVAILABLE),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
module.exports = {
|
|
185
|
+
createHostBridge,
|
|
186
|
+
createHostProvider,
|
|
187
|
+
hostSpeechService,
|
|
188
|
+
normalizeHostResult,
|
|
189
|
+
HOST_PROVIDER_NAMES,
|
|
190
|
+
};
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
// 国外语音厂商适配器共用的网络细节:超时、取消、HTTP/WS 建连、错误码映射、语言码归一。
|
|
2
|
+
// 只被 providers/intl/* 引用,网关不认识这里;凭据不落日志、不进错误信息。
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
const { WebSocket } = require('ws');
|
|
6
|
+
|
|
7
|
+
/** 契约里的统一错误码(与 docs/voice-input-contract.md 第二节一致)。 */
|
|
8
|
+
const CODES = Object.freeze({
|
|
9
|
+
DISABLED: 'voice-disabled',
|
|
10
|
+
MISSING: 'voice-provider-missing',
|
|
11
|
+
UNAVAILABLE: 'voice-provider-unavailable',
|
|
12
|
+
INVALID_AUDIO: 'voice-invalid-audio',
|
|
13
|
+
TOO_LONG: 'voice-too-long',
|
|
14
|
+
TOO_LARGE: 'voice-too-large',
|
|
15
|
+
QUOTA: 'voice-quota',
|
|
16
|
+
RATE_LIMITED: 'voice-rate-limited',
|
|
17
|
+
TIMEOUT: 'voice-timeout',
|
|
18
|
+
FAILED: 'voice-failed',
|
|
19
|
+
CANCELLED: 'voice-cancelled',
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
/** 网关只认 code;message 给人看,绝不能出现凭据。 */
|
|
23
|
+
class VoiceError extends Error {
|
|
24
|
+
constructor(code, message, details) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = 'VoiceError';
|
|
27
|
+
this.code = code;
|
|
28
|
+
if (details) Object.assign(this, details);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const HTTP_CODE = {
|
|
33
|
+
400: CODES.INVALID_AUDIO,
|
|
34
|
+
401: CODES.UNAVAILABLE,
|
|
35
|
+
402: CODES.QUOTA,
|
|
36
|
+
403: CODES.UNAVAILABLE,
|
|
37
|
+
404: CODES.UNAVAILABLE,
|
|
38
|
+
408: CODES.TIMEOUT,
|
|
39
|
+
413: CODES.TOO_LARGE,
|
|
40
|
+
415: CODES.INVALID_AUDIO,
|
|
41
|
+
422: CODES.INVALID_AUDIO,
|
|
42
|
+
429: CODES.RATE_LIMITED,
|
|
43
|
+
500: CODES.FAILED,
|
|
44
|
+
502: CODES.UNAVAILABLE,
|
|
45
|
+
503: CODES.UNAVAILABLE,
|
|
46
|
+
504: CODES.TIMEOUT,
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
function mapHttpStatus(status) {
|
|
50
|
+
if (HTTP_CODE[status]) return HTTP_CODE[status];
|
|
51
|
+
if (status >= 500) return CODES.FAILED;
|
|
52
|
+
if (status >= 400) return CODES.FAILED;
|
|
53
|
+
return CODES.FAILED;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 把上游错误正文压成一句人类可读的话,压掉超长正文与可能回显的凭据。 */
|
|
57
|
+
function errorDetail(bodyText, secrets) {
|
|
58
|
+
const text = typeof bodyText === 'string' ? bodyText.trim() : '';
|
|
59
|
+
if (!text) return '';
|
|
60
|
+
let detail = text;
|
|
61
|
+
try {
|
|
62
|
+
const json = JSON.parse(text);
|
|
63
|
+
detail =
|
|
64
|
+
(json && json.error && (json.error.message || json.error.code)) ||
|
|
65
|
+
(json && (json.message || json.detail || json.error || json.code)) ||
|
|
66
|
+
text;
|
|
67
|
+
} catch {
|
|
68
|
+
// 不是 JSON 就原样截断
|
|
69
|
+
}
|
|
70
|
+
detail = scrub(String(detail), secrets);
|
|
71
|
+
return detail.length > 200 ? `${detail.slice(0, 200)}…` : detail;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 去掉消息里出现的凭据片段;适配器抛错前统一过这一道。 */
|
|
75
|
+
function scrub(text, secrets) {
|
|
76
|
+
let out = String(text == null ? '' : text);
|
|
77
|
+
for (const secret of secrets || []) {
|
|
78
|
+
if (typeof secret === 'string' && secret.length >= 6) out = out.split(secret).join('[redacted]');
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function httpError(label, status, bodyText, secrets) {
|
|
84
|
+
const detail = errorDetail(bodyText, secrets);
|
|
85
|
+
return new VoiceError(mapHttpStatus(status), `${label}返回 HTTP ${status}${detail ? `:${detail}` : ''}`, { status });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function transportError(err, deadline, label, secrets) {
|
|
89
|
+
if (deadline && deadline.timedOut()) return new VoiceError(CODES.TIMEOUT, `${label}超时`);
|
|
90
|
+
if ((deadline && deadline.callerAborted()) || (err && err.name === 'AbortError')) {
|
|
91
|
+
return new VoiceError(CODES.CANCELLED, `${label}已取消`, { cancelled: true });
|
|
92
|
+
}
|
|
93
|
+
return new VoiceError(CODES.FAILED, `${label}网络失败:${scrub(err && err.message, secrets)}`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 合并调用方 signal 与本适配器的超时,两者都能中断请求。 */
|
|
97
|
+
function deadlineFor(signal, timeoutMs) {
|
|
98
|
+
const timeout = timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : null;
|
|
99
|
+
const list = [];
|
|
100
|
+
if (signal) list.push(signal);
|
|
101
|
+
if (timeout) list.push(timeout);
|
|
102
|
+
const combined = list.length === 0 ? null : list.length === 1 ? list[0] : AbortSignal.any(list);
|
|
103
|
+
return {
|
|
104
|
+
signal: combined || undefined,
|
|
105
|
+
callerAborted: () => Boolean(signal && signal.aborted),
|
|
106
|
+
timedOut: () => Boolean(timeout && timeout.aborted),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 发一个 HTTP 请求并读完正文。
|
|
112
|
+
* @returns {Promise<{status:number, headers:object, text:string, json:any}>}
|
|
113
|
+
*/
|
|
114
|
+
async function httpRequest(url, options = {}) {
|
|
115
|
+
const { method = 'POST', headers = {}, body, signal, timeoutMs = 30000, label = '语音服务', secrets = [] } = options;
|
|
116
|
+
const deadline = deadlineFor(signal, timeoutMs);
|
|
117
|
+
let res;
|
|
118
|
+
try {
|
|
119
|
+
res = await fetch(url, { method, headers, body, signal: deadline.signal });
|
|
120
|
+
} catch (err) {
|
|
121
|
+
throw transportError(err, deadline, label, secrets);
|
|
122
|
+
}
|
|
123
|
+
let text = '';
|
|
124
|
+
try {
|
|
125
|
+
text = await res.text();
|
|
126
|
+
} catch (err) {
|
|
127
|
+
throw transportError(err, deadline, label, secrets);
|
|
128
|
+
}
|
|
129
|
+
let json = null;
|
|
130
|
+
try {
|
|
131
|
+
json = text ? JSON.parse(text) : null;
|
|
132
|
+
} catch {
|
|
133
|
+
json = null;
|
|
134
|
+
}
|
|
135
|
+
return { status: res.status, headers: res.headers, text, json };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** 发请求并要求 2xx;否则按状态码映射成统一错误。 */
|
|
139
|
+
async function httpJson(url, options = {}) {
|
|
140
|
+
const res = await httpRequest(url, options);
|
|
141
|
+
if (res.status < 200 || res.status >= 300) throw httpError(options.label || '语音服务', res.status, res.text, options.secrets);
|
|
142
|
+
return res;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 建 WebSocket;握手阶段的 4xx/5xx 与超时、取消都在这里收口。 */
|
|
146
|
+
function openWs(url, options = {}) {
|
|
147
|
+
const { headers = {}, signal, timeoutMs = 15000, label = '语音服务连接', secrets = [] } = options;
|
|
148
|
+
return new Promise((resolve, reject) => {
|
|
149
|
+
const ws = new WebSocket(url, { headers });
|
|
150
|
+
let settled = false;
|
|
151
|
+
let timer = null;
|
|
152
|
+
const onAbort = () => {
|
|
153
|
+
ws.terminate();
|
|
154
|
+
settle(reject, new VoiceError(CODES.CANCELLED, `${label}已取消`, { cancelled: true }));
|
|
155
|
+
};
|
|
156
|
+
function settle(fn, value) {
|
|
157
|
+
if (settled) return;
|
|
158
|
+
settled = true;
|
|
159
|
+
if (timer) clearTimeout(timer);
|
|
160
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
161
|
+
fn(value);
|
|
162
|
+
}
|
|
163
|
+
if (signal) {
|
|
164
|
+
if (signal.aborted) {
|
|
165
|
+
ws.terminate();
|
|
166
|
+
reject(new VoiceError(CODES.CANCELLED, `${label}已取消`, { cancelled: true }));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
170
|
+
}
|
|
171
|
+
timer = setTimeout(() => {
|
|
172
|
+
ws.terminate();
|
|
173
|
+
settle(reject, new VoiceError(CODES.TIMEOUT, `${label}超时`));
|
|
174
|
+
}, Math.max(1, timeoutMs));
|
|
175
|
+
if (timer.unref) timer.unref();
|
|
176
|
+
ws.once('open', () => settle(resolve, ws));
|
|
177
|
+
ws.once('unexpected-response', (_req, res) => {
|
|
178
|
+
const status = res && res.statusCode;
|
|
179
|
+
if (res && typeof res.resume === 'function') res.resume();
|
|
180
|
+
ws.terminate();
|
|
181
|
+
settle(reject, httpError(label, status, '', secrets));
|
|
182
|
+
});
|
|
183
|
+
// 只吃掉握手期的错误;连上之后的错误由适配器自己的监听处理。
|
|
184
|
+
ws.once('error', (err) => settle(reject, transportError(err, deadlineFor(signal, 0), label, secrets)));
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 语言码归一:'zh-CN' -> 'zh','auto'/空 都当自动。 */
|
|
189
|
+
function baseLang(lang) {
|
|
190
|
+
const value = String(lang == null ? '' : lang).trim().toLowerCase();
|
|
191
|
+
if (!value || value === 'auto') return 'auto';
|
|
192
|
+
return value.split(/[-_]/)[0];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** 按映射表翻成厂商语言码;没命中就退回基础码。 */
|
|
196
|
+
function localeOf(lang, table) {
|
|
197
|
+
const base = baseLang(lang);
|
|
198
|
+
if (base === 'auto') return 'auto';
|
|
199
|
+
return (table && table[base]) || base;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** 把热词整理成去重、限长的字符串数组;厂商对词条数量与长度都有上限。 */
|
|
203
|
+
function cleanHotwords(hotwords, { max = 50, maxLen = 60 } = {}) {
|
|
204
|
+
if (!Array.isArray(hotwords)) return [];
|
|
205
|
+
const out = [];
|
|
206
|
+
const seen = new Set();
|
|
207
|
+
for (const raw of hotwords) {
|
|
208
|
+
if (typeof raw !== 'string') continue;
|
|
209
|
+
const word = raw.trim();
|
|
210
|
+
if (!word || word.length > maxLen) continue;
|
|
211
|
+
const key = word.toLowerCase();
|
|
212
|
+
if (seen.has(key)) continue;
|
|
213
|
+
seen.add(key);
|
|
214
|
+
out.push(word);
|
|
215
|
+
if (out.length >= max) break;
|
|
216
|
+
}
|
|
217
|
+
return out;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** 把上下文字符串压成各家 prompt 可接受的短文本。 */
|
|
221
|
+
function cleanContext(context, maxLen = 400) {
|
|
222
|
+
if (typeof context !== 'string') return '';
|
|
223
|
+
const text = context.replace(/\s+/g, ' ').trim();
|
|
224
|
+
return text.length > maxLen ? text.slice(0, maxLen) : text;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function safeLog(log, message) {
|
|
228
|
+
if (typeof log === 'function') {
|
|
229
|
+
try {
|
|
230
|
+
log(message);
|
|
231
|
+
} catch {
|
|
232
|
+
// 日志失败不影响识别
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function backoff(ms, signal) {
|
|
238
|
+
return new Promise((resolve, reject) => {
|
|
239
|
+
if (signal && signal.aborted) {
|
|
240
|
+
reject(new VoiceError(CODES.CANCELLED, '已取消', { cancelled: true }));
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
const timer = setTimeout(() => {
|
|
244
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
245
|
+
resolve();
|
|
246
|
+
}, ms);
|
|
247
|
+
function onAbort() {
|
|
248
|
+
clearTimeout(timer);
|
|
249
|
+
reject(new VoiceError(CODES.CANCELLED, '已取消', { cancelled: true }));
|
|
250
|
+
}
|
|
251
|
+
if (signal) signal.addEventListener('abort', onAbort, { once: true });
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** 关闭 WebSocket 并等它真的关上;超时不再等,直接掐断。 */
|
|
256
|
+
function closeWs(ws, { code = 1000, graceMs = 1500 } = {}) {
|
|
257
|
+
if (!ws) return Promise.resolve();
|
|
258
|
+
if (ws.readyState === WebSocket.CLOSED) return Promise.resolve();
|
|
259
|
+
return new Promise((resolve) => {
|
|
260
|
+
let done = false;
|
|
261
|
+
const finish = () => {
|
|
262
|
+
if (done) return;
|
|
263
|
+
done = true;
|
|
264
|
+
clearTimeout(timer);
|
|
265
|
+
ws.removeListener('close', finish);
|
|
266
|
+
resolve();
|
|
267
|
+
};
|
|
268
|
+
const timer = setTimeout(() => {
|
|
269
|
+
try {
|
|
270
|
+
ws.terminate();
|
|
271
|
+
} catch {
|
|
272
|
+
// 已经断了
|
|
273
|
+
}
|
|
274
|
+
finish();
|
|
275
|
+
}, graceMs);
|
|
276
|
+
if (timer.unref) timer.unref();
|
|
277
|
+
ws.once('close', finish);
|
|
278
|
+
try {
|
|
279
|
+
ws.close(code);
|
|
280
|
+
} catch {
|
|
281
|
+
ws.terminate();
|
|
282
|
+
finish();
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** 等待 WebSocket 关闭,期间保持消息处理;用于 finish() 收尾。 */
|
|
288
|
+
function waitForClose(ws, timeoutMs = 5000, signal) {
|
|
289
|
+
return new Promise((resolve, reject) => {
|
|
290
|
+
if (!ws) {
|
|
291
|
+
resolve();
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
let done = false;
|
|
295
|
+
const finish = (err) => {
|
|
296
|
+
if (done) return;
|
|
297
|
+
done = true;
|
|
298
|
+
clearTimeout(timer);
|
|
299
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
300
|
+
ws.removeListener('close', onClose);
|
|
301
|
+
if (err) reject(err);
|
|
302
|
+
else resolve();
|
|
303
|
+
};
|
|
304
|
+
const onClose = () => finish(null);
|
|
305
|
+
const onAbort = () => {
|
|
306
|
+
try {
|
|
307
|
+
ws.terminate();
|
|
308
|
+
} catch {
|
|
309
|
+
// 忽略
|
|
310
|
+
}
|
|
311
|
+
finish(new VoiceError(CODES.CANCELLED, '已取消', { cancelled: true }));
|
|
312
|
+
};
|
|
313
|
+
const timer = setTimeout(() => {
|
|
314
|
+
try {
|
|
315
|
+
ws.terminate();
|
|
316
|
+
} catch {
|
|
317
|
+
// 忽略
|
|
318
|
+
}
|
|
319
|
+
finish(null);
|
|
320
|
+
}, Math.max(1, timeoutMs));
|
|
321
|
+
if (timer.unref) timer.unref();
|
|
322
|
+
if (ws.readyState === WebSocket.CLOSED) {
|
|
323
|
+
finish(null);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
ws.once('close', onClose);
|
|
327
|
+
if (signal) signal.addEventListener('abort', onAbort, { once: true });
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
module.exports = {
|
|
332
|
+
CODES,
|
|
333
|
+
VoiceError,
|
|
334
|
+
httpRequest,
|
|
335
|
+
httpJson,
|
|
336
|
+
openWs,
|
|
337
|
+
baseLang,
|
|
338
|
+
localeOf,
|
|
339
|
+
cleanHotwords,
|
|
340
|
+
cleanContext,
|
|
341
|
+
safeLog,
|
|
342
|
+
scrub,
|
|
343
|
+
backoff,
|
|
344
|
+
closeWs,
|
|
345
|
+
waitForClose,
|
|
346
|
+
};
|