dsh-sixlayer-memory 2.3.2 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,55 @@
1
1
  # 变更记录 · dsh-sixlayer-memory(六层记忆底座)
2
2
 
3
+ ## 2.5.0 — 2026-12-05
4
+
5
+ 主题:**边说边出字**(微信/搜狗输入法那种流式语音输入)。
6
+
7
+ ### 新增
8
+
9
+ - **本地流式识别**(`lib/memory/stream-asr.js`):sherpa-onnx 离线模型,ffmpeg 采麦克风
10
+ 按 100ms 一块喂进去,增量解码,**字随着说话一段段长出来**,不再等说完。
11
+ - 引擎:`sherpa-onnx-node`(native,装在 `$DSH_HOME/memory-core/runtime/`,不随插件包发布)
12
+ - 模型:`streaming-zh-14M`(zh,52MB 四个 onnx),装在 `$DSH_HOME/memory-core/models/`
13
+ - 热键动作新增 `stream`:按一下开始 + 弹**置顶字幕条**,再按一下结束并把最终文字投进当前会话
14
+ - 实测:3.8 秒语音 → 0.11 秒解码完,逐块输出「帮我 / 帮我看 / 帮我看一下 / …第三关怎么走」
15
+ - **字幕条**(`overlay.ps1`):底部居中的置顶小窗,每 120ms 读一次识别文本,边说边显示;
16
+ 不在插件包里塞 Electron 依赖,用 WPF 一行行刷新
17
+ - 配置 `stream: { model?, runtime?, overlay? }`;`mem_hotkey({action:'stream'})` 一键切换
18
+
19
+ ### 说明
20
+
21
+ - DeepSeek 的 ASR 接口**不支持流式**(官方文档原文),所以"边说边出字"只能走本地引擎;
22
+ 想要云端精度就切 `action:'asr'`,两者随时可换
23
+ - 流式不可用(没装模型/运行时)时只是该动作失败,**不影响记忆主流程**
24
+
25
+ ### 回归
26
+
27
+ - 全量 35 个套件全绿 · 工具 35 个
28
+
29
+ ---
30
+
31
+ ## 2.4.0 — 2026-12-05
32
+
33
+ 主题:**说完直接发出去,不看焦点、不碰剪贴板**。
34
+
35
+ ### 新增
36
+
37
+ - **语音结果直接投递进当前会话**:`agent/pre-step` 时记下活着的 agent,识别完把文字用
38
+ `agent.followup()` 当成一条用户消息送进去——不需要点输入框、不需要光标、不依赖剪贴板。
39
+ 拿不到 agent 或投递失败才回退到"粘到输入框"。
40
+ - 配置 `asr.deliver`:`agent`(默认,直接发)/ `paste`(只粘输入框)
41
+ - 每次投递在审计里记 `op:'voice'` + `delivered: agent|paste|failed`
42
+
43
+ ### 修复
44
+
45
+ - 2.3.2 的 SendKeys 粘贴在部分窗口仍不生效——现在这条路径只是兜底,不再是主路径
46
+
47
+ ### 回归
48
+
49
+ - 全量 35 个套件全绿 · 工具 35 个
50
+
51
+ ---
52
+
3
53
  ## 2.3.2 — 2026-12-05
4
54
 
