ai-helper-agent 2.4.7 → 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 (46) 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-Wu4cQfi-.js → agent-store-D0oEv0PW.js} +1 -1
  5. package/dist/assets/background.js +5 -5
  6. package/dist/assets/chat-export-MTTSSIwM.js +37 -0
  7. package/dist/assets/content.js +41 -30
  8. package/dist/assets/{dist-LQPh1k0y.js → dist-BUuoW_84.js} +1 -1
  9. package/dist/assets/i18n-Br_sF5pb.js +49 -0
  10. package/dist/assets/{markdown-render-DsMFYJ7j.js → markdown-render-Dq5F_dqP.js} +2 -2
  11. package/dist/assets/{model-profiles-DWY7gG5H.js → model-profiles-BdQaV4EZ.js} +1 -1
  12. package/dist/assets/{options-Dir2xv8X.css → options-JtYgxtsc.css} +1 -1
  13. package/dist/assets/options.js +297 -238
  14. package/dist/assets/{page-snapshot-renderer-C0SlAjsY.js → page-snapshot-renderer-Cl0qk7U1.js} +1 -1
  15. package/dist/assets/{session-store-Dtfmjrt-.js → session-store-KkrAlIc6.js} +3 -3
  16. package/dist/assets/side_panel.css +1 -1
  17. package/dist/assets/side_panel.js +400 -400
  18. package/dist/assets/{utils-S-aJS9gf.js → utils-ZJjxSlg_.js} +1 -1
  19. package/dist/assets/{version-CcGQQNRR.js → version-C0CY79zF.js} +1 -1
  20. package/dist/manifest.json +1 -1
  21. package/dist/offscreen/offscreen.js +9 -9
  22. package/dist/options.html +38 -4
  23. package/dist/side_panel.html +25 -7
  24. package/dist/voice-capture-worklet.js +47 -0
  25. package/package.json +4 -1
  26. package/src/asr/config.js +155 -0
  27. package/src/asr/detect.js +215 -0
  28. package/src/asr/engine.js +347 -0
  29. package/src/asr/install.js +439 -0
  30. package/src/asr/model-catalog.js +207 -0
  31. package/src/asr/model-download.js +461 -0
  32. package/src/asr/model-pack.js +398 -0
  33. package/src/asr/offline-pool.js +283 -0
  34. package/src/asr/offline-worker.js +97 -0
  35. package/src/asr/probe-child.mjs +31 -0
  36. package/src/asr/routes.js +385 -0
  37. package/src/asr/session.js +435 -0
  38. package/src/asr/transcribe.js +310 -0
  39. package/src/directory-picker.js +549 -70
  40. package/src/locales/cli.json +26 -0
  41. package/src/locales/en.json +22 -1
  42. package/src/locales/zh.json +22 -1
  43. package/src/rag/install.js +60 -2
  44. package/src/server.js +168 -7
  45. package/dist/assets/chat-export-DYpi1VYc.js +0 -37
  46. package/dist/assets/i18n-DkQH7l0R.js +0 -49
