dsh-sixlayer-memory 2.5.4 → 2.6.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,54 @@
1
1
  # 变更记录 · dsh-sixlayer-memory(六层记忆底座)
2
2
 
3
+ ## 2.6.0 — 2026-12-05
4
+
5
+ 主题:**说话时自动带上屏幕截图**——打游戏问"这里怎么走",它得先看得见。
6
+
7
+ ### 新增
8
+
9
+ - **截屏随语音一起投递**(`lib/memory/screen.js`):语音识别完成后用 ffmpeg `gdigrab` 抓一张当前屏幕,
10
+ 缩到 1280 宽 JPEG(约 150KB),作为 `{type:'image', source:{type:'base64'}}` 和文字一起塞进消息。
11
+ 打游戏问路、看报错弹窗这类问题,终于不用先描述画面。
12
+ - 配置 `screen.enabled`(默认 true)、`screen.width`
13
+ - 截图失败就退回纯文本,不影响消息本身
14
+ - 审计里多记 `shot_bytes`
15
+ - **兜底消息构造器**(`fallbackUserMessageWithContent`):`dsh-llm` 解析不到时(日志里的 `factory=fallback`)
16
+ 也能构造带图片消息,而不是永远退回"粘剪贴板"
17
+
18
+ ### 回归
19
+
20
+ - 真机截屏:157KB JPEG,画面正常
21
+ - 全量 35 个套件全绿,工具 35 个
22
+
23
+ ---
24
+
25
+ ## 2.5.5 — 2026-12-05
26
+
27
+ 修「长按热键导致整个 App 重启」。
28
+
29
+ ### 根因
30
+
31
+ `hotkey.js` 里的孤儿进程清理用的是 **`execFileSync`**——同步阻塞宿主事件循环,最长 8 秒。
32
+ 它挂在"启动热键"这条路径上,而长按会反复触发启动:
33
+
34
+ ```
35
+ 长按 → 连发 PRESS → 反复 start() → 反复 execFileSync(每次卡 1-8 秒)
36
+ → 宿主事件循环被占死 → Electron 父进程判定无响应 → 杀掉宿主 → App 重启
37
+ ```
38
+
39
+ ### 修复
40
+
41
+ - 清理改成**异步 spawn**,只在 `REGFAIL`(热键被占用)这条失败路上跑,跑完重试一次;
42
+ 正常启动路径**不再有任何同步阻塞**
43
+ - 热键切换加**重入锁**(`streamBusy`):上一次 start/stop 没结束,后面的按键直接忽略
44
+ - 去抖 400ms → **700ms**:长按时最多每 0.7 秒切换一次,不再抖动
45
+
46
+ ### 回归
47
+
48
+ - 全量 35 个套件全绿
49
+
50
+ ---
51
+
3
52
  ## 2.5.4 — 2026-12-05
4
53
 