5
55
  修「识别出来了但没粘进输入框、也没提示音」——两处都是进程环境问题。
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  dsh plugin --profile desktop add dsh-sixlayer-memory
12
12
  ```
13
13
 
14
- **当前版本**:2.3.2 · **35 个工具** · schema v9 · 零外部依赖 · 回归 35 个套件全绿
14
+ **当前版本**:2.5.0 · **35 个工具** · schema v9 · 零外部依赖 · 回归 35 个套件全绿
15
15
 
16
16
  📦 [npm](https://www.npmjs.com/package/dsh-sixlayer-memory) · 🎬 [40 秒介绍视频](media/intro-40s.mp4) · 📝 [变更记录](CHANGELOG.md)
17
17
 
package/lib/index.js CHANGED
@@ -13,12 +13,20 @@ import { fileURLToPath } from 'node:url'
13
13
  import MemoryStore from './memory/store.js'
14
14
  import { buildRegistry } from './memory/tools.js'
15
15
  import { Injector } from './memory/inject.js'
16
- import { attachLifecycle, lifecycleSummary } from './memory/lifecycle.js'
16
+ import { attachLifecycle, lifecycleSummary, resolveMessageFactory } from './memory/lifecycle.js'
17
17
  import { decorateRows, explainRecord } from './memory/explain.js'
18
18
  import { readDetail } from './memory/detail.js'
19
19
  import { createQqBridge } from './memory/qq.js'
20
20
  import { HotkeyListener, resolveHotkeyConfig } from './memory/hotkey.js'
21
- import { VoiceRecorder, beep, loadDeepSeekKey, pasteText, resolveAsrConfig, transcribe, transcribeLocal } from './memory/asr.js'
21
+ import { VoiceRecorder, beep, loadDeepSeekKey, pasteText, resolveAsrConfig, resolveFfmpeg, transcribe, transcribeLocal } from './memory/asr.js'
22
+ import {
23
+ StreamRecognizer,
24
+ loadSherpa,
25
+ resolveModelDir,
26
+ startOverlay,
27
+ stopOverlay,
28
+ writeOverlayText,
29
+ } from './memory/stream-asr.js'
22
30
  import { createApiHandler, ensureApiToken, createApiServer } from './memory/api.js'
23
31
  import { createQqOfficialBridge } from './memory/qq-official.js'
24
32
  import { ingestQqSessions, affectReport } from './memory/affect-events.js'
@@ -203,6 +211,9 @@ export function apply(ctx, config = {}) {
203
211
  })
204
212
  let lastVoice = null
205
213
  let lastHotkeyAt = 0
214
+ // pre-step 时记下活着的 agent:语音识别完直接把文字当消息投进去,不靠剪贴板
215
+ let lastAgent = null
216
+ let lastSessionId = ''
206
217
  const toggleVoice = async () => {
207
218
  // 正在录 → 停 + 转写 + 粘贴
208
219
  if (voice.recording) {
@@ -236,9 +247,32 @@ export function apply(ctx, config = {}) {
236
247
  diag('asr: 转写失败 ' + result.reason)
237
248
  return lastVoice
238
249
  }
239
- const pasted = await pasteText(result.text, { autoEnter: asrConfig.autoEnter })
250
+ // 优先直接把文字当一条用户消息送进当前会话(不看焦点、不用剪贴板);
251
+ // 拿不到 agent 或失败时才退回"粘到输入框"。
252
+ let delivered = 'none'
253
+ const factory = resolveMessageFactory()
254
+ if (asrConfig.deliver !== 'paste' && lastAgent && typeof lastAgent.followup === 'function' && factory) {
255
+ try {
256
+ lastAgent.followup(factory({ content: [{ type: 'text', text: result.text }], source: { kind: 'user' } }))
257
+ delivered = 'agent'
258
+ } catch (error) {
259
+ diag('asr: 直接投递失败(回退粘贴)' + (error?.message ?? error))
260
+ }
261
+ }
262
+ if (delivered === 'none') {
263
+ const pasted = await pasteText(result.text, { autoEnter: asrConfig.autoEnter })
264
+ delivered = pasted.ok ? 'paste' : 'failed'
265
+ }
240
266
  try {
241
- store?.recorder?.record?.({ op: 'voice', via, key_source: source, chars: result.text.length, ms: result.durationMs ?? stopped.ms })
267
+ store?.recorder?.record?.({
268
+ op: 'voice',
269
+ via,
270
+ delivered,
271
+ session: lastSessionId,
272
+ key_source: source,
273
+ chars: result.text.length,
274
+ ms: result.durationMs ?? stopped.ms,
275
+ })
242
276
  } catch {
243
277
  /* 审计失败不影响 */
244
278
  }
@@ -248,8 +282,9 @@ export function apply(ctx, config = {}) {
248
282
  stage: 'done',
249
283
  text: result.text,
250
284
  via,
285
+ delivered,
251
286
  ms: result.durationMs ?? stopped.ms,
252
- pasted: pasted.ok,
287
+ pasted: delivered !== 'failed',
253
288
  file: stopped.file,
254
289
  }
255
290
  return lastVoice
@@ -264,6 +299,81 @@ export function apply(ctx, config = {}) {
264
299
  return lastVoice
265
300
  }
266
301
 
302
+ // 流式识别(边说边出字):本地 sherpa-onnx,模型和运行时都在 ~/.dsh/memory-core 下
303
+ const streamModelDir = resolveModelDir({ name: String(config.stream?.model ?? ''), dataDir })
304
+ const streamSherpa = streamModelDir ? loadSherpa({ runtimeDir: String(config.stream?.runtime ?? '') }) : null
305
+ let overlayChild = null
306
+ let overlayFile = ''
307
+ const streamer = new StreamRecognizer({
308
+ modelDir: streamModelDir,
309
+ sherpa: streamSherpa,
310
+ ffmpegPath: resolveFfmpeg(),
311
+ device: asrConfig.device,
312
+ logger: (m) => diag('stream: ' + m),
313
+ onPartial: (text) => {
314
+ if (overlayFile) writeOverlayText(overlayFile, text)
315
+ },
316
+ })
317
+ diag(
318
+ 'stream: ' +
319
+ (streamer.available ? `可用(模型 ${streamModelDir})` : `不可用(模型=${streamModelDir || '无'} / 运行时=${streamSherpa ? '有' : '无'})`),
320
+ )
321
+
322
+ /** 流式:按一下开始(弹字幕条),再按一下结束并投递。 */
323
+ const toggleStream = async () => {
324
+ if (streamer.running) {
325
+ const r = await streamer.stop()
326
+ stopOverlay(overlayChild, overlayFile)
327
+ overlayChild = null
328
+ overlayFile = ''
329
+ beep({ freq: 520, ms: 90 })
330
+ if (!r.ok || !r.text) {
331
+ lastVoice = { at: new Date().toISOString(), ok: false, stage: 'transcribe', reason: r.reason ?? '没有识别到内容', via: 'stream' }
332
+ return lastVoice
333
+ }
334
+ return deliverVoiceText(r.text, { via: 'stream', ms: r.ms })
335
+ }
336
+ const s = await streamer.start()
337
+ if (!s.ok) {
338
+ beep({ freq: 300, ms: 120 })
339
+ lastVoice = { at: new Date().toISOString(), ok: false, stage: 'record', reason: s.reason, via: 'stream' }
340
+ return lastVoice
341
+ }
342
+ beep({ freq: 880, ms: 70 })
343
+ if (config.stream?.overlay !== false) {
344
+ overlayFile = path.join(dataDir, 'voice', 'live.txt')
345
+ fs.mkdirSync(path.dirname(overlayFile), { recursive: true })
346
+ overlayChild = startOverlay({ file: overlayFile, title: '正在听…再说一次按键结束', logger: (m) => diag('stream: ' + m) })
347
+ }
348
+ lastVoice = { at: new Date().toISOString(), ok: true, stage: 'recording', via: 'stream' }
349
+ return lastVoice
350
+ }
351
+
352
+ /** 把识别出的文本投进当前会话(优先 agent,失败退回粘贴)。 */
353
+ const deliverVoiceText = async (text, { via = 'asr', ms = 0 } = {}) => {
354
+ let delivered = 'none'
355
+ const factory = resolveMessageFactory()
356
+ if (asrConfig.deliver !== 'paste' && lastAgent && typeof lastAgent.followup === 'function' && factory) {
357
+ try {
358
+ lastAgent.followup(factory({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
359
+ delivered = 'agent'
360
+ } catch (error) {
361
+ diag('voice: 直接投递失败(回退粘贴)' + (error?.message ?? error))
362
+ }
363
+ }
364
+ if (delivered === 'none') {
365
+ const pasted = await pasteText(text, { autoEnter: asrConfig.autoEnter })
366
+ delivered = pasted.ok ? 'paste' : 'failed'
367
+ }
368
+ try {
369
+ store?.recorder?.record?.({ op: 'voice', via, delivered, session: lastSessionId, chars: text.length, ms })
370
+ } catch {
371
+ /* 审计失败不影响 */
372
+ }
373
+ lastVoice = { at: new Date().toISOString(), ok: true, stage: 'done', text, via, delivered, ms, pasted: delivered !== 'failed' }
374
+ return lastVoice
375
+ }
376
+
267
377
  // 全局热键:按一个键唤起系统语音听写(Win+H)。默认关闭,开了才注册。
268
378
  const hotkeyConfig = resolveHotkeyConfig(config.hotkey, dataDir)
269
379
  const hotkey = new HotkeyListener({
@@ -281,6 +391,11 @@ export function apply(ctx, config = {}) {
281
391
  if (now - lastHotkeyAt < 400) return
282
392
  lastHotkeyAt = now
283
393
  toggleVoice().catch((error) => diag('asr: 热键流程异常 ' + (error?.message ?? error)))
394
+ } else if (hotkeyConfig.action === 'stream') {
395
+ const now = Date.now()
396
+ if (now - lastHotkeyAt < 400) return
397
+ lastHotkeyAt = now
398
+ toggleStream().catch((error) => diag('stream: 热键流程异常 ' + (error?.message ?? error)))
284
399
  }
285
400
  } else if (ev.type === 'conflict') {
286
401
  logger?.warn?.(`memory-core: 全局热键 ${ev.hotkey} 被占用,换一个键或关掉这个功能`)
@@ -562,6 +677,10 @@ export function apply(ctx, config = {}) {
562
677
  store,
563
678
  config: config.lifecycle ?? {},
564
679
  diag,
680
+ onAgent: (agent, sessionId) => {
681
+ if (agent) lastAgent = agent
682
+ if (sessionId) lastSessionId = sessionId
683
+ },
565
684
  })
566
685
  return () => {
567
686
  try {
package/lib/memory/asr.js CHANGED
@@ -256,6 +256,8 @@ export function resolveAsrConfig(config = {}, dataDir = '') {
256
256
  localCommand: String(pick('localCommand', '')),
257
257
  device: String(pick('device', '')),
258
258
  autoEnter: Boolean(pick('autoEnter', false)),
259
+ // agent = 直接把文字当消息送进当前会话(不看焦点);paste = 粘到输入框
260
+ deliver: String(pick('deliver', 'agent')) === 'paste' ? 'paste' : 'agent',
259
261
  apiKey: config?.apiKey ? String(config.apiKey) : '',
260
262
  }
261
263
  }
@@ -263,7 +265,7 @@ export function resolveAsrConfig(config = {}, dataDir = '') {
263
265
  /** 写覆盖文件(工具改配置时用)。apiKey 不进文件。 */
264
266
  export function saveAsrConfig(dataDir, patch = {}) {
265
267
  const next = { ...readAsrOverrides(dataDir) }
266
- for (const k of ['enabled', 'baseUrl', 'localCommand', 'device', 'autoEnter']) {
268
+ for (const k of ['enabled', 'baseUrl', 'localCommand', 'device', 'autoEnter', 'deliver']) {
267
269
  if (patch[k] !== undefined) next[k] = patch[k]
268
270
  }
269
271
  const file = asrOverridesPath(dataDir)
@@ -257,7 +257,7 @@ export function resolveHotkeyConfig(config = {}, dataDir = '') {
257
257
  const stored = readOverrides(dataDir)
258
258
  const pick = (k, fallback) => (config && config[k] !== undefined ? config[k] : stored[k] !== undefined ? stored[k] : fallback)
259
259
  const action = String(pick('action', 'dictation'))
260
- const ALLOWED = new Set(['dictation', 'asr', 'none'])
260
+ const ALLOWED = new Set(['dictation', 'asr', 'stream', 'none'])
261
261
  return {
262
262
  enabled: Boolean(pick('enabled', false)),
263
263
  key: String(pick('key', DEFAULT_HOTKEY)),
@@ -237,7 +237,7 @@ function deepFreeze(value) {
237
237
  * @param {any} ctx 宿主上下文
238
238
  * @param {{store:any, config?:any, diag?:(m:string)=>void, createUserMessage?:Function}} options
239
239
  */
240
- export function attachLifecycle(ctx, { store, config, diag = () => {}, createUserMessage } = {}) {
240
+ export function attachLifecycle(ctx, { store, config, diag = () => {}, createUserMessage, onAgent = null } = {}) {
241
241
  const cfg = normalizeLifecycle(config)
242
242
  if (!store) return () => {}
243
243
  if (cfg.enabled === false) {
@@ -311,6 +311,13 @@ export function attachLifecycle(ctx, { store, config, diag = () => {}, createUse
311
311
  if (!query) return decision
312
312
 
313
313
  const sessionId = String(payload?.agent?.session?.id ?? '')
314
+ // 把当前活着的 agent 交出去:语音输入要能"直接把文字当一条消息发进去",
315
+ // 而不是靠模拟 Ctrl+V 去猜用户焦点在哪个窗口。
316
+ try {
317
+ onAgent?.(payload?.agent ?? null, sessionId)
318
+ } catch (error) {
319
+ diag('lifecycle: onAgent 回调出错 ' + (error?.message ?? error))
320
+ }
314
321
  const hash = sha256(query)
315
322
  const now = Date.now()
316
323
  const cooldown = Number(cfg.recall.cooldownMs ?? 30_000)
@@ -0,0 +1,57 @@
1
+ # overlay.ps1 -- always-on-top subtitle bar for streaming speech recognition.
2
+ # Polls a UTF-8 text file and shows its content. Exit when the file disappears.
3
+ # Usage: powershell -STA -NoProfile -ExecutionPolicy Bypass -File overlay.ps1 -Path <file> -Title <text>
4
+ param(
5
+ [Parameter(Mandatory = $true)][string]$Path,
6
+ [string]$Title = ''
7
+ )
8
+
9
+ $ErrorActionPreference = 'Stop'
10
+ Add-Type -AssemblyName PresentationFramework
11
+ Add-Type -AssemblyName PresentationCore
12
+ Add-Type -AssemblyName WindowsBase
13
+
14
+ $w = New-Object System.Windows.Window
15
+ $w.WindowStyle = 'None'
16
+ $w.AllowsTransparency = $true
17
+ $w.Background = [System.Windows.Media.BrushConverter]::new().ConvertFromString('#E6141A22')
18
+ $w.Topmost = $true
19
+ $w.ShowInTaskbar = $false
20
+ $w.ResizeMode = 'NoResize'
21
+ $w.Width = 940
22
+ $w.Height = 96
23
+ $screen = [System.Windows.SystemParameters]::PrimaryScreenWidth
24
+ $w.Left = ($screen - 940) / 2
25
+ $w.Top = [System.Windows.SystemParameters]::PrimaryScreenHeight - 220
26
+
27
+ $border = New-Object System.Windows.Controls.Border
28
+ $border.CornerRadius = [System.Windows.CornerRadius]::new(14)
29
+ $border.Padding = [System.Windows.Thickness]::new(20, 10, 20, 10)
30
+ $border.Background = [System.Windows.Media.BrushConverter]::new().ConvertFromString('#F21B2330')
31
+
32
+ $stack = New-Object System.Windows.Controls.StackPanel
33
+ $tip = New-Object System.Windows.Controls.TextBlock
34
+ $tip.Text = $Title
35
+ $tip.FontSize = 12
36
+ $tip.Foreground = [System.Windows.Media.BrushConverter]::new().ConvertFromString('#88FFFFFF')
37
+ $tip.Margin = [System.Windows.Thickness]::new(0, 0, 0, 4)
38
+ $tb = New-Object System.Windows.Controls.TextBlock
39
+ $tb.FontSize = 24
40
+ $tb.TextWrapping = 'Wrap'
41
+ $tb.Foreground = [System.Windows.Media.BrushConverter]::new().ConvertFromString('#FFFFFFFF')
42
+ $stack.Children.Add($tip) | Out-Null
43
+ $stack.Children.Add($tb) | Out-Null
44
+ $border.Child = $stack
45
+ $w.Content = $border
46
+
47
+ $timer = New-Object System.Windows.Threading.DispatcherTimer
48
+ $timer.Interval = [TimeSpan]::FromMilliseconds(120)
49
+ $timer.Add_Tick({
50
+ if (-not (Test-Path -LiteralPath $Path)) { $timer.Stop(); $w.Close(); return }
51
+ try {
52
+ $t = [System.IO.File]::ReadAllText($Path, [System.Text.Encoding]::UTF8)
53
+ if ($t -ne $tb.Text) { $tb.Text = $t }
54
+ } catch { }
55
+ })
56
+ $timer.Start()
57
+ $w.ShowDialog() | Out-Null
@@ -0,0 +1,234 @@
1
+ /**
2
+ * stream-asr.js —— 流式语音识别:边说边出字。
3
+ *
4
+ * 和 asr.js 的区别:
5
+ * asr.js 说完 → 整段上传 DeepSeek → 一次性返回(接口不支持流式)
6
+ * stream-asr 边说 → 每 100ms 一块喂本地模型 → 增量解码 → 文字一段段长出来
7
+ *
8
+ * 引擎是 sherpa-onnx(离线、CPU、零网络),模型放在 `$DSH_HOME/memory-core/models/`,
9
+ * npm 依赖装在 `$DSH_HOME/memory-core/runtime/`(不随插件包发布,避免 100MB+ 塞进 npm)。
10
+ *
11
+ * 全部失败都只是"流式不可用",退回整段识别,绝不影响记忆主流程。
12
+ */
13
+ import { spawn } from 'node:child_process'
14
+ import fs from 'node:fs'
15
+ import path from 'node:path'
16
+ import { createRequire } from 'node:module'
17
+ import { fileURLToPath } from 'node:url'
18
+
19
+ const require_ = createRequire(fileURLToPath(import.meta.url))
20
+
21
+ export const DEFAULT_MODEL = 'streaming-zh-14M'
22
+
23
+ /** 找模型目录:配置 > $DSH_HOME/memory-core/models/<name> */
24
+ export function resolveModelDir({ name = DEFAULT_MODEL, dataDir = '', env = process.env } = {}) {
25
+ const home = env.DSH_HOME || path.join(env.USERPROFILE || env.HOME || '', '.dsh')
26
+ const candidates = []
27
+ if (name && path.isAbsolute(name)) candidates.push(name)
28
+ candidates.push(path.join(home, 'memory-core', 'models', name))
29
+ if (dataDir) candidates.push(path.join(dataDir, 'models', name))
30
+ for (const dir of candidates) {
31
+ if (fs.existsSync(path.join(dir, 'tokens.txt')) && fs.existsSync(path.join(dir, 'encoder-epoch-99-avg-1.onnx'))) return dir
32
+ }
33
+ return ''
34
+ }
35
+
36
+ /** 按绝对路径加载 native 模块(不在插件包依赖里)。 */
37
+ export function loadSherpa({ runtimeDir = '', env = process.env } = {}) {
38
+ const home = env.DSH_HOME || path.join(env.USERPROFILE || env.HOME || '', '.dsh')
39
+ const dirs = [
40
+ env.MEMORY_SHERPA_PATH,
41
+ runtimeDir,
42
+ path.join(home, 'memory-core', 'runtime', 'node_modules', 'sherpa-onnx-node'),
43
+ ].filter(Boolean)
44
+ for (const dir of dirs) {
45
+ try {
46
+ return require_.resolve(dir) && require_(dir)
47
+ } catch {
48
+ /* 换下一个 */
49
+ }
50
+ }
51
+ return null
52
+ }
53
+
54
+ /**
55
+ * 流式字幕条:一个置顶的小窗,实时显示"正在说的字"。
56
+ * 返回句柄,stopOverlay 时关掉;窗口自己也会在字幕文件消失时退出。
57
+ */
58
+ export function startOverlay({ file, title = '正在听…', logger = null } = {}) {
59
+ const script = path.join(path.dirname(fileURLToPath(import.meta.url)), 'overlay.ps1')
60
+ if (!fs.existsSync(script)) return null
61
+ try {
62
+ fs.writeFileSync(file, '', 'utf8')
63
+ const child = spawn('powershell.exe', ['-STA', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script, '-Path', file, '-Title', title], {
64
+ windowsHide: true,
65
+ stdio: 'ignore',
66
+ })
67
+ child.on('error', (error) => logger?.(`字幕条启动失败:${error.message}`))
68
+ return child
69
+ } catch (error) {
70
+ logger?.(`字幕条启动失败:${error.message}`)
71
+ return null
72
+ }
73
+ }
74
+
75
+ export function stopOverlay(child, file) {
76
+ try {
77
+ if (file) fs.rmSync(file, { force: true })
78
+ } catch {
79
+ /* 忽略 */
80
+ }
81
+ try {
82
+ child?.kill()
83
+ } catch {
84
+ /* 忽略 */
85
+ }
86
+ }
87
+
88
+ /** 把当前识别文本写进字幕文件(窗口每 120ms 读一次)。 */
89
+ export function writeOverlayText(file, text) {
90
+ try {
91
+ fs.writeFileSync(file, String(text ?? ''), 'utf8')
92
+ } catch {
93
+ /* 忽略 */
94
+ }
95
+ }
96
+ export class StreamRecognizer {
97
+ constructor({ modelDir = '', sherpa = null, ffmpegPath = 'ffmpeg.exe', device = '', logger = null, onPartial = null } = {}) {
98
+ this.modelDir = modelDir
99
+ this.sherpa = sherpa
100
+ this.ffmpegPath = ffmpegPath
101
+ this.device = device
102
+ this.log = logger ?? (() => {})
103
+ this.onPartial = onPartial
104
+ this.child = null
105
+ this.stream = null
106
+ this.recognizer = null
107
+ this.text = ''
108
+ this.startedAt = 0
109
+ }
110
+
111
+ get running() {
112
+ return Boolean(this.child)
113
+ }
114
+
115
+ get available() {
116
+ return Boolean(this.sherpa && this.modelDir)
117
+ }
118
+
119
+ /** 懒创建识别器(第一次用才加载模型,约 0.3-1 秒)。 */
120
+ _ensureRecognizer() {
121
+ if (this.recognizer) return this.recognizer
122
+ const p = (f) => path.join(this.modelDir, f)
123
+ this.recognizer = new this.sherpa.OnlineRecognizer({
124
+ featConfig: { sampleRate: 16000, featureDim: 80 },
125
+ modelConfig: {
126
+ transducer: {
127
+ encoder: p('encoder-epoch-99-avg-1.onnx'),
128
+ decoder: p('decoder-epoch-99-avg-1.onnx'),
129
+ joiner: p('joiner-epoch-99-avg-1.onnx'),
130
+ },
131
+ tokens: p('tokens.txt'),
132
+ numThreads: 2,
133
+ provider: 'cpu',
134
+ debug: 0,
135
+ },
136
+ decodingMethod: 'greedy_search',
137
+ })
138
+ return this.recognizer
139
+ }
140
+
141
+ /** @returns {Promise<{ok:boolean, reason?:string}>} */
142
+ async start() {
143
+ if (this.child) return { ok: false, reason: '已经在流式识别' }
144
+ if (!this.available) return { ok: false, reason: '流式模型或 sherpa 运行时没装' }
145
+ try {
146
+ this._ensureRecognizer()
147
+ } catch (error) {
148
+ return { ok: false, reason: `模型加载失败:${error?.message ?? error}` }
149
+ }
150
+ this.stream = this.recognizer.createStream()
151
+ this.text = ''
152
+ this.startedAt = Date.now()
153
+
154
+ const args = ['-hide_banner', '-loglevel', 'error', '-f', 'dshow', '-i', `audio=${this.device}`, '-ac', '1', '-ar', '16000', '-f', 's16le', '-']
155
+ let child
156
+ try {
157
+ child = spawn(this.ffmpegPath, args, { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] })
158
+ } catch (error) {
159
+ return { ok: false, reason: error.message }
160
+ }
161
+ this.child = child
162
+
163
+ let carry = Buffer.alloc(0)
164
+ child.stdout.on('data', (chunk) => {
165
+ carry = Buffer.concat([carry, chunk])
166
+ const FRAME = 3200 // 100ms of s16le @16k
167
+ while (carry.length >= FRAME) {
168
+ const buf = carry.subarray(0, FRAME)
169
+ carry = carry.subarray(FRAME)
170
+ this._feed(buf)
171
+ }
172
+ })
173
+ child.stderr.on('data', (c) => this.log(String(c).trim().slice(0, 160)))
174
+ child.on('exit', (code) => {
175
+ if (this.child === child) this.child = null
176
+ this.log(`ffmpeg 退出 code=${code}`)
177
+ })
178
+ return { ok: true }
179
+ }
180
+
181
+ _feed(buf) {
182
+ try {
183
+ const samples = new Float32Array(buf.length / 2)
184
+ for (let i = 0; i < samples.length; i += 1) samples[i] = buf.readInt16LE(i * 2) / 32768
185
+ this.stream.acceptWaveform({ samples, sampleRate: 16000 })
186
+ while (this.recognizer.isReady(this.stream)) this.recognizer.decode(this.stream)
187
+ const text = this.recognizer.getResult(this.stream).text ?? ''
188
+ if (text && text !== this.text) {
189
+ this.text = text
190
+ try {
191
+ this.onPartial?.(text)
192
+ } catch {
193
+ /* 回调失败不影响识别 */
194
+ }
195
+ }
196
+ } catch (error) {
197
+ this.log(`喂音频失败:${error?.message ?? error}`)
198
+ }
199
+ }
200
+
201
+ /** 停止并给出最终文本。 @returns {Promise<{ok:boolean, text:string, ms:number, reason?:string}>} */
202
+ async stop() {
203
+ const child = this.child
204
+ if (!child) return { ok: false, text: '', ms: 0, reason: '没有在流式识别' }
205
+ this.child = null
206
+ const ms = Date.now() - this.startedAt
207
+ await new Promise((resolve) => {
208
+ const done = () => resolve()
209
+ child.once('exit', done)
210
+ try {
211
+ child.stdin.write('q\n')
212
+ } catch {
213
+ /* 忽略 */
214
+ }
215
+ setTimeout(() => {
216
+ try {
217
+ child.kill()
218
+ } catch {
219
+ /* 已退出 */
220
+ }
221
+ resolve()
222
+ }, 800)
223
+ })
224
+ try {
225
+ this.stream.inputFinished()
226
+ while (this.recognizer.isReady(this.stream)) this.recognizer.decode(this.stream)
227
+ const tail = this.recognizer.getResult(this.stream).text
228
+ if (tail) this.text = tail
229
+ } catch (error) {
230
+ this.log(`收尾失败:${error?.message ?? error}`)
231
+ }
232
+ return { ok: Boolean(this.text), text: this.text, ms }
233
+ }
234
+ }
@@ -764,8 +764,9 @@ export function buildRegistry(store, host) {
764
764
  key: { type: 'string', description: '热键,如 Alt+V / Ctrl+Shift+F9;必须带修饰键' },
765
765
  action: {
766
766
  type: 'string',
767
- enum: ['dictation', 'asr', 'none'],
768
- description: 'dictation=唤起系统听写;asr=录音并调 DeepSeek 识别后粘贴;none=只记录',
767
+ enum: ['dictation', 'asr', 'stream', 'none'],
768
+ description:
769
+ 'dictation=唤起系统听写(边说边出字,但打到光标处);asr=录音后调 DeepSeek 识别再投递(质量好,说完才出);stream=本地流式识别(边说边出字 + 直接投递,需装模型);none=只记录',
769
770
  },
770
771
  enabled: { type: 'boolean', description: '开或关' },
771
772
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sixlayer-memory",
3
- "version": "2.3.2",
3
+ "version": "2.5.0",
4
4
  "private": false,
5
5
  "description": "DSH 工作台:六层记忆底座(每轮自动召回 + 候选沉淀 + 闸门审计)+ 零件化,支持 QQ 随身使用。",
6
6
  "type": "module",
@@ -32,7 +32,8 @@
32
32
  "docs/DETAIL.zh.md",
33
33
  "docs/preview.svg",
34
34
  "docs/生命周期-自动召回与候选.md",
35
- "LICENSE"
35
+ "LICENSE",
36
+ "lib/memory/overlay.ps1"
36
37
  ],
37
38
  "dsh": {
38
39
  "bundle": {