@@ -0,0 +1,435 @@
1
+ // agent/src/asr/session.js - 流式识别会话(WS /ws/asr/:sessionId)
2
+ //
3
+ // 协议(客户端 → 服务端):
4
+ // - 二进制帧:PCM16LE / 单声道 / 16kHz(每帧 100ms 左右)
5
+ // - JSON 帧:{type:'start', language?} / {type:'stop'} / {type:'cancel'}
6
+ // 服务端 → 客户端:
7
+ // - {type:'ready', draft, finalize} 会话就绪(draft=false 表示没有流式模型,只等 stop 定稿)
8
+ // - {type:'partial', text} 流式草稿(节流 150ms)
9
+ // - {type:'endpoint', text} 检测到句尾(草稿已提交为稳定片段)
10
+ // - {type:'final', text, fallback} 定稿(fallback=true 表示退化为流式文本)
11
+ // - {type:'error', code, error} busy / model_missing / internal / rss_pressure
12
+ //
13
+ // 资源回收:连接关闭(未 stop)、空闲 30s、总时长 5min、并发超限 —— 全部收敛到 release()。
14
+ //
15
+ // stop 定稿是异步的:offline 推理跑在 worker 线程(见 offline-pool.js),会话在发起定稿的
16
+ // 那一刻就 release(并发名额、流式资源立即归还),final 帧等 worker 回来再补发。
17
+
18
+ import {
19
+ MAX_SESSIONS,
20
+ SESSION_IDLE_MS,
21
+ MAX_RECORDING_MS,
22
+ RSS_LIMIT_BYTES,
23
+ } from './config.js';
24
+ import { tidyJoin, tidyChineseSpacing, stripSenseVoiceTags } from './transcribe.js';
25
+ import { getOnlineRecognizer as defaultGetOnline } from './engine.js';
26
+ import { runOfflineTask } from './offline-pool.js';
27
+
28
+ // 草稿推送节流(150ms:肉眼连贯且不会把 WS 打满)
29
+ const PARTIAL_THROTTLE_MS = 150;
30
+
31
+ // 单帧最大字节数(10s @16k mono PCM16 = 320KB;超过视为异常客户端)
32
+ const MAX_FRAME_BYTES = 320 * 1024;
33
+
34
+ /**
35
+ * PCM16LE Buffer → Float32Array(-1..1)
36
+ * @param {Buffer} buf
37
+ * @returns {Float32Array}
38
+ */
39
+ export function pcm16ToFloat32(buf) {
40
+ const count = Math.floor(buf.length / 2);
41
+ const out = new Float32Array(count);
42
+ for (let i = 0; i < count; i++) {
43
+ out[i] = buf.readInt16LE(i * 2) / 32768;
44
+ }
45
+ return out;
46
+ }
47
+
48
+ /**
49
+ * 创建会话管理器(deps 可注入,便于单测)
50
+ * @param {{
51
+ * getModels: () => { online: object|null, offline: object|null, vad: object|null },
52
+ * getIdleUnloadMs?: () => number,
53
+ * getOnlineRecognizer?: Function,
54
+ * getOfflineRecognizer?: Function,
55
+ * getVad?: Function,
56
+ * transcribe?: Function,
57
+ * offlineTimeoutMs?: number,
58
+ * maxSessions?: number,
59
+ * now?: () => number,
60
+ * }} deps
61
+ * @returns {object}
62
+ */
63
+ export function createAsrSessionManager(deps) {
64
+ const sessions = new Map();
65
+ const now = deps.now || (() => Date.now());
66
+ const maxSessions = Number.isFinite(deps.maxSessions) && deps.maxSessions > 0
67
+ ? deps.maxSessions
68
+ : MAX_SESSIONS;
69
+ const getIdleUnloadMs = deps.getIdleUnloadMs || (() => 0);
70
+ // 默认走 worker 线程(不阻塞事件循环);单测注入同步/异步实现,返回 Promise 或值都可
71
+ const transcribe = deps.transcribe || ((samples, opts) => runOfflineTask({
72
+ kind: 'samples',
73
+ samples,
74
+ opts,
75
+ idleMs: getIdleUnloadMs(),
76
+ timeoutMs: deps.offlineTimeoutMs,
77
+ modelId: opts && opts.offlineModel ? opts.offlineModel.id : undefined,
78
+ onLog: deps.onLog,
79
+ }));
80
+
81
+ /**
82
+ * 发送 JSON 帧(连接已断时静默忽略)
83
+ */
84
+ function send(session, payload) {
85
+ const ws = session.ws;
86
+ if (!ws || ws.readyState !== 1) return;
87
+ try {
88
+ ws.send(JSON.stringify(payload));
89
+ } catch {
90
+ // 发送失败说明连接已坏,交给 close 事件回收
91
+ }
92
+ }
93
+
94
+ /**
95
+ * 释放会话占用的全部资源(幂等)
96
+ */
97
+ function release(session) {
98
+ if (!session || session.released) return;
99
+ session.released = true;
100
+ if (session.idleTimer) { clearTimeout(session.idleTimer); session.idleTimer = null; }
101
+ if (session.maxTimer) { clearTimeout(session.maxTimer); session.maxTimer = null; }
102
+ if (session.onlineStream && typeof session.onlineStream.free === 'function') {
103
+ try { session.onlineStream.free(); } catch { /* 原生释放失败忽略 */ }
104
+ }
105
+ session.onlineStream = null;
106
+ session.chunks = [];
107
+ sessions.delete(session.id);
108
+ }
109
+
110
+ /**
111
+ * 重置空闲计时(每帧/每条控制消息都调)
112
+ */
113
+ function touch(session) {
114
+ session.lastActivityAt = now();
115
+ if (session.idleTimer) clearTimeout(session.idleTimer);
116
+ session.idleTimer = setTimeout(() => {
117
+ // 空闲超时:静默收敛(客户端可能已崩,不依赖它发 cancel)
118
+ send(session, { type: 'error', code: 'idle_timeout', error: 'session idle timeout' });
119
+ release(session);
120
+ try { session.ws.close(); } catch { /* 忽略 */ }
121
+ }, SESSION_IDLE_MS);
122
+ if (typeof session.idleTimer.unref === 'function') session.idleTimer.unref();
123
+ }
124
+
125
+ /**
126
+ * 建流(失败不抛出:draft=false,客户端退化为「松手整段定稿」)
127
+ */
128
+ function ensureOnline(session) {
129
+ if (session.onlineReady) return true;
130
+ session.onlineReady = true;
131
+ const models = deps.getModels();
132
+ session.models = models;
133
+ if (!models.online) return false;
134
+ try {
135
+ const rec = (deps.getOnlineRecognizer || defaultGetOnline)(models.online, { idleUnloadMs: getIdleUnloadMs() });
136
+ session.onlineRecognizer = rec;
137
+ session.onlineStream = rec.createStream();
138
+ return true;
139
+ } catch (err) {
140
+ session.onlineRecognizer = null;
141
+ session.onlineStream = null;
142
+ deps.onError?.('online_init_failed', err);
143
+ return false;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * 解码当前流并推送草稿(节流)
149
+ */
150
+ function pumpPartial(session, force = false) {
151
+ const rec = session.onlineRecognizer;
152
+ const stream = session.onlineStream;
153
+ if (!rec || !stream) return;
154
+
155
+ while (typeof rec.isReady === 'function' && rec.isReady(stream)) {
156
+ rec.decode(stream);
157
+ }
158
+
159
+ let text = '';
160
+ try {
161
+ const result = rec.getResult(stream);
162
+ text = tidyChineseSpacing(stripSenseVoiceTags(result && result.text ? result.text : ''));
163
+ } catch {
164
+ return;
165
+ }
166
+
167
+ // 即使本次被节流也要更新 currentText:stop 时若退化为流式文本,
168
+ // 取到的必须是「已解码到的最新文本」,而不是上一次推送的旧值(否则丢掉尾部)。
169
+ // 去重靠 lastSentText(真正推送过的文本),与 currentText 分开。
170
+ if (text && text !== session.currentText) session.currentText = text;
171
+
172
+ const t = now();
173
+ if (!force && t - session.lastPartialAt < PARTIAL_THROTTLE_MS) return;
174
+ if (!text || text === session.lastSentText) return;
175
+ session.lastPartialAt = t;
176
+ session.lastSentText = text;
177
+
178
+ send(session, { type: 'partial', text: tidyJoin([session.committedText, text]) });
179
+ }
180
+
181
+ /**
182
+ * 句子结束:把当前草稿提交为稳定片段并重置流
183
+ */
184
+ function handleEndpoint(session) {
185
+ const rec = session.onlineRecognizer;
186
+ const stream = session.onlineStream;
187
+ if (!rec || !stream) return;
188
+ let text = '';
189
+ try {
190
+ const result = rec.getResult(stream);
191
+ text = tidyChineseSpacing(stripSenseVoiceTags(result && result.text ? result.text : ''));
192
+ } catch {
193
+ text = '';
194
+ }
195
+ if (text) {
196
+ session.committedText = tidyJoin([session.committedText, text]);
197
+ send(session, { type: 'endpoint', text: session.committedText });
198
+ }
199
+ session.currentText = '';
200
+ session.lastSentText = '';
201
+ try { rec.reset(stream); } catch { /* 版本差异:重置失败仍可继续累积 */ }
202
+ }
203
+
204
+ /**
205
+ * 处理 stop:优先 offline 定稿,必要时退回流式文本
206
+ *
207
+ * 同步段先把整段波形与草稿取走,异步段只等 worker 结果 —— 调用方可以立刻 release,
208
+ * 把并发名额与流式资源还给下一次录音(一次定稿可能几百毫秒到数十秒)。
209
+ * @returns {Promise<void>} 定稿帧发出(或放弃)后 resolve
210
+ */
211
+ function finalize(session) {
212
+ const models = session.models || deps.getModels();
213
+ const samples = concatChunks(session.chunks);
214
+ session.chunks = [];
215
+
216
+ const draftText = tidyJoin([session.committedText, session.currentText]);
217
+ const finishWith = (text, fallback) => send(session, { type: 'final', text, fallback });
218
+
219
+ if (!models.offline) {
220
+ finishWith(draftText, true);
221
+ return Promise.resolve();
222
+ }
223
+
224
+ // RSS 保护:接近阈值时不做 offline 定稿(避免 OOM 拖垮整个代理)
225
+ const rss = typeof process.memoryUsage === 'function' ? process.memoryUsage().rss : 0;
226
+ if (rss > RSS_LIMIT_BYTES) {
227
+ deps.onLog?.('asr_offline_skipped', { reason: 'rss_pressure', rss });
228
+ finishWith(draftText, true);
229
+ return Promise.resolve();
230
+ }
231
+
232
+ if (samples.length === 0) {
233
+ finishWith(draftText, !draftText);
234
+ return Promise.resolve();
235
+ }
236
+
237
+ // Promise.resolve().then 包一层:注入的同步实现抛错也走同一条回退路径
238
+ return Promise.resolve()
239
+ .then(() => transcribe(samples, {
240
+ offlineModel: models.offline,
241
+ vadModel: models.vad || null,
242
+ idleUnloadMs: getIdleUnloadMs(),
243
+ language: session.language,
244
+ }))
245
+ .then((result) => {
246
+ finishWith((result && result.text) || draftText, false);
247
+ }, (err) => {
248
+ deps.onError?.('offline_finalize_failed', err);
249
+ finishWith(draftText, true);
250
+ });
251
+ }
252
+
253
+ /**
254
+ * 处理一条控制消息
255
+ */
256
+ function handleControl(session, message) {
257
+ const type = message && message.type;
258
+
259
+ if (type === 'start') {
260
+ if (typeof message.language === 'string') session.language = message.language;
261
+ const draft = ensureOnline(session);
262
+ send(session, { type: 'ready', draft, finalize: Boolean(session.models.offline) });
263
+ return;
264
+ }
265
+
266
+ if (type === 'stop') {
267
+ if (session.finishing) return;
268
+ session.finishing = true;
269
+ // 定稿是异步的:先发起(同步段已取走波形与草稿),立刻释放名额,再等结果补发 final
270
+ const done = finalize(session);
271
+ release(session);
272
+ const close = () => { try { session.ws.close(); } catch { /* 忽略 */ } };
273
+ done.then(close, close);
274
+ return;
275
+ }
276
+
277
+ if (type === 'cancel') {
278
+ release(session);
279
+ try { session.ws.close(); } catch { /* 忽略 */ }
280
+ return;
281
+ }
282
+
283
+ // 未知控制帧:忽略(向前兼容)
284
+ }
285
+
286
+ /**
287
+ * 处理二进制音频帧
288
+ */
289
+ function handleAudio(session, chunk) {
290
+ if (!Buffer.isBuffer(chunk) || chunk.length === 0) return;
291
+ if (chunk.length > MAX_FRAME_BYTES) {
292
+ send(session, { type: 'error', code: 'frame_too_large', error: `frame > ${MAX_FRAME_BYTES} bytes` });
293
+ return;
294
+ }
295
+ touch(session);
296
+ if (!session.onlineReady) ensureOnline(session);
297
+
298
+ const samples = pcm16ToFloat32(chunk);
299
+ if (samples.length === 0) return;
300
+ session.wavSamples += samples.length;
301
+
302
+ // 保留整段波形用于 stop 时 offline 定稿(5min @16k = 4.8M float ≈ 19MB,可接受)
303
+ session.chunks.push(samples);
304
+
305
+ if (session.onlineStream && session.onlineRecognizer) {
306
+ try {
307
+ session.onlineStream.acceptWaveform({ sampleRate: 16000, samples });
308
+ } catch (err) {
309
+ deps.onError?.('accept_waveform_failed', err);
310
+ session.onlineStream = null;
311
+ session.onlineRecognizer = null;
312
+ }
313
+ if (session.onlineStream) {
314
+ pumpPartial(session);
315
+ if (typeof session.onlineRecognizer.isEndpoint === 'function') {
316
+ let endpoint = false;
317
+ try { endpoint = session.onlineRecognizer.isEndpoint(session.onlineStream) === true; } catch { endpoint = false; }
318
+ if (endpoint) handleEndpoint(session);
319
+ }
320
+ }
321
+ }
322
+ }
323
+
324
+ /**
325
+ * 接收一个新连接
326
+ * @param {import('ws').WebSocket} ws
327
+ * @param {string} id
328
+ * @returns {boolean} false = 并发超限,已拒绝
329
+ */
330
+ function attach(ws, id, options = {}) {
331
+ if (sessions.size >= maxSessions) {
332
+ try {
333
+ if (ws.readyState === 1) {
334
+ ws.send(JSON.stringify({ type: 'error', code: 'busy', error: 'another ASR session is active' }));
335
+ }
336
+ ws.close();
337
+ } catch { /* 忽略 */ }
338
+ return false;
339
+ }
340
+
341
+ const session = {
342
+ id,
343
+ ws,
344
+ language: typeof options.language === 'string' ? options.language : 'auto',
345
+ onlineReady: false,
346
+ onlineRecognizer: null,
347
+ onlineStream: null,
348
+ models: null,
349
+ chunks: [],
350
+ wavSamples: 0,
351
+ committedText: '',
352
+ currentText: '',
353
+ lastSentText: '',
354
+ lastPartialAt: 0,
355
+ lastActivityAt: now(),
356
+ createdAt: now(),
357
+ finishing: false,
358
+ released: false,
359
+ idleTimer: null,
360
+ maxTimer: null,
361
+ };
362
+ sessions.set(id, session);
363
+ touch(session);
364
+
365
+ // 总时长上限:到时自动定稿并结束(长按不现实,5 分钟已是单次输入的合理上限)
366
+ session.maxTimer = setTimeout(() => {
367
+ send(session, { type: 'error', code: 'max_duration', error: 'recording length limit reached' });
368
+ session.finishing = true;
369
+ let done;
370
+ try { done = finalize(session); } catch { done = Promise.resolve(); }
371
+ release(session);
372
+ const close = () => { try { ws.close(); } catch { /* 忽略 */ } };
373
+ done.then(close, close);
374
+ }, MAX_RECORDING_MS);
375
+ if (typeof session.maxTimer.unref === 'function') session.maxTimer.unref();
376
+
377
+ ws.on('message', (data, isBinary) => {
378
+ if (session.released) return;
379
+ if (isBinary) {
380
+ handleAudio(session, Buffer.isBuffer(data) ? data : Buffer.from(data));
381
+ return;
382
+ }
383
+ touch(session);
384
+ let message = null;
385
+ try { message = JSON.parse(data.toString()); } catch { return; }
386
+ handleControl(session, message);
387
+ });
388
+
389
+ ws.on('close', () => {
390
+ // 未走 stop 就断开(关面板/切标签页):直接释放,不产出 final
391
+ if (!session.finishing) {
392
+ deps.onLog?.('asr_session_closed', { id, samples: session.wavSamples });
393
+ }
394
+ release(session);
395
+ });
396
+
397
+ ws.on('error', () => release(session));
398
+
399
+ return true;
400
+ }
401
+
402
+ return {
403
+ attach,
404
+ release,
405
+ /** 当前活跃会话数(测试/状态接口用) */
406
+ activeCount: () => sessions.size,
407
+ /** 主动关闭全部会话(停服路径) */
408
+ closeAll: () => {
409
+ for (const session of Array.from(sessions.values())) {
410
+ send(session, { type: 'error', code: 'server_shutdown', error: 'agent is shutting down' });
411
+ release(session);
412
+ try { session.ws.close(); } catch { /* 忽略 */ }
413
+ }
414
+ },
415
+ _sessions: sessions,
416
+ };
417
+ }
418
+
419
+ /**
420
+ * 拼接 Float32 分片
421
+ * @param {Float32Array[]} chunks
422
+ * @returns {Float32Array}
423
+ */
424
+ function concatChunks(chunks) {
425
+ if (!Array.isArray(chunks) || chunks.length === 0) return new Float32Array(0);
426
+ let total = 0;
427
+ for (const c of chunks) total += c.length;
428
+ const out = new Float32Array(total);
429
+ let offset = 0;
430
+ for (const c of chunks) {
431
+ out.set(c, offset);
432
+ offset += c.length;
433
+ }
434
+ return out;
435
+ }