ai-helper-agent 2.4.8 → 2.5.1

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 (97) 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/dist/_locales/en/messages.json +11 -0
  20. package/dist/dist/_locales/zh_CN/messages.json +11 -0
  21. package/dist/dist/assets/__vite-browser-external-CM3Eme-n.js +1 -0
  22. package/dist/dist/assets/agent-store-D0oEv0PW.js +1 -0
  23. package/dist/dist/assets/background.js +451 -0
  24. package/dist/dist/assets/chat-export-7wjGjcA8.js +37 -0
  25. package/dist/dist/assets/chunk-CMxvf4Kt.js +1 -0
  26. package/dist/dist/assets/content.js +985 -0
  27. package/dist/dist/assets/dist-BUuoW_84.js +24 -0
  28. package/dist/dist/assets/dist-DuuG_8Br.js +133 -0
  29. package/dist/dist/assets/i18n-Br_sF5pb.js +49 -0
  30. package/dist/dist/assets/jszip.min-DO6SOhXU.js +2 -0
  31. package/dist/dist/assets/lib-YwkWjNcC.js +220 -0
  32. package/dist/dist/assets/markdown-render-lSSxW953.js +63 -0
  33. package/dist/dist/assets/marked.min.js-D2rXgLAQ.js +56 -0
  34. package/dist/dist/assets/marked.min.js-loader-tKH5SQVQ.js +13 -0
  35. package/dist/dist/assets/model-profiles-BdQaV4EZ.js +24 -0
  36. package/dist/dist/assets/network-scope-CNRYXk74.js +1 -0
  37. package/dist/dist/assets/options-JtYgxtsc.css +1 -0
  38. package/dist/dist/assets/options.js +859 -0
  39. package/dist/dist/assets/page-snapshot-renderer-Cl0qk7U1.js +3 -0
  40. package/dist/dist/assets/pdf-DnVqBaAN.js +6 -0
  41. package/dist/dist/assets/session-store-KkrAlIc6.js +81 -0
  42. package/dist/dist/assets/side_panel.css +1 -0
  43. package/dist/dist/assets/side_panel.js +2595 -0
  44. package/dist/dist/assets/theme-BRAX5X2F.css +1 -0
  45. package/dist/dist/assets/theme-CLwYsx9o.js +1 -0
  46. package/dist/dist/assets/utils-ZJjxSlg_.js +112 -0
  47. package/dist/dist/assets/version-C7x4HYX1.js +1 -0
  48. package/dist/dist/assets/xlsx-DGkz7cnk.js +105 -0
  49. package/dist/dist/icons/README.md +11 -0
  50. package/dist/dist/icons/design-philosophy.md +41 -0
  51. package/dist/dist/icons/icon128.png +0 -0
  52. package/dist/dist/icons/icon128.svg +68 -0
  53. package/dist/dist/icons/icon16.png +0 -0
  54. package/dist/dist/icons/icon16.svg +32 -0
  55. package/dist/dist/icons/icon48.png +0 -0
  56. package/dist/dist/icons/icon48.svg +56 -0
  57. package/dist/dist/libs/github-markdown-light.min.css +8 -0
  58. package/dist/dist/libs/html2canvas.min.js +20 -0
  59. package/dist/dist/libs/jspdf.min.js +398 -0
  60. package/dist/dist/libs/marked.min.js +69 -0
  61. package/dist/dist/libs/mermaid.min.js +2024 -0
  62. package/dist/dist/libs/pdf.worker.min.js +22 -0
  63. package/dist/dist/libs/qrcode.min.js +7 -0
  64. package/dist/dist/manifest.json +94 -0
  65. package/dist/dist/offscreen/offscreen.html +11 -0
  66. package/dist/dist/offscreen/offscreen.js +49 -0
  67. package/dist/dist/options.html +1091 -0
  68. package/dist/dist/service-worker-loader.js +1 -0
  69. package/dist/dist/side_panel.html +1357 -0
  70. package/dist/dist/styles/styles.css +262 -0
  71. package/dist/dist/voice-capture-worklet.js +47 -0
  72. package/dist/manifest.json +1 -1
  73. package/dist/offscreen/offscreen.js +8 -8
  74. package/dist/options.html +38 -4
  75. package/dist/side_panel.html +25 -7
  76. package/dist/voice-capture-worklet.js +47 -0
  77. package/package.json +4 -1
  78. package/src/asr/config.js +155 -0
  79. package/src/asr/detect.js +215 -0
  80. package/src/asr/engine.js +347 -0
  81. package/src/asr/install.js +439 -0
  82. package/src/asr/model-catalog.js +207 -0
  83. package/src/asr/model-download.js +461 -0
  84. package/src/asr/model-pack.js +398 -0
  85. package/src/asr/offline-pool.js +283 -0
  86. package/src/asr/offline-worker.js +97 -0
  87. package/src/asr/probe-child.mjs +31 -0
  88. package/src/asr/routes.js +385 -0
  89. package/src/asr/session.js +435 -0
  90. package/src/asr/transcribe.js +310 -0
  91. package/src/directory-picker.js +157 -45
  92. package/src/locales/cli.json +26 -0
  93. package/src/locales/en.json +22 -1
  94. package/src/locales/zh.json +22 -1
  95. package/src/rag/install.js +60 -2
  96. package/src/server.js +136 -2
  97. package/dist/assets/i18n-DBVIgrwQ.js +0 -49
