ai-helper-agent 2.4.8 → 2.5.0

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 (44) hide show
  1. package/README.md +33 -1
  2. package/README.zh-CN.md +33 -1
  3. package/bin/agent.js +78 -0
  4. package/dist/assets/{agent-store-BTqZ3_7C.js → agent-store-D0oEv0PW.js} +1 -1
  5. package/dist/assets/background.js +4 -4
  6. package/dist/assets/{chat-export-BE9AcllU.js → chat-export-MTTSSIwM.js} +1 -1
  7. package/dist/assets/content.js +28 -28
  8. package/dist/assets/i18n-Br_sF5pb.js +49 -0
  9. package/dist/assets/{markdown-render-BhfoP_jE.js → markdown-render-Dq5F_dqP.js} +2 -2
  10. package/dist/assets/{model-profiles-BlsZEsSZ.js → model-profiles-BdQaV4EZ.js} +1 -1
  11. package/dist/assets/{options-Dir2xv8X.css → options-JtYgxtsc.css} +1 -1
  12. package/dist/assets/options.js +297 -238
  13. package/dist/assets/{page-snapshot-renderer-2AUkuzX_.js → page-snapshot-renderer-Cl0qk7U1.js} +1 -1
  14. package/dist/assets/{session-store-Xg-R-TyE.js → session-store-KkrAlIc6.js} +3 -3
  15. package/dist/assets/side_panel.css +1 -1
  16. package/dist/assets/side_panel.js +174 -174
  17. package/dist/assets/{utils-CTRffrs-.js → utils-ZJjxSlg_.js} +1 -1
  18. package/dist/assets/{version-D_5kiJwl.js → version-C0CY79zF.js} +1 -1
  19. package/dist/manifest.json +1 -1
  20. package/dist/offscreen/offscreen.js +8 -8
  21. package/dist/options.html +38 -4
  22. package/dist/side_panel.html +25 -7
  23. package/dist/voice-capture-worklet.js +47 -0
  24. package/package.json +4 -1
  25. package/src/asr/config.js +155 -0
  26. package/src/asr/detect.js +215 -0
  27. package/src/asr/engine.js +347 -0
  28. package/src/asr/install.js +439 -0
  29. package/src/asr/model-catalog.js +207 -0
  30. package/src/asr/model-download.js +461 -0
  31. package/src/asr/model-pack.js +398 -0
  32. package/src/asr/offline-pool.js +283 -0
  33. package/src/asr/offline-worker.js +97 -0
  34. package/src/asr/probe-child.mjs +31 -0
  35. package/src/asr/routes.js +385 -0
  36. package/src/asr/session.js +435 -0
  37. package/src/asr/transcribe.js +310 -0
  38. package/src/directory-picker.js +157 -45
  39. package/src/locales/cli.json +26 -0
  40. package/src/locales/en.json +22 -1
  41. package/src/locales/zh.json +22 -1
  42. package/src/rag/install.js +60 -2
  43. package/src/server.js +136 -2
  44. package/dist/assets/i18n-DBVIgrwQ.js +0 -49
