dsh-sixlayer-memory 2.6.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 +61 -0
- package/README.md +1 -1
- package/lib/index.js +28 -0
- package/lib/memory/lifecycle.js +19 -1
- package/lib/memory/pet-bridge.js +130 -0
- package/lib/memory/tts.js +166 -0
- package/package.json +1 -1
- package/tools/p33.mjs +87 -0
- package/tools/p34.mjs +44 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,66 @@
|
|
|
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
|
+
|
|
26
|
+
## 2.7.0 — 2026-12-06
|
|
27
|
+
|
|
28
|
+
主题:**桌宠接上记忆**——它终于记得你的事了。
|
|
29
|
+
|
|
30
|
+
### 背景:dsh-pet 留了一个正式接口
|
|
31
|
+
|
|
32
|
+
翻了 dsh-pet 的源码,它提供 `petApi7340` 服务:
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
ctx.provide("petApi7340", {
|
|
36
|
+
memory: { register, list }, // 对话记忆提供者
|
|
37
|
+
speech: { register, list }, // 语音识别提供者
|
|
38
|
+
voice: { register, list }, // 语音合成提供者
|
|
39
|
+
})
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
每轮对话前它会调 `recall({ petId, system, history, userText })`,**最多等 1500ms**,
|
|
43
|
+
可以返回 `{ system?, userText?, history? }`。这就是"第三方记忆插件"的正门——不用改它的代码。
|
|
44
|
+
|
|
45
|
+
### 新增
|
|
46
|
+
|
|
47
|
+
- **`memory/pet-bridge.js`**:把六层记忆注册成 dsh-pet 的对话记忆提供者
|
|
48
|
+
- `recall`:拿用户这句话去 FTS5 检索,命中的摘要拼成一段
|
|
49
|
+
「【你记得和主人有关的事(来自六层记忆库,按相关度排序)】」接进它的 system
|
|
50
|
+
- **只改 system**,不碰 history/userText——改那两样会让桌宠"自己说过什么"错乱
|
|
51
|
+
- 命中才注入;没命中/太短/检索抛错都返回 `undefined`,桌宠照常说话
|
|
52
|
+
- 注册时机容错:插件加载顺序不定,服务没挂上就轮询(2s 一次,最多 60s)
|
|
53
|
+
- **默认只读不写**:不把桌宠闲聊灌进记忆库(一天能淹掉真记忆);要开写入可以后续加
|
|
54
|
+
- 配置 `pet.enabled`(默认 true);`diag.log` 里 `pet:` 前缀能看到注册状态与每次命中
|
|
55
|
+
|
|
56
|
+
### 回归
|
|
57
|
+
|
|
58
|
+
- 新增 `p33`(18 项):命中拼接、保留原 system、不污染 history、没命中/太短/异常、长度上限、
|
|
59
|
+
服务延迟出现后自动注册、stop 注销、服务始终不存在
|
|
60
|
+
- 全量 **36 个套件全绿**,工具 35 个
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
3
64
|
## 2.6.0 — 2026-12-05
|
|
4
65
|
|
|
5
66
|
主题:**说话时自动带上屏幕截图**——打游戏问"这里怎么走",它得先看得见。
|
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
dsh plugin --profile desktop add dsh-sixlayer-memory
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
**当前版本**:2.
|
|
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
|
@@ -28,6 +28,8 @@ import {
|
|
|
28
28
|
writeOverlayText,
|
|
29
29
|
} from './memory/stream-asr.js'
|
|
30
30
|
import { captureScreen, toImagePart } from './memory/screen.js'
|
|
31
|
+
import { createRecall, registerPetMemory } from './memory/pet-bridge.js'
|
|
32
|
+
import { speak } from './memory/tts.js'
|
|
31
33
|
import { createApiHandler, ensureApiToken, createApiServer } from './memory/api.js'
|
|
32
34
|
import { createQqOfficialBridge } from './memory/qq-official.js'
|
|
33
35
|
import { ingestQqSessions, affectReport } from './memory/affect-events.js'
|
|
@@ -215,6 +217,8 @@ export function apply(ctx, config = {}) {
|
|
|
215
217
|
// pre-step 时记下活着的 agent:语音识别完直接把文字当消息投进去,不靠剪贴板
|
|
216
218
|
let lastAgent = null
|
|
217
219
|
let lastSessionId = ''
|
|
220
|
+
// 最近一次"用嘴问"的时间:只有这种轮次结束后才把回答念出来,打字聊天不吵
|
|
221
|
+
let lastVoiceAt = 0
|
|
218
222
|
const toggleVoice = async () => {
|
|
219
223
|
// 正在录 → 停 + 转写 + 粘贴
|
|
220
224
|
if (voice.recording) {
|
|
@@ -412,6 +416,7 @@ export function apply(ctx, config = {}) {
|
|
|
412
416
|
const pasted = await pasteText(text, { autoEnter: asrConfig.autoEnter })
|
|
413
417
|
delivered = pasted.ok ? 'paste' : 'failed'
|
|
414
418
|
}
|
|
419
|
+
lastVoiceAt = Date.now()
|
|
415
420
|
try {
|
|
416
421
|
store?.recorder?.record?.({
|
|
417
422
|
op: 'voice',
|
|
@@ -439,6 +444,15 @@ export function apply(ctx, config = {}) {
|
|
|
439
444
|
return lastVoice
|
|
440
445
|
}
|
|
441
446
|
|
|
447
|
+
// 桌宠融合:把自己注册成 dsh-pet 的"对话记忆提供者",它每轮对话前会来查记忆。
|
|
448
|
+
const petRecall = store ? createRecall({ store, logger: (m) => diag(m) }) : null
|
|
449
|
+
const petBridge =
|
|
450
|
+
store && config.pet?.enabled !== false
|
|
451
|
+
? registerPetMemory({ ctx, recall: petRecall, logger: (m) => diag(m) })
|
|
452
|
+
: null
|
|
453
|
+
if (petBridge) ctx.effect(() => () => petBridge.stop())
|
|
454
|
+
diag('pet: ' + (petBridge ? JSON.stringify(petBridge.status()) : '未启用'))
|
|
455
|
+
|
|
442
456
|
// 全局热键:按一个键唤起系统语音听写(Win+H)。默认关闭,开了才注册。
|
|
443
457
|
const hotkeyConfig = resolveHotkeyConfig(config.hotkey, dataDir)
|
|
444
458
|
const hotkey = new HotkeyListener({
|
|
@@ -746,6 +760,20 @@ export function apply(ctx, config = {}) {
|
|
|
746
760
|
if (agent) lastAgent = agent
|
|
747
761
|
if (sessionId) lastSessionId = sessionId
|
|
748
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
|
+
},
|
|
749
777
|
})
|
|
750
778
|
return () => {
|
|
751
779
|
try {
|
package/lib/memory/lifecycle.js
CHANGED
|
@@ -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,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pet-bridge.js —— 把六层记忆接到 dsh-pet 的"对话记忆提供者"上。
|
|
3
|
+
*
|
|
4
|
+
* dsh-pet 暴露了一个服务 `petApi7340`,里面有:
|
|
5
|
+
* memory.register({ id, recall, capture })
|
|
6
|
+
* 它每轮对话前会调 `recall({ petId, system, history, userText })`,最多等 1500ms;
|
|
7
|
+
* 我们能返回 `{ system }` 把"你记得关于主人的事"拼进它的系统提示。
|
|
8
|
+
*
|
|
9
|
+
* 设计上的三个克制:
|
|
10
|
+
* 1. **只读不写**:默认只做 recall,不把桌宠闲聊灌进记忆库(否则一天能淹掉真记忆);
|
|
11
|
+
* 2. **超时内完成**:本地 FTS 检索是毫秒级,绝不拖住桌宠回复;
|
|
12
|
+
* 3. **失败静默**:任何异常都返回 undefined,桌宠照常说话。
|
|
13
|
+
*
|
|
14
|
+
* @module memory/pet-bridge
|
|
15
|
+
*/
|
|
16
|
+
export const PET_SERVICE = 'petApi7340'
|
|
17
|
+
export const PROVIDER_ID = 'sixlayer'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 造一个 recall 函数:查记忆库,命中的摘要拼成一段系统提示。
|
|
21
|
+
* @param {{store:any, topK?:number, maxChars?:number, minQueryChars?:number, logger?:(m:string)=>void}} options
|
|
22
|
+
*/
|
|
23
|
+
export function createRecall({ store, topK = 3, maxChars = 600, minQueryChars = 2, logger = () => {} } = {}) {
|
|
24
|
+
let calls = 0
|
|
25
|
+
let hitsTotal = 0
|
|
26
|
+
const recall = async ({ petId = '', system = '', userText = '' } = {}) => {
|
|
27
|
+
calls += 1
|
|
28
|
+
const query = String(userText ?? '').trim()
|
|
29
|
+
if (query.length < minQueryChars) return undefined
|
|
30
|
+
let rows = []
|
|
31
|
+
try {
|
|
32
|
+
rows = store.search({ query, topK }) ?? []
|
|
33
|
+
} catch (error) {
|
|
34
|
+
logger(`pet: 检索失败 ${error?.message ?? error}`)
|
|
35
|
+
return undefined
|
|
36
|
+
}
|
|
37
|
+
const lines = rows
|
|
38
|
+
.map((r) => String(r.summary ?? r.snippet ?? '').replace(/\s+/g, ' ').trim())
|
|
39
|
+
.filter((s) => s.length >= 4)
|
|
40
|
+
if (lines.length === 0) return undefined
|
|
41
|
+
hitsTotal += lines.length
|
|
42
|
+
let block = lines.map((s, i) => `${i + 1}. ${s}`).join('\n')
|
|
43
|
+
if (block.length > maxChars) block = block.slice(0, maxChars) + '…'
|
|
44
|
+
// 只动 system,不碰 history/userText —— 改那两样会让桌宠"自己说过什么"错乱
|
|
45
|
+
const next = `${system}\n\n【你记得和主人有关的事(来自六层记忆库,按相关度排序)】\n${block}`
|
|
46
|
+
logger(`pet: petId=${petId || '-'} query=${query.slice(0, 20)} 命中 ${lines.length} 条`)
|
|
47
|
+
return { system: next }
|
|
48
|
+
}
|
|
49
|
+
recall.stats = () => ({ calls, hits: hitsTotal })
|
|
50
|
+
return recall
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 尝试注册到 dsh-pet。宿主可能还没把服务挂上(插件加载顺序不定),所以:
|
|
55
|
+
* 先立即试一次,没有就轮询,最多等 60 秒。
|
|
56
|
+
*
|
|
57
|
+
* @returns {{ok:boolean, stop:Function, status:Function}}
|
|
58
|
+
*/
|
|
59
|
+
export function registerPetMemory({ ctx, recall, providerId = PROVIDER_ID, logger = () => {}, pollMs = 2000, maxWaitMs = 60000 } = {}) {
|
|
60
|
+
let dispose = null
|
|
61
|
+
let stopped = false
|
|
62
|
+
let attempts = 0
|
|
63
|
+
let state = 'pending'
|
|
64
|
+
let reason = ''
|
|
65
|
+
|
|
66
|
+
const tryRegister = () => {
|
|
67
|
+
if (dispose || stopped) return Boolean(dispose)
|
|
68
|
+
attempts += 1
|
|
69
|
+
let api = null
|
|
70
|
+
try {
|
|
71
|
+
api = ctx?.get?.(PET_SERVICE) ?? ctx?.[PET_SERVICE] ?? null
|
|
72
|
+
} catch {
|
|
73
|
+
api = null
|
|
74
|
+
}
|
|
75
|
+
const register = api?.memory?.register
|
|
76
|
+
if (typeof register !== 'function') {
|
|
77
|
+
return false
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
dispose = register.call(api.memory, { id: providerId, recall })
|
|
81
|
+
state = 'registered'
|
|
82
|
+
reason = ''
|
|
83
|
+
logger(`pet: 已注册记忆提供者 ${providerId}`)
|
|
84
|
+
return true
|
|
85
|
+
} catch (error) {
|
|
86
|
+
state = 'error'
|
|
87
|
+
reason = error?.message ?? String(error)
|
|
88
|
+
logger('pet: 注册失败 ' + reason)
|
|
89
|
+
return false
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (!tryRegister()) {
|
|
94
|
+
const startedAt = Date.now()
|
|
95
|
+
const timer = setInterval(() => {
|
|
96
|
+
if (stopped || dispose) {
|
|
97
|
+
clearInterval(timer)
|
|
98
|
+
return
|
|
99
|
+
}
|
|
100
|
+
if (tryRegister()) {
|
|
101
|
+
clearInterval(timer)
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
if (Date.now() - startedAt > maxWaitMs) {
|
|
105
|
+
clearInterval(timer)
|
|
106
|
+
state = 'unavailable'
|
|
107
|
+
reason = 'dsh-pet 没挂 petApi7340(没装或没启用)'
|
|
108
|
+
logger('pet: ' + reason)
|
|
109
|
+
}
|
|
110
|
+
}, pollMs)
|
|
111
|
+
timer.unref?.()
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
get ok() {
|
|
116
|
+
return Boolean(dispose)
|
|
117
|
+
},
|
|
118
|
+
status: () => ({ provider: providerId, state, registered: Boolean(dispose), attempts, reason }),
|
|
119
|
+
stop: () => {
|
|
120
|
+
stopped = true
|
|
121
|
+
try {
|
|
122
|
+
dispose?.()
|
|
123
|
+
} catch {
|
|
124
|
+
/* 忽略 */
|
|
125
|
+
}
|
|
126
|
+
dispose = null
|
|
127
|
+
state = 'stopped'
|
|
128
|
+
},
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -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
package/tools/p33.mjs
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/** p33:桌宠记忆桥(recall 拼 system / 未命中返回 undefined / 注册轮询与清理) */
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import os from 'node:os'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import MemoryStore from '../lib/memory/store.js'
|
|
6
|
+
import { PET_SERVICE, PROVIDER_ID, createRecall, registerPetMemory } from '../lib/memory/pet-bridge.js'
|
|
7
|
+
|
|
8
|
+
let pass = 0
|
|
9
|
+
let fail = 0
|
|
10
|
+
function ok(name, cond, extra = '') {
|
|
11
|
+
if (cond) { pass += 1; console.log(' ok ' + name) } else { fail += 1; console.log(' FAIL ' + name + (extra ? ' :: ' + extra : '')) }
|
|
12
|
+
}
|
|
13
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
14
|
+
|
|
15
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'p33-'))
|
|
16
|
+
const store = new MemoryStore({ dataDir: dir }).open()
|
|
17
|
+
store.write({ content: '主人喜欢喝冰美式,不加糖。', layer: 'L2', sourceChannel: 'user' })
|
|
18
|
+
store.write({ content: '主人打游戏卡在逃离后室第三关,发电机那关。', layer: 'L2', sourceChannel: 'user' })
|
|
19
|
+
store.write({ content: '主人每天下午三点左右会犯困。', layer: 'L4', sourceChannel: 'user' })
|
|
20
|
+
|
|
21
|
+
const logs = []
|
|
22
|
+
const recall = createRecall({ store, logger: (m) => logs.push(m) })
|
|
23
|
+
|
|
24
|
+
// ---------- 1. 命中:把摘要拼进 system ----------
|
|
25
|
+
const r1 = await recall({ petId: 'main', system: '你是鲸鱼娘。', userText: '后室那个游戏我该怎么打' })
|
|
26
|
+
ok('命中:返回 system', typeof r1?.system === 'string', JSON.stringify(r1))
|
|
27
|
+
ok('命中:保留了原 system 开头', r1?.system?.startsWith('你是鲸鱼娘。'), r1?.system?.slice(0, 20))
|
|
28
|
+
ok('命中:带上记忆块标题', r1?.system?.includes('你记得和主人有关的事'), r1?.system?.slice(-80))
|
|
29
|
+
ok('命中:提到后室那条', r1?.system?.includes('后室') || r1?.system?.includes('发电机'), r1?.system?.slice(-120))
|
|
30
|
+
ok('命中:不动 history / userText', r1 && r1.history === undefined && r1.userText === undefined, JSON.stringify(Object.keys(r1 ?? {})))
|
|
31
|
+
|
|
32
|
+
// ---------- 2. 没命中 / 太短 ----------
|
|
33
|
+
const r2 = await recall({ petId: 'main', system: 's', userText: '量子色动力学的重整化群方程' })
|
|
34
|
+
ok('没命中:返回 undefined', r2 === undefined, JSON.stringify(r2))
|
|
35
|
+
const r3 = await recall({ petId: 'main', system: 's', userText: '嗯' })
|
|
36
|
+
ok('太短:直接跳过', r3 === undefined)
|
|
37
|
+
const r4 = await recall({})
|
|
38
|
+
ok('空参数:不炸', r4 === undefined)
|
|
39
|
+
|
|
40
|
+
// ---------- 3. 统计 ----------
|
|
41
|
+
const st = recall.stats()
|
|
42
|
+
ok('统计:累计调用次数', st.calls >= 4, JSON.stringify(st))
|
|
43
|
+
ok('统计:命中条数 > 0', st.hits > 0, JSON.stringify(st))
|
|
44
|
+
|
|
45
|
+
// ---------- 4. 长度上限 ----------
|
|
46
|
+
const long = createRecall({ store, maxChars: 30 })
|
|
47
|
+
const r5 = await long({ petId: 'main', system: 's', userText: '主人 后室 游戏' })
|
|
48
|
+
ok('上限:超过 maxChars 会截断并加省略号', r5?.system?.includes('…'), (r5?.system ?? '').slice(-40))
|
|
49
|
+
|
|
50
|
+
// ---------- 5. store 抛错时静默 ----------
|
|
51
|
+
const broken = createRecall({
|
|
52
|
+
store: { search() { throw new Error('boom') } },
|
|
53
|
+
logger: () => {},
|
|
54
|
+
})
|
|
55
|
+
const r6 = await broken({ petId: 'main', system: 's', userText: '随便问问什么' })
|
|
56
|
+
ok('检索异常:返回 undefined 不抛', r6 === undefined)
|
|
57
|
+
|
|
58
|
+
// ---------- 6. 注册:服务不存在时轮询,出现后注册成功 ----------
|
|
59
|
+
let registered = null
|
|
60
|
+
const fakeCtx = {
|
|
61
|
+
get(name) {
|
|
62
|
+
if (name !== PET_SERVICE) return undefined
|
|
63
|
+
return fakeCtx.__api
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
fakeCtx.__api = undefined
|
|
67
|
+
const bridge = registerPetMemory({ ctx: fakeCtx, recall, logger: () => {}, pollMs: 50, maxWaitMs: 2000 })
|
|
68
|
+
ok('注册:服务不在时先报未注册', bridge.ok === false && bridge.status().state === 'pending', JSON.stringify(bridge.status()))
|
|
69
|
+
fakeCtx.__api = { memory: { register(def) { registered = def; return () => { registered = null } } } }
|
|
70
|
+
await sleep(300)
|
|
71
|
+
ok('注册:服务出现后自动注册', bridge.ok === true && registered?.id === PROVIDER_ID, JSON.stringify(bridge.status()))
|
|
72
|
+
ok('注册:拿到的 recall 可用', typeof registered?.recall === 'function')
|
|
73
|
+
const r7 = await registered.recall({ petId: 'main', system: 'sys', userText: '冰美式' })
|
|
74
|
+
ok('注册:通过服务调用 recall 能返回 system', typeof r7?.system === 'string', JSON.stringify(r7))
|
|
75
|
+
bridge.stop()
|
|
76
|
+
ok('注册:stop 之后注销', bridge.ok === false && bridge.status().state === 'stopped')
|
|
77
|
+
|
|
78
|
+
// ---------- 7. 服务始终不存在 ----------
|
|
79
|
+
const bridge2 = registerPetMemory({ ctx: { get: () => undefined }, recall, logger: () => {}, pollMs: 50, maxWaitMs: 300 })
|
|
80
|
+
await sleep(600)
|
|
81
|
+
ok('注册:始终没有服务 → unavailable', bridge2.status().state === 'unavailable', JSON.stringify(bridge2.status()))
|
|
82
|
+
bridge2.stop()
|
|
83
|
+
|
|
84
|
+
store.close()
|
|
85
|
+
fs.rmSync(dir, { recursive: true, force: true })
|
|
86
|
+
console.log(`\nP33 ${fail === 0 ? 'OK' : 'FAIL'} pass=${pass} fail=${fail}`)
|
|
87
|
+
process.exit(fail === 0 ? 0 : 1)
|
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)
|