dsh-sixlayer-memory 2.7.0 → 2.8.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,28 @@
1
1
  # 变更记录 · dsh-sixlayer-memory(六层记忆底座)
2
2
 
3
+ ## 2.8.0 — 2026-12-06
4
+
5
+ 主题:**用嘴问,用耳朵听**——语音问完,回答由桌宠的声音念出来。
6
+
7
+ ### 新增
8
+
9
+ - **回答转语音**(`lib/memory/tts.js`):用 dsh-pet 装的那份 `@andresaya/edge-tts`(同一引擎、同一批音色),
10
+ **不需要任何 API key**:
11
+ - `speakable()` 把 Markdown 洗成能念的句子:丢标题行、代码块、表格分隔行、强调标记;
12
+ 链接只念文字;超长在句号处截断加省略号
13
+ - 播放链路:mp3 → 有 `ffplay` 就直接播,没有就转 wav 用 `SoundPlayer`(`ffplay` 缺失也能出声)
14
+ - **只念"语音问出来的那一轮"**:`turn/end` 里取助手最后一条回复;只有最近 5 分钟内发生过语音投递才念,
15
+ 打字聊天不会突然出声。配置 `tts.enabled`、`tts.voice`、`tts.windowMs`
16
+ - lifecycle 新增 `onReply` 回调(顺带把 `assistant/message` 也解析了,不只看 `user/message`)
17
+
18
+ ### 回归
19
+
20
+ - 新增 `p34`(11 项):标题/代码块/表格/列表/链接/强调清洗、句号处截断、空输入
21
+ - 真机验证:edge-tts 合成 → mp3 → wav → SoundPlayer 播放成功
22
+ - 全量 **37 个套件全绿**
23
+
24
+ ---
25
+
3
26
  ## 2.7.0 — 2026-12-06
4
27
 