@@ -0,0 +1,439 @@
1
+ // agent/src/asr/install.js - 语音输入可选依赖一键安装
2
+ //
3
+ // 安全设计(与 rag/install.js 同构,刻意不共有代码以免改动 RAG 的已验证行为):
4
+ // - 不接受调用方传入的包名:安装清单是包自身 package.json 的 asrDependencies 字段
5
+ // (单一事实来源),安装命令显式携带该清单构建的 pkg@spec
6
+ // - 非 Windows 严格 shell: false;Windows 优先用当前 Node 直执行 npm-cli.js
7
+ // (shell: false,规避 cmd 把 pkg@^x.y.z 的 ^ 当转义符吞掉),探测不到时降级
8
+ // npm.cmd + shell: true 并对 spec 加双引号(参数为纯静态常量,无用户输入,无注入面)
9
+ // - 异步任务 + 安装锁(同一时刻仅一个任务),超时上限 10 分钟
10
+ // - POSIX 以 detached: true 启动 npm(进程组组长),终止走进程树组杀
11
+ // - 状态持久化到 ~/.ai-helper-agent/asr-install-state.json:重启后把「运行中」收敛为「已中止」
12
+ // - 安装完成后在子进程重新探测依赖(防「装上但加载失败」的假成功)
13
+ //
14
+ // 与 RAG 的唯一刻意差异:**不做自动重装**。ASR 包体大(约 300MB+),自动重装会在用户
15
+ // 无感知的情况下拉满带宽;只记录 everSucceeded,状态里提示「依赖已被清理,请点击重新安装」。
16
+
17
+ import { spawn } from 'child_process';
18
+ import { fileURLToPath } from 'url';
19
+ import { dirname, join } from 'path';
20
+ import { homedir } from 'os';
21
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
22
+ import { resetAsrDetection, detectAsrAvailable, getLastAsrProbeError } from './detect.js';
23
+ import { stopProcessTree } from '../process-tree.js';
24
+ import { logSystem } from '../logger.js';
25
+ import { t as translate, parseAcceptLanguage } from '../i18n.js';
26
+ import { getRegistryUrl } from '../install-mode.js';
27
+
28
+ /**
29
+ * agent 包根目录(install.js 位于 <agent>/src/asr/,向上两级)
30
+ */
31
+ function getAgentRoot() {
32
+ return join(dirname(fileURLToPath(import.meta.url)), '..', '..');
33
+ }
34
+
35
+ /**
36
+ * 读取包内 package.json 的 asrDependencies(读取失败/字段缺失返回空,由构建方拒绝安装)
37
+ * @returns {Array<[string, string]>}
38
+ */
39
+ function readAsrDependencies() {
40
+ try {
41
+ const raw = JSON.parse(readFileSync(join(getAgentRoot(), 'package.json'), 'utf-8'));
42
+ const deps = raw && typeof raw.asrDependencies === 'object' && raw.asrDependencies !== null
43
+ ? raw.asrDependencies
44
+ : {};
45
+ return Object.entries(deps).filter(([name, spec]) => name && typeof spec === 'string' && spec.trim());
46
+ } catch {
47
+ return [];
48
+ }
49
+ }
50
+
51
+ const ASR_DEPENDENCY_ENTRIES = readAsrDependencies();
52
+
53
+ // 包名清单(供状态接口/前端展示)
54
+ export const ASR_INSTALL_PACKAGES = ASR_DEPENDENCY_ENTRIES.map(([name]) => name);
55
+
56
+ /**
57
+ * 安装 spec 列表(name@version-range):一键安装命令的显式参数
58
+ * @returns {string[]}
59
+ */
60
+ export function getAsrInstallSpecs() {
61
+ return ASR_DEPENDENCY_ENTRIES.map(([name, spec]) => `${name}@${spec}`);
62
+ }
63
+
64
+ /**
65
+ * 取 spec 的包名(兼容 scoped:@scope/pkg@^1.0.0 → @scope/pkg)
66
+ * @param {string} spec
67
+ * @returns {string}
68
+ */
69
+ function specName(spec) {
70
+ const idx = spec.lastIndexOf('@');
71
+ return idx > 0 ? spec.slice(0, idx) : spec;
72
+ }
73
+
74
+ /**
75
+ * 读取「对侧」可选组件(RAG)曾安装成功的依赖 spec,用于合并安装
76
+ *
77
+ * 背景(实测缺陷):ASR 与 RAG 的可选依赖都以 `npm install --no-save` 装在同一个
78
+ * 包目录里。npm 执行带包名的 install 时会按依赖树重算包目录,把不在本次清单内的
79
+ * 顶层包当作 extraneous 移除——只带自己清单安装,就会把 RAG 整组依赖清掉。
80
+ * 判据用对侧状态文件的 everSucceeded(持久化,不随目录被清而丢失):只要对方曾经
81
+ * 装成功过,就把它的清单一起带上,既避免互相清除,也顺带恢复已被清掉的对方。
82
+ * @returns {string[]}
83
+ */
84
+ function readPeerPreservedSpecs() {
85
+ try {
86
+ const stateFile = join(homedir(), '.ai-helper-agent', 'rag-install-state.json');
87
+ if (!existsSync(stateFile)) return [];
88
+ const state = JSON.parse(readFileSync(stateFile, 'utf-8'));
89
+ if (!state || state.everSucceeded !== true) return [];
90
+ const raw = JSON.parse(readFileSync(join(getAgentRoot(), 'package.json'), 'utf-8'));
91
+ const deps = raw && typeof raw.ragDependencies === 'object' && raw.ragDependencies !== null
92
+ ? raw.ragDependencies
93
+ : {};
94
+ return Object.entries(deps)
95
+ .filter(([name, spec]) => name && typeof spec === 'string' && spec.trim())
96
+ .map(([name, spec]) => `${name}@${spec}`);
97
+ } catch {
98
+ return [];
99
+ }
100
+ }
101
+
102
+ /**
103
+ * 合并本组件清单与对侧保全清单(同名包以本组件 spec 为准,本组件顺序在前)
104
+ * @param {string[]} ownSpecs
105
+ * @param {string[]} peerSpecs
106
+ * @returns {string[]}
107
+ */
108
+ function mergePreservedSpecs(ownSpecs, peerSpecs) {
109
+ const seen = new Set(ownSpecs.map(specName));
110
+ const merged = [...ownSpecs];
111
+ for (const spec of peerSpecs) {
112
+ const name = specName(spec);
113
+ if (!name || seen.has(name)) continue;
114
+ seen.add(name);
115
+ merged.push(spec);
116
+ }
117
+ return merged;
118
+ }
119
+
120
+ /**
121
+ * Windows:定位与 node 同目录分布的 npm-cli.js
122
+ * @param {string} execPath
123
+ * @returns {string|null}
124
+ */
125
+ function findWinNpmCli(execPath) {
126
+ const candidate = join(dirname(execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js');
127
+ return existsSync(candidate) ? candidate : null;
128
+ }
129
+
130
+ /**
131
+ * 构建 ASR 依赖安装命令(API 一键安装与 CLI 共用;参数可注入供测试)
132
+ * @param {{ isWin?: boolean, execPath?: string, specs?: string[], registry?: string|null, cwd?: string }} [opts]
133
+ * @returns {{ command: string, args: string[], shell: boolean, cwd: string }}
134
+ */
135
+ export function buildAsrInstallCommand(opts = {}) {
136
+ const isWin = opts.isWin ?? process.platform === 'win32';
137
+ const execPath = opts.execPath ?? process.execPath;
138
+ const ownSpecs = opts.specs ?? getAsrInstallSpecs();
139
+ if (ownSpecs.length === 0) {
140
+ // 包损坏/被裁剪:拒绝构建(无包名参数的 npm install 会按依赖树重算包目录,不可接受)
141
+ throw new Error('asrDependencies missing in package.json');
142
+ }
143
+ // 显式注入 specs(测试/诊断)视为精确清单,不做对侧保全
144
+ const specs = opts.specs ? ownSpecs : mergePreservedSpecs(ownSpecs, readPeerPreservedSpecs());
145
+ const registryUrl = opts.registry ?? getRegistryUrl();
146
+ const baseArgs = ['install', '--no-save', '--no-audit', '--no-fund'];
147
+ if (registryUrl) baseArgs.push(`--registry=${registryUrl}`);
148
+ const cwd = opts.cwd ?? getAgentRoot();
149
+ if (isWin) {
150
+ const npmCli = findWinNpmCli(execPath);
151
+ if (npmCli) return { command: execPath, args: [npmCli, ...baseArgs, ...specs], shell: false, cwd };
152
+ return { command: 'npm.cmd', args: [...baseArgs, ...specs.map((s) => `"${s}"`)], shell: true, cwd };
153
+ }
154
+ return { command: 'npm', args: [...baseArgs, ...specs], shell: false, cwd };
155
+ }
156
+
157
+ // 单次安装超时上限(10 分钟;需下载约 300MB 原生依赖)
158
+ const INSTALL_TIMEOUT_MS = 10 * 60 * 1000;
159
+
160
+ // 安装日志保留上限(行数)
161
+ const LOG_TAIL_LIMIT = 50;
162
+
163
+ // 任务状态持久化文件
164
+ const STATE_FILE = join(homedir(), '.ai-helper-agent', 'asr-install-state.json');
165
+
166
+ // 模块级语言:无请求上下文的场景(停服中止、重启收敛)消息用
167
+ const moduleT = (key, params) => translate(parseAcceptLanguage(), key, params);
168
+
169
+ // 安装任务状态(null = 从未安装)
170
+ let installTask = null;
171
+
172
+ // 运行中的 npm 子进程
173
+ let npmChild = null;
174
+
175
+ /**
176
+ * 收敛持久化字段(防状态文件被篡改/损坏)
177
+ */
178
+ function sanitizePersistedState(raw) {
179
+ if (!raw || typeof raw !== 'object') return null;
180
+ return {
181
+ running: raw.running === true,
182
+ done: raw.done === true,
183
+ success: raw.success === true,
184
+ everSucceeded: raw.everSucceeded === true,
185
+ phase: typeof raw.phase === 'string' ? raw.phase : null,
186
+ logTail: Array.isArray(raw.logTail) ? raw.logTail.filter((l) => typeof l === 'string').slice(-LOG_TAIL_LIMIT) : [],
187
+ startedAt: typeof raw.startedAt === 'number' ? raw.startedAt : null,
188
+ finishedAt: typeof raw.finishedAt === 'number' ? raw.finishedAt : null,
189
+ error: typeof raw.error === 'string' ? raw.error : null,
190
+ };
191
+ }
192
+
193
+ /**
194
+ * 持久化当前任务状态(写失败不阻塞安装主流程)
195
+ */
196
+ function savePersistedState() {
197
+ if (!installTask) return;
198
+ try {
199
+ mkdirSync(dirname(STATE_FILE), { recursive: true });
200
+ writeFileSync(STATE_FILE, JSON.stringify({
201
+ running: installTask.running,
202
+ done: installTask.done,
203
+ success: installTask.success,
204
+ everSucceeded: installTask.everSucceeded === true,
205
+ phase: installTask.phase,
206
+ logTail: installTask.logTail.slice(-LOG_TAIL_LIMIT),
207
+ startedAt: installTask.startedAt,
208
+ finishedAt: installTask.finishedAt,
209
+ error: installTask.error,
210
+ }), 'utf-8');
211
+ } catch (err) {
212
+ console.warn(`[ASR] persist install state failed: ${err.message}`);
213
+ }
214
+ }
215
+
216
+ // 模块加载时恢复上次任务状态:上次标记「运行中」说明进程被杀,收敛为「已中止」
217
+ (function restorePersistedState() {
218
+ let persisted = null;
219
+ try {
220
+ persisted = sanitizePersistedState(JSON.parse(readFileSync(STATE_FILE, 'utf-8')));
221
+ } catch {
222
+ persisted = null;
223
+ }
224
+ if (!persisted) return;
225
+ installTask = { ...persisted };
226
+ if (!persisted.running) return;
227
+ installTask.running = false;
228
+ installTask.done = true;
229
+ installTask.success = false;
230
+ installTask.phase = 'done';
231
+ installTask.finishedAt = Date.now();
232
+ installTask.error = moduleT('asr.installAborted');
233
+ savePersistedState();
234
+ })();
235
+
236
+ /**
237
+ * 启动 ASR 依赖安装(异步任务,立即返回)
238
+ * @param {Function} t 请求级翻译函数
239
+ * @returns {{ started: boolean, error?: string }}
240
+ */
241
+ export function startAsrInstall(t) {
242
+ if (installTask && installTask.running) {
243
+ // alreadyRunning 让前端区分「已在安装中」与「安装失败」:前者不该弹错误提示,
244
+ // 直接把界面切到进度态继续轮询(用户重复点击是常态,不是异常)
245
+ return { started: false, alreadyRunning: true, error: t('asr.installRunning') };
246
+ }
247
+
248
+ const task = {
249
+ running: true,
250
+ done: false,
251
+ success: false,
252
+ phase: 'installing',
253
+ logTail: [],
254
+ startedAt: Date.now(),
255
+ finishedAt: null,
256
+ error: null,
257
+ trigger: 'manual',
258
+ // 「曾成功安装过」只增不减
259
+ everSucceeded: Boolean(installTask && installTask.everSucceeded === true),
260
+ };
261
+ installTask = task;
262
+ savePersistedState();
263
+
264
+ runInstall(task, t).catch((err) => {
265
+ task.running = false;
266
+ task.done = true;
267
+ task.success = false;
268
+ task.phase = 'done';
269
+ task.error = err.message;
270
+ task.finishedAt = Date.now();
271
+ savePersistedState();
272
+ });
273
+
274
+ return { started: true, alreadyRunning: false };
275
+ }
276
+
277
+ /**
278
+ * 获取安装任务状态(供前端轮询)
279
+ * @returns {object}
280
+ */
281
+ export function getAsrInstallStatus() {
282
+ if (!installTask) {
283
+ return {
284
+ running: false,
285
+ done: false,
286
+ success: false,
287
+ everSucceeded: false,
288
+ phase: null,
289
+ logTail: [],
290
+ startedAt: null,
291
+ finishedAt: null,
292
+ error: null,
293
+ packages: ASR_INSTALL_PACKAGES,
294
+ };
295
+ }
296
+ return { ...installTask, packages: ASR_INSTALL_PACKAGES };
297
+ }
298
+
299
+ /**
300
+ * 是否曾成功安装过(前端据此提示「依赖已被清理,请重新安装」)
301
+ * @returns {boolean}
302
+ */
303
+ export function hasAsrEverInstalled() {
304
+ return Boolean(installTask && installTask.everSucceeded === true);
305
+ }
306
+
307
+ /**
308
+ * 中止运行中的安装并终止 npm 进程树(停服/重启路径调用)
309
+ * 幂等:无运行中的任务时返回 false
310
+ * @returns {Promise<boolean>}
311
+ */
312
+ export async function stopAsrInstall() {
313
+ const task = installTask;
314
+ const wasRunning = Boolean(task && task.running);
315
+ if (wasRunning) {
316
+ task.running = false;
317
+ task.done = true;
318
+ task.success = false;
319
+ task.phase = 'done';
320
+ task.finishedAt = Date.now();
321
+ task.error = moduleT('asr.installAborted');
322
+ task.aborted = true;
323
+ savePersistedState();
324
+ }
325
+ const child = npmChild;
326
+ npmChild = null;
327
+ if (child) {
328
+ await stopProcessTree(child, { graceMs: 5000 });
329
+ }
330
+ return wasRunning;
331
+ }
332
+
333
+ /**
334
+ * 执行安装 + 安装后验证
335
+ */
336
+ async function runInstall(task, t) {
337
+ const result = await runNpmInstall(task, t);
338
+
339
+ // 已被 stopAsrInstall 中止:状态已收敛并持久化,勿覆写
340
+ if (task.aborted) return;
341
+
342
+ if (!result.success) {
343
+ task.running = false;
344
+ task.done = true;
345
+ task.success = false;
346
+ task.phase = 'done';
347
+ task.error = result.error;
348
+ task.finishedAt = Date.now();
349
+ savePersistedState();
350
+ console.log(`[ASR] ${result.error}`);
351
+ return;
352
+ }
353
+
354
+ // npm 退出码 0 → 子进程重新探测(以真实加载结果为准,避免假成功)
355
+ task.phase = 'verifying';
356
+ resetAsrDetection();
357
+ const available = await detectAsrAvailable({ force: true });
358
+
359
+ task.running = false;
360
+ task.done = true;
361
+ task.success = available;
362
+ if (available) task.everSucceeded = true;
363
+ task.phase = 'done';
364
+ task.finishedAt = Date.now();
365
+ if (!available) {
366
+ const reason = getLastAsrProbeError();
367
+ task.error = reason ? `${t('asr.verifyFailed')} - ${reason}` : t('asr.verifyFailed');
368
+ if (reason) {
369
+ task.logTail.push(`[verify] ${reason}`);
370
+ if (task.logTail.length > LOG_TAIL_LIMIT) task.logTail = task.logTail.slice(-LOG_TAIL_LIMIT);
371
+ }
372
+ }
373
+ savePersistedState();
374
+ }
375
+
376
+ /**
377
+ * 执行 npm install(参数为纯静态常量,不含任何用户输入)
378
+ * @returns {Promise<{ success: boolean, error?: string }>}
379
+ */
380
+ function runNpmInstall(task, t) {
381
+ return new Promise((resolvePromise) => {
382
+ const isWin = process.platform === 'win32';
383
+ let cmd;
384
+ try {
385
+ cmd = buildAsrInstallCommand();
386
+ } catch (err) {
387
+ resolvePromise({ success: false, error: t('asr.installFailed', { message: err.message }) });
388
+ return;
389
+ }
390
+
391
+ const npm = spawn(cmd.command, cmd.args, {
392
+ shell: cmd.shell,
393
+ detached: !isWin,
394
+ cwd: cmd.cwd,
395
+ env: { ...process.env },
396
+ windowsHide: true,
397
+ });
398
+ npmChild = npm;
399
+
400
+ const appendLog = (chunk) => {
401
+ for (const line of chunk.toString().split('\n')) {
402
+ const trimmed = line.trim();
403
+ if (trimmed) task.logTail.push(trimmed);
404
+ }
405
+ if (task.logTail.length > LOG_TAIL_LIMIT) {
406
+ task.logTail = task.logTail.slice(-LOG_TAIL_LIMIT);
407
+ }
408
+ };
409
+
410
+ let settled = false;
411
+ let timer = null;
412
+ const finish = (result) => {
413
+ if (settled) return;
414
+ settled = true;
415
+ if (timer) clearTimeout(timer);
416
+ resolvePromise(result);
417
+ };
418
+
419
+ npm.stdout.on('data', appendLog);
420
+ npm.stderr.on('data', appendLog);
421
+ npm.on('error', (err) => {
422
+ if (npmChild === npm) npmChild = null;
423
+ finish({ success: false, error: t('asr.installFailed', { message: err.message }) });
424
+ });
425
+
426
+ timer = setTimeout(() => {
427
+ finish({ success: false, error: t('asr.installTimeout') });
428
+ stopProcessTree(npm, { graceMs: 5000 }).catch(() => {});
429
+ }, INSTALL_TIMEOUT_MS);
430
+ timer.unref();
431
+
432
+ npm.on('close', (code) => {
433
+ if (npmChild === npm) npmChild = null;
434
+ finish(code === 0
435
+ ? { success: true }
436
+ : { success: false, error: t('asr.installFailed', { message: `exit code ${code}` }) });
437
+ });
438
+ });
439
+ }
@@ -0,0 +1,207 @@
1
+ // agent/src/asr/model-catalog.js - 内置推荐模型清单(自动下载的唯一事实来源)
2
+ //
3
+ // 分发走两条腿(两条都要保留,不能二选一):
4
+ // 1. 能访问外网 / 能访问 HF 镜像:配置页一键下载,逐文件拉取后本地生成 manifest.json
5
+ // 2. 完全内网:在能上网的机器上备好同构目录,用「从文件夹导入」或直接拷进 MODELS_DIR
6
+ //
7
+ // 为什么不下官方 .tar.bz2:Node 标准库没有 bzip2 解压能力,为解压引入依赖不值得;
8
+ // HF 仓库里每个文件都能单独 HTTP 取,且实测 Content-Length 与本地已验证文件字节数
9
+ // 完全一致,可直接用内置 sha256 校验。
10
+ //
11
+ // 端点策略:默认 hf-mirror(实测 huggingface.co 国内直连不可达:curl 返回 000);
12
+ // mirrors.json 里 huggingface === 'mirror' 时同样走镜像,AI_HELPER_ASR_HF_ENDPOINT
13
+ // 可显式覆盖(其它地区的部署用它指向官方站点或自建代理)。
14
+ //
15
+ // 安全约束:下载目标 id 只能取自本清单白名单,绝不接受调用方传入的任意字符串,
16
+ // 因此不存在拼路径穿越的入口。
17
+
18
+ import { getHfEndpoint } from '../install-mode.js';
19
+
20
+ // 默认模型下载端点(实测可达;huggingface.co 直连超时)
21
+ const DEFAULT_HF_ENDPOINT = 'https://hf-mirror.com';
22
+
23
+ // manifest 的 schema 版本必须与 model-pack.js 的 MANIFEST_SCHEMA 一致
24
+ const MANIFEST_SCHEMA = 1;
25
+
26
+ /**
27
+ * 推荐模型清单
28
+ *
29
+ * 每个条目的 manifest / sha256 均以本地已跑通的模型包为准(实测转写通过),
30
+ * 不按上游文件目录动态推导——上游新增文件不应该改变我们的加载参数。
31
+ */
32
+ export const MODEL_CATALOG = [
33
+ {
34
+ id: 'sense-voice-zh-en-ja-ko-yue',
35
+ name: 'SenseVoice 中英日韩粤(int8,定稿)',
36
+ kind: 'offline',
37
+ repo: 'csukuangfj/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17',
38
+ description: '松手后整段高精度转写,自动带标点并把数字规整为阿拉伯数字',
39
+ files: [
40
+ {
41
+ name: 'model.int8.onnx',
42
+ size: 239233841,
43
+ sha256: 'c71f0ce00bec95b07744e116345e33d8cbbe08cef896382cf907bf4b51a2cd51',
44
+ },
45
+ {
46
+ name: 'tokens.txt',
47
+ size: 315894,
48
+ sha256: 'f449eb28dc567533d7fa59be34e2abca8784f771850c78a47fb731a31429a1dc',
49
+ },
50
+ ],
51
+ manifest: {
52
+ schema: MANIFEST_SCHEMA,
53
+ engine: 'sherpa-onnx',
54
+ id: 'sense-voice-zh-en-ja-ko-yue',
55
+ name: 'SenseVoice 中英日韩粤(int8,定稿)',
56
+ kind: 'offline',
57
+ arch: 'senseVoice',
58
+ language: 'zh-en',
59
+ senseVoiceLanguage: 'auto',
60
+ decodingMethod: 'greedy_search',
61
+ sampleRate: 16000,
62
+ modelFile: 'model.int8.onnx',
63
+ tokensFile: 'tokens.txt',
64
+ files: ['model.int8.onnx', 'tokens.txt'],
65
+ sha256: {
66
+ 'model.int8.onnx': 'c71f0ce00bec95b07744e116345e33d8cbbe08cef896382cf907bf4b51a2cd51',
67
+ 'tokens.txt': 'f449eb28dc567533d7fa59be34e2abca8784f771850c78a47fb731a31429a1dc',
68
+ },
69
+ },
70
+ },
71
+ {
72
+ id: 'streaming-zipformer-bilingual-zh-en',
73
+ name: 'Streaming Zipformer 中英双语(int8,流式草稿)',
74
+ kind: 'online',
75
+ repo: 'csukuangfj/sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20',
76
+ description: '边说边出草稿;松手后仍由定稿模型覆盖。small 版质量不足,不推荐',
77
+ files: [
78
+ {
79
+ name: 'encoder-epoch-99-avg-1.int8.onnx',
80
+ size: 181895032,
81
+ sha256: '8fa764187a261844f859d7143ebaa563af5d10adfece4c18a8f414c88cba2a9b',
82
+ },
83
+ {
84
+ name: 'decoder-epoch-99-avg-1.int8.onnx',
85
+ size: 13091040,
86
+ sha256: '1a70c593d71e53f023f5f55b0b4cfff5055abb786ee3992e5f63dc2e273cc4fa',
87
+ },
88
+ {
89
+ name: 'joiner-epoch-99-avg-1.int8.onnx',
90
+ size: 3228404,
91
+ sha256: '1ed689c5ed19dbaa725d9d191bb4822b5f4855a39e1ffd28cbc1f340d25b2ee0',
92
+ },
93
+ {
94
+ name: 'tokens.txt',
95
+ size: 56317,
96
+ sha256: 'a8e0e4ec53810e433789b54a5c0134a7eaa2ffca595a6334d54c00da858841d3',
97
+ },
98
+ ],
99
+ manifest: {
100
+ schema: MANIFEST_SCHEMA,
101
+ engine: 'sherpa-onnx',
102
+ id: 'streaming-zipformer-bilingual-zh-en',
103
+ name: 'Streaming Zipformer 中英双语(int8,流式草稿)',
104
+ kind: 'online',
105
+ arch: 'transducer',
106
+ language: 'zh-en',
107
+ sampleRate: 16000,
108
+ encoder: 'encoder-epoch-99-avg-1.int8.onnx',
109
+ decoder: 'decoder-epoch-99-avg-1.int8.onnx',
110
+ joiner: 'joiner-epoch-99-avg-1.int8.onnx',
111
+ tokensFile: 'tokens.txt',
112
+ files: [
113
+ 'encoder-epoch-99-avg-1.int8.onnx',
114
+ 'decoder-epoch-99-avg-1.int8.onnx',
115
+ 'joiner-epoch-99-avg-1.int8.onnx',
116
+ 'tokens.txt',
117
+ ],
118
+ sha256: {
119
+ 'encoder-epoch-99-avg-1.int8.onnx': '8fa764187a261844f859d7143ebaa563af5d10adfece4c18a8f414c88cba2a9b',
120
+ 'decoder-epoch-99-avg-1.int8.onnx': '1a70c593d71e53f023f5f55b0b4cfff5055abb786ee3992e5f63dc2e273cc4fa',
121
+ 'joiner-epoch-99-avg-1.int8.onnx': '1ed689c5ed19dbaa725d9d191bb4822b5f4855a39e1ffd28cbc1f340d25b2ee0',
122
+ 'tokens.txt': 'a8e0e4ec53810e433789b54a5c0134a7eaa2ffca595a6334d54c00da858841d3',
123
+ },
124
+ },
125
+ },
126
+ ];
127
+
128
+ /** 一键下载的默认目标(定稿 + 草稿) */
129
+ export const DEFAULT_DOWNLOAD_IDS = MODEL_CATALOG.map((entry) => entry.id);
130
+
131
+ /**
132
+ * 按 id 取清单条目(白名单查询:非法 id 一律返回 null)
133
+ * @param {string} id
134
+ * @returns {object|null}
135
+ */
136
+ export function getCatalogEntry(id) {
137
+ if (typeof id !== 'string') return null;
138
+ return MODEL_CATALOG.find((entry) => entry.id === id) || null;
139
+ }
140
+
141
+ /**
142
+ * 条目总字节数
143
+ * @param {object} entry
144
+ * @returns {number}
145
+ */
146
+ export function getEntryBytes(entry) {
147
+ return entry.files.reduce((sum, file) => sum + file.size, 0);
148
+ }
149
+
150
+ /**
151
+ * 归一化调用方传入的 id 列表
152
+ *
153
+ * 只保留清单内存在的 id(去重、保持清单顺序);传空/非法一律回落为默认组合,
154
+ * 这样接口既支持「只下其中一个」,也不会被任意字符串利用。
155
+ * @param {unknown} ids
156
+ * @returns {object[]}
157
+ */
158
+ export function resolveCatalogEntries(ids) {
159
+ if (!Array.isArray(ids) || ids.length === 0) {
160
+ return MODEL_CATALOG.filter((entry) => DEFAULT_DOWNLOAD_IDS.includes(entry.id));
161
+ }
162
+ const wanted = new Set(ids.filter((id) => typeof id === 'string'));
163
+ return MODEL_CATALOG.filter((entry) => wanted.has(entry.id));
164
+ }
165
+
166
+ /**
167
+ * 当前模型下载端点(不带结尾斜杠)
168
+ * @returns {string}
169
+ */
170
+ export function resolveHfEndpoint() {
171
+ const override = process.env.AI_HELPER_ASR_HF_ENDPOINT;
172
+ if (typeof override === 'string' && /^https?:\/\//i.test(override.trim())) {
173
+ return override.trim().replace(/\/+$/, '');
174
+ }
175
+ const fromMirrors = getHfEndpoint();
176
+ const base = fromMirrors || DEFAULT_HF_ENDPOINT;
177
+ return base.replace(/\/+$/, '');
178
+ }
179
+
180
+ /**
181
+ * 单个文件的下载地址
182
+ * @param {string} repo HF 仓库(org/name)
183
+ * @param {string} fileName
184
+ * @returns {string}
185
+ */
186
+ export function buildFileUrl(repo, fileName) {
187
+ return `${resolveHfEndpoint()}/${repo}/resolve/main/${encodeURIComponent(fileName)}`;
188
+ }
189
+
190
+ /**
191
+ * 对外展示用的清单视图(隐藏 repo 内部细节,保留体积/说明/是否已安装)
192
+ * @param {{ installedIds?: Set<string>|string[] }} [opts]
193
+ * @returns {object[]}
194
+ */
195
+ export function toPublicCatalog(opts = {}) {
196
+ const installed = opts.installedIds instanceof Set
197
+ ? opts.installedIds
198
+ : new Set(Array.isArray(opts.installedIds) ? opts.installedIds : []);
199
+ return MODEL_CATALOG.map((entry) => ({
200
+ id: entry.id,
201
+ name: entry.name,
202
+ kind: entry.kind,
203
+ description: entry.description,
204
+ totalBytes: getEntryBytes(entry),
205
+ installed: installed.has(entry.id),
206
+ }));
207
+ }