5
54
  修「字幕条弹出来了但一个字都没有」,并把字幕条改成**透明**。
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  dsh plugin --profile desktop add dsh-sixlayer-memory
12
12
  ```
13
13
 
14
- **当前版本**:2.5.4 · **35 个工具** · schema v9 · 零外部依赖 · 回归 35 个套件全绿
14
+ **当前版本**:2.6.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,7 +13,7 @@ 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, resolveMessageFactory } from './memory/lifecycle.js'
16
+ import { attachLifecycle, lifecycleSummary, fallbackUserMessageWithContent, 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'
@@ -27,6 +27,7 @@ import {
27
27
  stopOverlay,
28
28
  writeOverlayText,
29
29
  } from './memory/stream-asr.js'
30
+ import { captureScreen, toImagePart } from './memory/screen.js'
30
31
  import { createApiHandler, ensureApiToken, createApiServer } from './memory/api.js'
31
32
  import { createQqOfficialBridge } from './memory/qq-official.js'
32
33
  import { ingestQqSessions, affectReport } from './memory/affect-events.js'
@@ -251,7 +252,7 @@ export function apply(ctx, config = {}) {
251
252
  // 拿不到 agent 或失败时才退回"粘到输入框"。
252
253
  let delivered = 'none'
253
254
  const factory = resolveMessageFactory()
254
- if (asrConfig.deliver !== 'paste' && lastAgent && typeof lastAgent.followup === 'function' && factory) {
255
+ if (asrConfig.deliver !== 'paste' && lastAgent && typeof lastAgent.followup === 'function') {
255
256
  try {
256
257
  lastAgent.followup(factory({ content: [{ type: 'text', text: result.text }], source: { kind: 'user' } }))
257
258
  delivered = 'agent'
@@ -324,8 +325,16 @@ export function apply(ctx, config = {}) {
324
325
  )
325
326
 
326
327
  /** 流式:按一下开始(弹字幕条),再按一下结束并投递。 */
328
+ let streamBusy = false
327
329
  const toggleStream = async () => {
328
- if (streamer.running) {
330
+ // 长按会连发,且 start/stop 里有异步等待;重入会把识别器/ffmpeg 弄成半死状态。
331
+ if (streamBusy) {
332
+ diag('stream: 上一次切换还没结束,忽略这次')
333
+ return lastVoice
334
+ }
335
+ streamBusy = true
336
+ try {
337
+ if (streamer.running) {
329
338
  const r = await streamer.stop()
330
339
  stopOverlay(overlayChild, overlayFile)
331
340
  overlayChild = null
@@ -351,18 +360,52 @@ export function apply(ctx, config = {}) {
351
360
  }
352
361
  lastVoice = { at: new Date().toISOString(), ok: true, stage: 'recording', via: 'stream' }
353
362
  return lastVoice
363
+ } finally {
364
+ streamBusy = false
365
+ }
354
366
  }
355
367
 
356
368
  /** 把识别出的文本投进当前会话(优先 agent,失败退回粘贴)。 */
357
369
  const deliverVoiceText = async (text, { via = 'asr', ms = 0 } = {}) => {
358
370
  let delivered = 'none'
359
- const factory = resolveMessageFactory()
371
+ const dshFactory = resolveMessageFactory()
372
+ // dsh-llm 解析不到时(宿主 profile 结构变了就会这样)用同形的兜底消息构造器,
373
+ // 不再因为 factory 是 null 就永远退回"粘剪贴板"。
374
+ const buildUserMessage = (content) =>
375
+ dshFactory ? dshFactory({ content, source: { kind: 'user' } }) : fallbackUserMessageWithContent({ content, kind: 'user' })
376
+ // 打游戏问"这里怎么走"时,光有文字没用——顺手截一张当前屏幕一起发过去。
377
+ let shot = { ok: false }
378
+ if (config.screen?.enabled !== false) {
379
+ shot = await captureScreen({
380
+ ffmpegPath: resolveFfmpeg(),
381
+ outDir: path.join(dataDir, 'voice'),
382
+ width: Number(config.screen?.width ?? 1280),
383
+ })
384
+ if (!shot.ok) diag('screen: 截图失败 ' + (shot.reason ?? ''))
385
+ }
360
386
  if (asrConfig.deliver !== 'paste' && lastAgent && typeof lastAgent.followup === 'function' && factory) {
387
+ const build = (withImage) => {
388
+ const content = [{ type: 'text', text }]
389
+ if (withImage && shot.ok) {
390
+ try {
391
+ content.push(toImagePart(shot.file, shot.mediaType))
392
+ } catch (error) {
393
+ diag('screen: 图片编码失败 ' + (error?.message ?? error))
394
+ }
395
+ }
396
+ return buildUserMessage(content)
397
+ }
361
398
  try {
362
- lastAgent.followup(factory({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
363
- delivered = 'agent'
399
+ lastAgent.followup(build(true))
400
+ delivered = shot.ok ? 'agent+shot' : 'agent'
364
401
  } catch (error) {
365
- diag('voice: 直接投递失败(回退粘贴)' + (error?.message ?? error))
402
+ diag('voice: 带图投递失败,退回纯文本:' + (error?.message ?? error))
403
+ try {
404
+ lastAgent.followup(build(false))
405
+ delivered = 'agent'
406
+ } catch (error2) {
407
+ diag('voice: 直接投递失败(回退粘贴)' + (error2?.message ?? error2))
408
+ }
366
409
  }
367
410
  }
368
411
  if (delivered === 'none') {
@@ -370,11 +413,29 @@ export function apply(ctx, config = {}) {
370
413
  delivered = pasted.ok ? 'paste' : 'failed'
371
414
  }
372
415
  try {
373
- store?.recorder?.record?.({ op: 'voice', via, delivered, session: lastSessionId, chars: text.length, ms })
416
+ store?.recorder?.record?.({
417
+ op: 'voice',
418
+ via,
419
+ delivered,
420
+ session: lastSessionId,
421
+ chars: text.length,
422
+ ms,
423
+ shot_bytes: shot.ok ? shot.bytes : 0,
424
+ })
374
425
  } catch {
375
426
  /* 审计失败不影响 */
376
427
  }
377
- lastVoice = { at: new Date().toISOString(), ok: true, stage: 'done', text, via, delivered, ms, pasted: delivered !== 'failed' }
428
+ lastVoice = {
429
+ at: new Date().toISOString(),
430
+ ok: true,
431
+ stage: 'done',
432
+ text,
433
+ via,
434
+ delivered,
435
+ ms,
436
+ shot: shot.ok ? shot.file : '',
437
+ pasted: delivered !== 'failed',
438
+ }
378
439
  return lastVoice
379
440
  }
380
441
 
@@ -392,12 +453,12 @@ export function apply(ctx, config = {}) {
392
453
  // 去抖:按住键会连发,只认第一次。
393
454
  if (hotkeyConfig.action === 'asr') {
394
455
  const now = Date.now()
395
- if (now - lastHotkeyAt < 400) return
456
+ if (now - lastHotkeyAt < 700) return
396
457
  lastHotkeyAt = now
397
458
  toggleVoice().catch((error) => diag('asr: 热键流程异常 ' + (error?.message ?? error)))
398
459
  } else if (hotkeyConfig.action === 'stream') {
399
460
  const now = Date.now()
400
- if (now - lastHotkeyAt < 400) return
461
+ if (now - lastHotkeyAt < 700) return
401
462
  lastHotkeyAt = now
402
463
  toggleStream().catch((error) => diag('stream: 热键流程异常 ' + (error?.message ?? error)))
403
464
  }
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * @module memory/hotkey
14
14
  */
15
- import { spawn, execFileSync } from 'node:child_process'
15
+ import { spawn } from 'node:child_process'
16
16
  import fs from 'node:fs'
17
17
  import path from 'node:path'
18
18
  import { fileURLToPath } from 'node:url'
@@ -102,10 +102,11 @@ export class HotkeyListener {
102
102
  return { ok: true, hotkey: this.parsed.label, action: this.action }
103
103
  }
104
104
 
105
- _spawn() {
106
- // 清掉**别的进程**留下的 helper:DSH 重启时父进程被换掉,但 PowerShell 子进程不会跟着死,
107
- // 它继续占着 Alt+V,新实例就永远注册失败(error: 已被其它程序占用)。
108
- // 只杀 owner 不是自己的,否则同进程内两个 listener 会互相把对方干掉(p31 的冲突用例就测不出来了)。
105
+ /**
106
+ * 异步清理别的进程留下的 helper(**不能同步执行**:execFileSync 会把宿主事件循环卡住十几秒,
107
+ * 长按热键时会被反复调用,宿主表现为"卡死"然后被父进程杀掉 → 整个 App 重启)。
108
+ */
109
+ _cleanupOrphansAsync(onDone) {
109
110
  try {
110
111
  const me = String(process.pid)
111
112
  const cmd = [
@@ -113,10 +114,16 @@ export class HotkeyListener {
113
114
  `| Where-Object { $_.CommandLine -like '*hotkey-helper.ps1*' -and $_.CommandLine -notlike '*-OwnerPid ${me}*' }`,
114
115
  '| ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }',
115
116
  ].join(' ')
116
- execFileSync('powershell.exe', ['-NoProfile', '-Command', cmd], { windowsHide: true, timeout: 8000, stdio: 'ignore' })
117
+ const p = spawn('powershell.exe', ['-NoProfile', '-Command', cmd], { windowsHide: true, stdio: 'ignore' })
118
+ p.on('error', () => onDone?.())
119
+ p.on('exit', () => onDone?.())
120
+ setTimeout(() => onDone?.(), 3000)
117
121
  } catch {
118
- /* 清不掉也要继续试 */
122
+ onDone?.()
119
123
  }
124
+ }
125
+
126
+ _spawn() {
120
127
  let child
121
128
  try {
122
129
  child = spawn(
@@ -183,6 +190,19 @@ export class HotkeyListener {
183
190
  this._fatalReason = `热键 ${this.parsed.label} 已被其它程序占用`
184
191
  this.lastError = this._fatalReason
185
192
  this._emit({ type: 'conflict', hotkey: this.parsed.label })
193
+ // 只在"被占用"这条路上清一次孤儿进程,然后重试;清完还不行就认输,别死循环
194
+ if (!this._retriedAfterCleanup) {
195
+ this._retriedAfterCleanup = true
196
+ this._cleanupOrphansAsync(() => {
197
+ if (this.stoppedByUs) return
198
+ this._fatalReason = ''
199
+ this.lastError = ''
200
+ this.state = 'idle'
201
+ setTimeout(() => {
202
+ if (!this.stoppedByUs && !this.child) this._spawn()
203
+ }, 300)
204
+ })
205
+ }
186
206
  } else if (line === 'BADKEY') {
187
207
  this.state = 'error'
188
208
  this._fatalReason = '热键格式不支持'
@@ -223,6 +223,21 @@ export function fallbackUserMessage({ text, kind = 'memory-core' }) {
223
223
  return deepFreeze(structuredClone(message))
224
224
  }
225
225
 
226
+ /**
227
+ * 兜底消息(万能版):content 原样收下,支持 [text, image] 这种多段内容。
228
+ * 语音输入投递时用——dsh-llm 解析不到时也能构造出同形的 UserMessage。
229
+ */
230
+ export function fallbackUserMessageWithContent({ content, kind = 'user' }) {
231
+ const parts = Array.isArray(content) ? content : [{ type: 'text', text: String(content ?? '') }]
232
+ const message = {
233
+ id: randomUUID(),
234
+ role: 'user',
235
+ content: parts,
236
+ source: { kind },
237
+ }
238
+ return deepFreeze(structuredClone(message))
239
+ }
240
+
226
241
  function deepFreeze(value) {
227
242
  if (value && typeof value === 'object' && !Object.isFrozen(value)) {
228
243
  Object.freeze(value)
@@ -0,0 +1,92 @@
1
+ /**
2
+ * screen.js —— 截一张当前屏幕,给"语音提问"配上画面。
3
+ *
4
+ * 为什么用 ffmpeg 而不是截图库:DSH 桌面版本来就带了一份 ffmpeg(see-now / 语音都靠它),
5
+ * 零新依赖,而且 gdigrab 抓的是真实桌面(游戏窗口化时能抓到画面)。
6
+ *
7
+ * 输出统一缩到 1280 宽的 JPEG:PNG 截图动辄 1MB,base64 之后模型侧容易超限;
8
+ * JPEG q4 大约 150KB,看得清 UI,也不至于把请求撑爆。
9
+ *
10
+ * @module memory/screen
11
+ */
12
+ import { spawn } from 'node:child_process'
13
+ import fs from 'node:fs'
14
+ import os from 'node:os'
15
+ import path from 'node:path'
16
+
17
+ export const DEFAULT_WIDTH = 1280
18
+
19
+ /**
20
+ * 截屏一张。
21
+ * @returns {Promise<{ok:boolean, file?:string, bytes?:number, mediaType?:string, reason?:string}>}
22
+ */
23
+ export function captureScreen({ ffmpegPath = 'ffmpeg.exe', outDir = '', width = DEFAULT_WIDTH, timeoutMs = 8000 } = {}) {
24
+ return new Promise((resolve) => {
25
+ const dir = outDir || path.join(os.tmpdir(), 'dsh-memory-shot')
26
+ let file
27
+ try {
28
+ fs.mkdirSync(dir, { recursive: true })
29
+ file = path.join(dir, `shot-${Date.now()}.jpg`)
30
+ } catch (error) {
31
+ resolve({ ok: false, reason: `建目录失败:${error.message}` })
32
+ return
33
+ }
34
+ const w = Math.max(320, Math.min(Number(width) || DEFAULT_WIDTH, 2560))
35
+ let child
36
+ try {
37
+ child = spawn(
38
+ ffmpegPath,
39
+ ['-hide_banner', '-loglevel', 'error', '-f', 'gdigrab', '-i', 'desktop', '-frames:v', '1', '-vf', `scale=${w}:-1`, '-q:v', '4', '-y', file],
40
+ { windowsHide: true, stdio: ['ignore', 'ignore', 'pipe'] },
41
+ )
42
+ } catch (error) {
43
+ resolve({ ok: false, reason: error.message })
44
+ return
45
+ }
46
+ let err = ''
47
+ let settled = false
48
+ const done = (r) => {
49
+ if (settled) return
50
+ settled = true
51
+ resolve(r)
52
+ }
53
+ const timer = setTimeout(() => {
54
+ try {
55
+ child.kill()
56
+ } catch {
57
+ /* 忽略 */
58
+ }
59
+ done({ ok: false, reason: '截屏超时' })
60
+ }, timeoutMs)
61
+ child.stderr.on('data', (c) => {
62
+ err += c.toString('utf8')
63
+ })
64
+ child.on('error', (e) => {
65
+ clearTimeout(timer)
66
+ done({ ok: false, reason: e.message })
67
+ })
68
+ child.on('exit', (code) => {
69
+ clearTimeout(timer)
70
+ if (code !== 0) {
71
+ done({ ok: false, reason: `ffmpeg 退出 ${code}${err ? ':' + err.trim().slice(0, 120) : ''}` })
72
+ return
73
+ }
74
+ try {
75
+ const bytes = fs.statSync(file).size
76
+ if (bytes < 1024) {
77
+ done({ ok: false, reason: '截图是空的' })
78
+ return
79
+ }
80
+ done({ ok: true, file, bytes, mediaType: 'image/jpeg' })
81
+ } catch (error) {
82
+ done({ ok: false, reason: error.message })
83
+ }
84
+ })
85
+ })
86
+ }
87
+
88
+ /** 读成 base64,给消息内容里的 image part 用。 */
89
+ export function toImagePart(file, mediaType = 'image/jpeg') {
90
+ const data = fs.readFileSync(file).toString('base64')
91
+ return { type: 'image', source: { type: 'base64', data, media_type: mediaType } }
92
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sixlayer-memory",
3
- "version": "2.5.4",
3
+ "version": "2.6.0",
4
4
  "private": false,
5
5
  "description": "DSH 工作台:六层记忆底座(每轮自动召回 + 候选沉淀 + 闸门审计)+ 零件化,支持 QQ 随身使用。",
6
6
  "type": "module",