5
28
  主题:**桌宠接上记忆**——它终于记得你的事了。
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  dsh plugin --profile desktop add dsh-sixlayer-memory
12
12
  ```
13
13
 
14
- **当前版本**:2.7.0 · **35 个工具** · schema v9 · 零外部依赖 · 回归 36 个套件全绿
14
+ **当前版本**:2.8.0 · **35 个工具** · schema v9 · 零外部依赖 · 回归 38 个套件全绿
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
@@ -29,6 +29,7 @@ import {
29
29
  } from './memory/stream-asr.js'
30
30
  import { captureScreen, toImagePart } from './memory/screen.js'
31
31
  import { createRecall, registerPetMemory } from './memory/pet-bridge.js'
32
+ import { speak } from './memory/tts.js'
32
33
  import { createApiHandler, ensureApiToken, createApiServer } from './memory/api.js'
33
34
  import { createQqOfficialBridge } from './memory/qq-official.js'
34
35
  import { ingestQqSessions, affectReport } from './memory/affect-events.js'
@@ -216,6 +217,8 @@ export function apply(ctx, config = {}) {
216
217
  // pre-step 时记下活着的 agent:语音识别完直接把文字当消息投进去,不靠剪贴板
217
218
  let lastAgent = null
218
219
  let lastSessionId = ''
220
+ // 最近一次"用嘴问"的时间:只有这种轮次结束后才把回答念出来,打字聊天不吵
221
+ let lastVoiceAt = 0
219
222
  const toggleVoice = async () => {
220
223
  // 正在录 → 停 + 转写 + 粘贴
221
224
  if (voice.recording) {
@@ -413,6 +416,7 @@ export function apply(ctx, config = {}) {
413
416
  const pasted = await pasteText(text, { autoEnter: asrConfig.autoEnter })
414
417
  delivered = pasted.ok ? 'paste' : 'failed'
415
418
  }
419
+ lastVoiceAt = Date.now()
416
420
  try {
417
421
  store?.recorder?.record?.({
418
422
  op: 'voice',
@@ -756,6 +760,20 @@ export function apply(ctx, config = {}) {
756
760
  if (agent) lastAgent = agent
757
761
  if (sessionId) lastSessionId = sessionId
758
762
  },
763
+ onReply: (text, { sessionId } = {}) => {
764
+ // 只念"语音问出来的那一轮"的回答;5 分钟之外的打字轮次一律不念
765
+ if (config.tts?.enabled === false) return
766
+ if (!lastVoiceAt || Date.now() - lastVoiceAt > Number(config.tts?.windowMs ?? 300000)) return
767
+ if (sessionId && lastSessionId && sessionId !== lastSessionId) return
768
+ lastVoiceAt = 0 // 一句只能念一次
769
+ speak(text, {
770
+ voice: String(config.tts?.voice ?? 'zh-CN-XiaoxiaoNeural'),
771
+ outDir: path.join(dataDir, 'voice'),
772
+ logger: (m) => diag('tts: ' + m),
773
+ })
774
+ .then((r) => diag(`tts: 念了 ${r.chars ?? 0} 字(${r.player ?? '无播放器'})${r.ok ? '' : '失败:' + r.reason}`))
775
+ .catch((error) => diag('tts: 异常 ' + (error?.message ?? error)))
776
+ },
759
777
  })
760
778
  return () => {
761
779
  try {
@@ -252,7 +252,7 @@ function deepFreeze(value) {
252
252
  * @param {any} ctx 宿主上下文
253
253
  * @param {{store:any, config?:any, diag?:(m:string)=>void, createUserMessage?:Function}} options
254
254
  */
255
- export function attachLifecycle(ctx, { store, config, diag = () => {}, createUserMessage, onAgent = null } = {}) {
255
+ export function attachLifecycle(ctx, { store, config, diag = () => {}, createUserMessage, onAgent = null, onReply = null } = {}) {
256
256
  const cfg = normalizeLifecycle(config)
257
257
  if (!store) return () => {}
258
258
  if (cfg.enabled === false) {
@@ -434,7 +434,18 @@ export function attachLifecycle(ctx, { store, config, diag = () => {}, createUse
434
434
 
435
435
  const events = eventsOfTurn(session, event.seq, turn)
436
436
  const texts = []
437
+ let lastReply = ''
437
438
  for (const ev of events) {
439
+ // 助手最后说了什么:语音对话结束时要让桌宠把它念出来
440
+ if (ev?.type === 'assistant/message') {
441
+ const said = (Array.isArray(ev?.data?.content) ? ev.data.content : [])
442
+ .filter((b) => b?.type === 'text' && typeof b.text === 'string')
443
+ .map((b) => b.text)
444
+ .join('\n')
445
+ .trim()
446
+ if (said) lastReply = said
447
+ continue
448
+ }
438
449
  if (ev?.type !== 'user/message' || ev?.data?.source?.kind !== 'user') continue
439
450
  const text = (Array.isArray(ev.data.content) ? ev.data.content : [])
440
451
  .filter((b) => b?.type === 'text' && typeof b.text === 'string')
@@ -442,6 +453,13 @@ export function attachLifecycle(ctx, { store, config, diag = () => {}, createUse
442
453
  .join('\n')
443
454
  if (text) texts.push(text)
444
455
  }
456
+ if (lastReply) {
457
+ try {
458
+ onReply?.(lastReply, { sessionId: String(session?.id ?? ''), turn })
459
+ } catch (error) {
460
+ diag('lifecycle: onReply 回调出错 ' + (error?.message ?? error))
461
+ }
462
+ }
445
463
  if (texts.length === 0) return
446
464
 
447
465
  const candidates = extractCandidates(texts.join('\n'), {
@@ -0,0 +1,166 @@
1
+ /**
2
+ * tts.js —— 让桌宠的声音念出回复(edge-tts,免 key)。
3
+ *
4
+ * 用的是 dsh-pet 装的那份 `@andresaya/edge-tts`(同一个引擎、同一批音色),
5
+ * 所以听起来和桌宠自己说话一模一样,而且**不需要任何 API key**。
6
+ *
7
+ * 播放走 ffplay(ffmpeg 自带);没有 ffplay 就用 PowerShell 的 MediaPlayer。
8
+ * 全部失败只是"没声音",绝不影响对话本身。
9
+ *
10
+ * @module memory/tts
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
+ import { createRequire } from 'node:module'
17
+ import { fileURLToPath } from 'node:url'
18
+ import { resolveFfmpeg } from './asr.js'
19
+
20
+ const require_ = createRequire(fileURLToPath(import.meta.url))
21
+ export const DEFAULT_VOICE = 'zh-CN-XiaoxiaoNeural'
22
+
23
+ /** 去掉 markdown/代码块/表格,只留能念的句子。 */
24
+ export function speakable(text, { maxChars = 220 } = {}) {
25
+ const raw = String(text ?? '')
26
+ const body = []
27
+ for (const line of raw.split(/\r?\n/)) {
28
+ const t = line.trim()
29
+ if (!t) continue
30
+ // 标题行(#、==)念出来很怪,整行丢掉;代码块围栏、表格分隔行也丢
31
+ if (/^#{1,6}\s+/.test(t) || /^[-=]{3,}$/.test(t) || /^```/.test(t)) continue
32
+ if (t.includes('-') && /^\|?[\s:|-]+\|?$/.test(t)) continue
33
+ body.push(t.replace(/^[-*+]\s+/, ''))
34
+ }
35
+ let s = body.join(' ')
36
+ s = s.replace(/`([^`]*)`/g, '$1')
37
+ s = s.replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
38
+ s = s.replace(/^\s*[-*+]\s+/g, '')
39
+ s = s.replace(/\|/g, ' ')
40
+ s = s.replace(/[*_~>]/g, '')
41
+ s = s.replace(/https?:\/\/\S+/g, '链接')
42
+ s = s.replace(/\s+/g, ' ').trim()
43
+ if (s.length <= maxChars) return s
44
+ // 尽量在句号处截断,别把半句话念出去
45
+ const cut = s.slice(0, maxChars)
46
+ const lastStop = Math.max(cut.lastIndexOf('。'), cut.lastIndexOf('!'), cut.lastIndexOf('?'), cut.lastIndexOf('. '))
47
+ return (lastStop > maxChars * 0.5 ? cut.slice(0, lastStop + 1) : cut) + '…'
48
+ }
49
+
50
+ /** 找 edge-tts 模块(优先 dsh-pet 装的那份)。 */
51
+ export function loadEdgeTts({ env = process.env, extraDirs = [] } = {}) {
52
+ const dirs = [...extraDirs]
53
+ const homes = [env.DSH_HOME, env.USERPROFILE ? path.join(env.USERPROFILE, '.dsh') : ''].filter(Boolean)
54
+ for (const home of homes) {
55
+ dirs.push(path.join(home, 'profiles', 'desktop', 'node_modules', '@andresaya', 'edge-tts'))
56
+ dirs.push(path.join(home, 'profiles', 'node_modules', '@andresaya', 'edge-tts'))
57
+ dirs.push(path.join(home, 'memory-core', 'runtime', 'node_modules', '@andresaya', 'edge-tts'))
58
+ }
59
+ for (const dir of dirs) {
60
+ try {
61
+ return require_(dir)
62
+ } catch {
63
+ /* 换下一个 */
64
+ }
65
+ }
66
+ return null
67
+ }
68
+
69
+ /** 找一个能播 mp3 的播放器。 */
70
+ export function resolvePlayer({ env = process.env } = {}) {
71
+ const home = env.DSH_HOME || (env.USERPROFILE ? path.join(env.USERPROFILE, '.dsh') : '')
72
+ const candidates = [
73
+ env.DSH_FFMPEG_PATH ? path.join(path.dirname(env.DSH_FFMPEG_PATH), 'ffplay.exe') : '',
74
+ home ? path.join(home, 'tools', 'ffmpeg', 'bin', 'ffplay.exe') : '',
75
+ 'ffplay.exe',
76
+ ].filter(Boolean)
77
+ for (const p of candidates) {
78
+ if (!p.includes(path.sep)) return p
79
+ if (fs.existsSync(p)) return p
80
+ }
81
+ return ''
82
+ }
83
+
84
+ /**
85
+ * 合成并播放一句。
86
+ * @returns {Promise<{ok:boolean, file?:string, chars?:number, reason?:string}>}
87
+ */
88
+ export async function speak(text, { voice = DEFAULT_VOICE, outDir = '', rate = '+0%', volume = '+0%', logger = () => {} } = {}) {
89
+ const say = speakable(text)
90
+ if (!say) return { ok: false, reason: '没有可念的内容' }
91
+ const mod = loadEdgeTts()
92
+ if (!mod) return { ok: false, reason: '找不到 edge-tts(dsh-pet 没装?)' }
93
+ const dir = outDir || path.join(os.tmpdir(), 'dsh-memory-tts')
94
+ let file
95
+ try {
96
+ fs.mkdirSync(dir, { recursive: true })
97
+ file = path.join(dir, `say-${Date.now()}.mp3`)
98
+ } catch (error) {
99
+ return { ok: false, reason: error.message }
100
+ }
101
+ try {
102
+ const TTS = mod.EdgeTTS ?? mod.default ?? mod
103
+ const tts = new TTS()
104
+ if (typeof tts.generate === 'function') {
105
+ // generate() 返回 { audio, format },是最稳的一条;synthesize() 的落盘参数各版本不一致
106
+ const result = await tts.generate(say, voice, { rate, volume })
107
+ const audio = result?.audio ?? result?.data ?? null
108
+ if (!audio) throw new Error('generate() 没有返回音频')
109
+ const ext = result?.format === 'webm' ? 'webm' : 'mp3'
110
+ file = file.replace(/\.mp3$/, '.' + ext)
111
+ fs.writeFileSync(file, Buffer.from(audio))
112
+ } else {
113
+ await tts.synthesize(say, voice, { rate, volume, outputFile: file })
114
+ }
115
+ } catch (error) {
116
+ return { ok: false, reason: `合成失败:${error?.message ?? error}` }
117
+ }
118
+ if (!fs.existsSync(file)) return { ok: false, reason: '合成没有产出文件' }
119
+ const player = resolvePlayer()
120
+ if (player) {
121
+ const viaFfplay = await new Promise((resolve) => {
122
+ let settled = false
123
+ try {
124
+ const p = spawn(player, ['-nodisp', '-autoexit', '-loglevel', 'quiet', file], { windowsHide: true, stdio: 'ignore' })
125
+ p.on('error', () => {
126
+ if (!settled) { settled = true; resolve(false) }
127
+ })
128
+ p.on('exit', (code) => {
129
+ if (!settled) { settled = true; resolve(code === 0 || code === null) }
130
+ })
131
+ setTimeout(() => { if (!settled) { settled = true; resolve(true) } }, 1500)
132
+ } catch {
133
+ resolve(false)
134
+ }
135
+ })
136
+ if (viaFfplay) return { ok: true, file, chars: say.length, player: 'ffplay' }
137
+ logger('ffplay 不可用,改用 SoundPlayer')
138
+ }
139
+ // 没有 ffplay:mp3 → wav,再用 SoundPlayer 播(SoundPlayer 不认 mp3)
140
+ const wav = await toWav(file)
141
+ if (!wav) return { ok: false, reason: '没有可用的播放器', file }
142
+ try {
143
+ spawn('powershell.exe', ['-NoProfile', '-Command', `(New-Object Media.SoundPlayer '${wav}').PlaySync()`], { windowsHide: true, stdio: 'ignore' })
144
+ return { ok: true, file, wav, chars: say.length, player: 'soundplayer' }
145
+ } catch (error) {
146
+ return { ok: false, reason: '播放失败:' + (error?.message ?? error), file }
147
+ }
148
+ }
149
+
150
+ /** mp3 → wav(24k 单声道),给 SoundPlayer 用。 */
151
+ function toWav(mp3) {
152
+ return new Promise((resolve) => {
153
+ const ffmpeg = resolveFfmpeg()
154
+ const wav = mp3.replace(/\.(mp3|webm)$/i, '.wav')
155
+ try {
156
+ const p = spawn(ffmpeg, ['-hide_banner', '-loglevel', 'error', '-i', mp3, '-ar', '24000', '-ac', '1', '-y', wav], {
157
+ windowsHide: true,
158
+ stdio: 'ignore',
159
+ })
160
+ p.on('error', () => resolve(''))
161
+ p.on('exit', (code) => resolve(code === 0 && fs.existsSync(wav) ? wav : ''))
162
+ } catch {
163
+ resolve('')
164
+ }
165
+ })
166
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sixlayer-memory",
3
- "version": "2.7.0",
3
+ "version": "2.8.0",
4
4
  "private": false,
5
5
  "description": "DSH 工作台:六层记忆底座(每轮自动召回 + 候选沉淀 + 闸门审计)+ 零件化,支持 QQ 随身使用。",
6
6
  "type": "module",
package/tools/p34.mjs ADDED
@@ -0,0 +1,44 @@
1
+ /** p34:口播文本清洗(把回答变成能念的句子) */
2
+ import { speakable } from '../lib/memory/tts.js'
3
+
4
+ let pass = 0
5
+ let fail = 0
6
+ function ok(name, cond, extra = '') {
7
+ if (cond) { pass += 1; console.log(' ok ' + name) } else { fail += 1; console.log(' FAIL ' + name + (extra ? ' :: ' + extra : '')) }
8
+ }
9
+
10
+ const a = speakable('## 结论\n\n先找三个电闸,全开之后回中央开门。')
11
+ ok('丢掉标题行', !a.includes('##') && a.startsWith('先找三个电闸'), a)
12
+
13
+ const b = speakable('看这段代码:\n```js\nconsole.log(1)\n```\n然后重启。')
14
+ ok('丢掉代码围栏那几行', !b.includes('```'), b)
15
+
16
+ const c = speakable('见 [文档](https://example.com/x)')
17
+ ok('链接只留文字 + URL 念作"链接"', c.includes('文档') && !c.includes('https://'), c)
18
+
19
+ const d = speakable('- 第一点\n- 第二点\n- 第三点')
20
+ ok('列表项去掉横杠', !d.includes('-') && d.includes('第一点'), d)
21
+
22
+ const e = speakable('**加粗**和_斜体_都要去掉标记')
23
+ ok('去掉强调标记', !e.includes('**') && !e.includes('_'), e)
24
+
25
+ const f = speakable('一'.repeat(300), { maxChars: 50 })
26
+ ok('超长会截断', f.length <= 52, `${f.length} 字`)
27
+
28
+ const g = speakable('短句一。短句二。短句三。'.repeat(10), { maxChars: 30 })
29
+ ok('截断尽量落在句号上', g.endsWith('…') && g.slice(0, -1).endsWith('。'), JSON.stringify(g.slice(-12)))
30
+
31
+ const h = speakable('')
32
+ ok('空输入返回空串', h === '')
33
+
34
+ const i = speakable(undefined)
35
+ ok('undefined 不炸', i === '')
36
+
37
+ const j = speakable('表格 | 列一 | 列二\n|---|----|\n| a | b |')
38
+ ok('表格竖线被清掉', !j.includes('|') && !j.includes('---'), j)
39
+
40
+ const k = speakable('标题\n\n正文第一段。\n\n正文第二段。')
41
+ ok('多段用空格连起来(不换行)', !k.includes('\n'), JSON.stringify(k))
42
+
43
+ console.log(`\nP34 ${fail === 0 ? 'OK' : 'FAIL'} pass=${pass} fail=${fail}`)
44
+ process.exit(fail === 0 ? 0 : 1)