@@ -0,0 +1,310 @@
1
+ // agent/src/asr/transcribe.js - 整段音频 → 文本(WAV 解析 + 重采样 + VAD 切段 + 定稿识别)
2
+ //
3
+ // 输入约定:PCM16 / 单声道 / 常见采样率(8k/16k/44.1k/48k)的 WAV。
4
+ // 非 16k 一律线性插值重采样(语音 fbank 特征对重采样质量不敏感,线性足够且零依赖)。
5
+ //
6
+ // 为什么按 VAD 切段再逐段识别:SenseVoice 单次可处理较长音频,但长句一次性喂入会
7
+ // 让中间静音稀释注意力、且失败即全损。切段并行度不追求(单用户本机 CPU 独占),
8
+ // 但"某段失败不拖垮整段"必须做到。
9
+
10
+ import { getOfflineRecognizer, getVad } from './engine.js';
11
+
12
+ // 引擎期望采样率
13
+ const TARGET_SAMPLE_RATE = 16000;
14
+
15
+ // 单段最长时长(VAD 的 maxSpeechDuration 之外的兜底,防止极端参数下无限长)
16
+ const MAX_SEGMENT_SECONDS = 30;
17
+
18
+ // VAD 窗口(silero v5 要求 512 @16k)
19
+ const VAD_WINDOW = 512;
20
+
21
+ /**
22
+ * 解析 WAV(仅支持 PCM/IEEE-float 的基础形态;返回空 samples 表示不可识别)
23
+ * @param {Buffer} buffer
24
+ * @returns {{ sampleRate: number, channels: number, bitsPerSample: number, float: boolean, samples: Float32Array }|null}
25
+ */
26
+ export function parseWav(buffer) {
27
+ if (!Buffer.isBuffer(buffer) || buffer.length < 44) return null;
28
+ if (buffer.toString('ascii', 0, 4) !== 'RIFF' || buffer.toString('ascii', 8, 12) !== 'WAVE') return null;
29
+
30
+ let offset = 12;
31
+ let fmt = null;
32
+ let dataStart = -1;
33
+ let dataLength = 0;
34
+
35
+ while (offset + 8 <= buffer.length) {
36
+ const id = buffer.toString('ascii', offset, offset + 4);
37
+ const size = buffer.readUInt32LE(offset + 4);
38
+ const body = offset + 8;
39
+ if (id === 'fmt ') {
40
+ if (body + 16 > buffer.length) return null;
41
+ const audioFormat = buffer.readUInt16LE(body);
42
+ const channels = buffer.readUInt16LE(body + 2);
43
+ const sampleRate = buffer.readUInt32LE(body + 4);
44
+ const bitsPerSample = buffer.readUInt16LE(body + 14);
45
+ fmt = { audioFormat, channels, sampleRate, bitsPerSample };
46
+ } else if (id === 'data') {
47
+ dataStart = body;
48
+ // 部分录音器写 data 长度为 0/0xFFFFFFFF(流式未回填),按实际剩余长度处理
49
+ dataLength = size > 0 && body + size <= buffer.length ? size : buffer.length - body;
50
+ break;
51
+ }
52
+ // chunk 按 2 字节对齐
53
+ offset = body + size + (size % 2);
54
+ }
55
+
56
+ if (!fmt || dataStart < 0) return null;
57
+ const { audioFormat, channels, sampleRate, bitsPerSample } = fmt;
58
+ if (!(sampleRate > 0) || !(channels > 0)) return null;
59
+ // 1 = PCM integer,3 = IEEE float
60
+ const isFloat = audioFormat === 3;
61
+ const isPcm = audioFormat === 1;
62
+ if (!isFloat && !isPcm) return null;
63
+ if (![8, 16, 24, 32].includes(bitsPerSample)) return null;
64
+
65
+ const bytesPerSample = bitsPerSample / 8;
66
+ const frameBytes = bytesPerSample * channels;
67
+ if (frameBytes <= 0) return null;
68
+ const frames = Math.floor(dataLength / frameBytes);
69
+ if (frames <= 0) return null;
70
+
71
+ const samples = new Float32Array(frames);
72
+ for (let i = 0; i < frames; i++) {
73
+ // 多声道只取第一声道(麦克风录音恒为 mono;立体声按左声道处理)
74
+ const p = dataStart + i * frameBytes;
75
+ let value;
76
+ if (isFloat) {
77
+ value = bitsPerSample === 32 ? buffer.readFloatLE(p) : 0;
78
+ } else if (bitsPerSample === 16) {
79
+ value = buffer.readInt16LE(p) / 32768;
80
+ } else if (bitsPerSample === 8) {
81
+ // 8bit PCM 是无符号、中心 128
82
+ value = (buffer.readUInt8(p) - 128) / 128;
83
+ } else if (bitsPerSample === 24) {
84
+ const b0 = buffer.readUInt8(p);
85
+ const b1 = buffer.readUInt8(p + 1);
86
+ const b2 = buffer.readInt8(p + 2);
87
+ value = ((b2 << 16) | (b1 << 8) | b0) / 8388608;
88
+ } else {
89
+ value = buffer.readInt32LE(p) / 2147483648;
90
+ }
91
+ samples[i] = Number.isFinite(value) ? value : 0;
92
+ }
93
+
94
+ return { sampleRate, channels, bitsPerSample, float: isFloat, samples };
95
+ }
96
+
97
+ /**
98
+ * 线性插值重采样到 16k
99
+ * @param {Float32Array} samples
100
+ * @param {number} fromRate
101
+ * @param {number} [toRate]
102
+ * @returns {Float32Array}
103
+ */
104
+ export function resampleTo16k(samples, fromRate, toRate = TARGET_SAMPLE_RATE) {
105
+ if (!(fromRate > 0) || !samples || samples.length === 0) return new Float32Array(0);
106
+ if (fromRate === toRate) return samples;
107
+ const ratio = fromRate / toRate;
108
+ const outLength = Math.max(1, Math.floor(samples.length / ratio));
109
+ const out = new Float32Array(outLength);
110
+ for (let i = 0; i < outLength; i++) {
111
+ const pos = i * ratio;
112
+ const left = Math.floor(pos);
113
+ const right = Math.min(left + 1, samples.length - 1);
114
+ const frac = pos - left;
115
+ out[i] = samples[left] * (1 - frac) + samples[right] * frac;
116
+ }
117
+ return out;
118
+ }
119
+
120
+ /**
121
+ * 计算整段音频的峰值(用于"全静音"的快速判定,避免白跑一遍模型)
122
+ * @param {Float32Array} samples
123
+ * @returns {number}
124
+ */
125
+ export function peakAmplitude(samples) {
126
+ let peak = 0;
127
+ for (let i = 0; i < samples.length; i++) {
128
+ const v = Math.abs(samples[i]);
129
+ if (v > peak) peak = v;
130
+ }
131
+ return peak;
132
+ }
133
+
134
+ /**
135
+ * 用 VAD 切段;VAD 不可用时按固定长度切(30s 上限)
136
+ * @param {object|null} vad
137
+ * @param {Float32Array} samples
138
+ * @param {number} sampleRate
139
+ * @returns {Float32Array[]}
140
+ */
141
+ export function splitByVad(vad, samples, sampleRate = TARGET_SAMPLE_RATE) {
142
+ const fixedChunks = () => {
143
+ const maxLen = MAX_SEGMENT_SECONDS * sampleRate;
144
+ const chunks = [];
145
+ for (let start = 0; start < samples.length; start += maxLen) {
146
+ chunks.push(samples.subarray(start, Math.min(start + maxLen, samples.length)));
147
+ }
148
+ return chunks.length > 0 ? chunks : [samples];
149
+ };
150
+
151
+ if (!vad || typeof vad.acceptWaveform !== 'function') return fixedChunks();
152
+
153
+ const segments = [];
154
+ try {
155
+ for (let offset = 0; offset + VAD_WINDOW <= samples.length; offset += VAD_WINDOW) {
156
+ const window = samples.subarray(offset, offset + VAD_WINDOW);
157
+ vad.acceptWaveform(window);
158
+ while (vad.isDetected && vad.isDetected()) {
159
+ const seg = vad.front();
160
+ // sherpa VAD 的 front() 返回 { samples: Float32Array, start: number } 形态
161
+ const data = seg && seg.samples ? seg.samples : seg;
162
+ if (data && data.length > 0) segments.push(data);
163
+ vad.pop();
164
+ }
165
+ }
166
+ // 收尾:把残余语音段取出
167
+ if (typeof vad.flush === 'function') vad.flush();
168
+ while (vad.isDetected && vad.isDetected()) {
169
+ const seg = vad.front();
170
+ const data = seg && seg.samples ? seg.samples : seg;
171
+ if (data && data.length > 0) segments.push(data);
172
+ vad.pop();
173
+ }
174
+ } catch {
175
+ // VAD 行为异常(版本差异):退回固定切分,保证仍能出结果
176
+ return fixedChunks();
177
+ }
178
+
179
+ return segments.length > 0 ? segments : fixedChunks();
180
+ }
181
+
182
+ /**
183
+ * 清掉 SenseVoice 输出的语种/情绪标记(`<|zh|><|NEUTRAL|><|Speech|>`),只留正文
184
+ * @param {string} text
185
+ * @returns {string}
186
+ */
187
+ export function stripSenseVoiceTags(text) {
188
+ return String(text || '')
189
+ .replace(/<\|[^|]*\|>/g, '')
190
+ .replace(/\s+/g, ' ')
191
+ .trim();
192
+ }
193
+
194
+ /**
195
+ * 中文排版收口:去掉中文之间的多余空格(模型常按词输出空格)
196
+ * @param {string} text
197
+ * @returns {string}
198
+ */
199
+ export function tidyChineseSpacing(text) {
200
+ return String(text || '')
201
+ .replace(/([\u4e00-\u9fff])[ \t]+(?=[\u4e00-\u9fff])/g, '$1')
202
+ .replace(/[ \t]+([,。!?;:、)】」』])/g, '$1')
203
+ .replace(/([(【「『])[ \t]+/g, '$1')
204
+ .trim();
205
+ }
206
+
207
+ /**
208
+ * 解码单个语音段
209
+ * @param {object} recognizer
210
+ * @param {Float32Array} samples
211
+ * @param {number} sampleRate
212
+ * @returns {string}
213
+ */
214
+ function decodeSegment(recognizer, samples, sampleRate) {
215
+ const stream = recognizer.createStream();
216
+ stream.acceptWaveform({ sampleRate, samples });
217
+ recognizer.decode(stream);
218
+ const result = typeof recognizer.getResult === 'function'
219
+ ? recognizer.getResult(stream)
220
+ : { text: '' };
221
+ try {
222
+ if (typeof stream.free === 'function') stream.free();
223
+ } catch { /* 忽略释放失败 */ }
224
+ return tidyChineseSpacing(stripSenseVoiceTags(result && result.text ? result.text : ''));
225
+ }
226
+
227
+ /**
228
+ * 整段转写(同步阻塞;调用方负责放在请求处理里等待)
229
+ * @param {Buffer} wavBuffer
230
+ * @param {{ offlineModel: object, vadModel?: object|null, language?: string, idleUnloadMs?: number }} opts
231
+ * @returns {{ text: string, durationMs: number, engineMs: number, segments: number, peak: number }}
232
+ */
233
+ export function transcribeWav(wavBuffer, opts = {}) {
234
+ const startedAt = Date.now();
235
+ const parsed = parseWav(wavBuffer);
236
+ if (!parsed) {
237
+ const err = new Error('unsupported_audio');
238
+ err.code = 'unsupported_audio';
239
+ throw err;
240
+ }
241
+
242
+ const originalDurationMs = Math.round((parsed.samples.length / parsed.sampleRate) * 1000);
243
+ const samples = resampleTo16k(parsed.samples, parsed.sampleRate, TARGET_SAMPLE_RATE);
244
+ const result = transcribeSamples(samples, opts);
245
+ return {
246
+ ...result,
247
+ durationMs: originalDurationMs,
248
+ engineMs: Date.now() - startedAt,
249
+ };
250
+ }
251
+
252
+ /**
253
+ * 对已重采样到 16k 的 Float32 波形做整段定稿识别(WS 会话 stop 路径复用)
254
+ * @param {Float32Array} samples 16k mono
255
+ * @param {{ offlineModel: object, vadModel?: object|null, idleUnloadMs?: number }} opts
256
+ * @returns {{ text: string, segments: number, peak: number }}
257
+ */
258
+ export function transcribeSamples(samples, opts = {}) {
259
+ const src = samples instanceof Float32Array ? samples : new Float32Array(samples || []);
260
+ const peak = peakAmplitude(src);
261
+
262
+ // 全静音:不跑模型,直接回空文本(前端据此提示「未识别到语音」)
263
+ if (peak < 0.003 || src.length < TARGET_SAMPLE_RATE * 0.2) {
264
+ return { text: '', segments: 0, peak };
265
+ }
266
+
267
+ if (!opts.offlineModel) {
268
+ const err = new Error('model_missing');
269
+ err.code = 'model_missing';
270
+ throw err;
271
+ }
272
+
273
+ const recognizer = getOfflineRecognizer(opts.offlineModel, { idleUnloadMs: opts.idleUnloadMs });
274
+ let vad = null;
275
+ if (opts.vadModel) {
276
+ try {
277
+ vad = getVad(opts.vadModel, { idleUnloadMs: opts.idleUnloadMs });
278
+ } catch {
279
+ vad = null; // VAD 加载失败不应让整段转写失败
280
+ }
281
+ }
282
+
283
+ const segments = splitByVad(vad, src, TARGET_SAMPLE_RATE);
284
+ const texts = [];
285
+ for (const seg of segments) {
286
+ const text = decodeSegment(recognizer, seg, TARGET_SAMPLE_RATE);
287
+ if (text) texts.push(text);
288
+ }
289
+
290
+ return { text: tidyJoin(texts), segments: segments.length, peak };
291
+ }
292
+
293
+ /**
294
+ * 拼接多段识别结果:中文片段直接相接,纯英文片段之间补空格
295
+ * @param {string[]} parts
296
+ * @returns {string}
297
+ */
298
+ export function tidyJoin(parts) {
299
+ let out = '';
300
+ for (const raw of parts) {
301
+ const part = raw.trim();
302
+ if (!part) continue;
303
+ if (!out) { out = part; continue; }
304
+ const last = out[out.length - 1];
305
+ const first = part[0];
306
+ const needSpace = /[A-Za-z0-9]/.test(last) && /[A-Za-z0-9]/.test(first);
307
+ out += needSpace ? ` ${part}` : part;
308
+ }
309
+ return tidyChineseSpacing(out);
310
+ }