dsh-sixlayer-memory 2.2.0 → 2.3.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,36 @@
1
1
  # 变更记录 · dsh-sixlayer-memory(六层记忆底座)
2
2
 
3
+ ## 2.3.0 — 2026-12-05
4
+
5
+ 主题:**按一下说话,说完文字直接进输入框**(不再只是唤起系统听写)。
6
+
7
+ ### 新增
8
+
9
+ - **DeepSeek 语音识别**(`lib/memory/asr.js`):`ffmpeg` 录一段 16kHz 单声道 WAV →
10
+ `POST https://api.deepseek.com/v1/tools/asr` → 文字 → 粘到当前输入框。
11
+ - key 来源优先级:`asr.apiKey` 配置 > `DEEPSEEK_API_KEY` 环境变量 > `~/.dsh/.credentials.yaml` 的 `refs`
12
+ - 麦克风自动发现(`ffmpeg -list_devices`),也可用 `asr.device` 指定
13
+ - 硬限制与官方一致:单段 ≤120 秒、≤8MiB;**识别失败绝不删录音**,WAV 留在 `memory-data/voice/`
14
+ - **粘完不自动回车**(`asr.autoEnter: false`):粘错了还能改,自动发送救不回来
15
+ - **本地保底(B 方案)**:`asr.localCommand` 指向任意本地识别程序(sherpa-onnx / whisper.cpp 都行),
16
+ 约定「传 wav 路径,stdout 输出文本」。云端失败(没 key / 429 / 超时)时自动降级走它,
17
+ 并修了 Windows 子进程按 GBK 输出的乱码问题(`chcp 65001`)
18
+ - **`mem_voice` 工具**(第 35 个):`status` / `start` / `stop` / `file`(转写已有音频)
19
+ - 热键动作新增 `asr`:`mem_hotkey({ action: 'asr' })` 后,**按一下开始录、再按一下结束并转写粘贴**
20
+
21
+ ### 修复
22
+
23
+ - 热键进程生命周期:`stop()` 前先置空 `child`,旧子进程退出不再覆盖新状态
24
+ - 热键动作 `asr` 不再被归一化成 `dictation`
25
+
26
+ ### 回归
27
+
28
+ - 新增 `p32`(23 项):设备解析、key 三种来源、配置三层、真机录音 2 秒、**真实调用 DeepSeek ASR
29
+ 识别 SAPI 合成语音**、本地保底、错误路径
30
+ - 全量 **35 个套件全绿**,工具 35 个
31
+
32
+ ---
33
+
3
34
  ## 2.2.0 — 2026-12-05
4
35
 
5
36
  主题:**按一个键就能说话**。
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  dsh plugin --profile desktop add dsh-sixlayer-memory
12
12
  ```
13
13
 
14
- **当前版本**:2.2.0 · **34 个工具** · schema v9 · 零外部依赖 · 回归 34 个套件全绿
14
+ **当前版本**:2.3.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
@@ -18,6 +18,7 @@ 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, loadDeepSeekKey, pasteText, resolveAsrConfig, transcribe, transcribeLocal } from './memory/asr.js'
21
22
  import { createApiHandler, ensureApiToken, createApiServer } from './memory/api.js'
22
23
  import { createQqOfficialBridge } from './memory/qq-official.js'
23
24
  import { ingestQqSessions, affectReport } from './memory/affect-events.js'
@@ -193,6 +194,67 @@ export function apply(ctx, config = {}) {
193
194
  : null
194
195
  diag('injector ' + (injector ? 'ok' : 'skipped'))
195
196
 
197
+ // 语音输入:按热键录音 → DeepSeek ASR 转写 → 粘到当前输入框(保底可走本地识别命令)
198
+ const asrConfig = resolveAsrConfig(config.asr, dataDir)
199
+ const voice = new VoiceRecorder({
200
+ device: asrConfig.device,
201
+ outDir: path.join(dataDir, 'voice'),
202
+ logger: (m) => diag('asr: ' + m),
203
+ })
204
+ let lastVoice = null
205
+ const toggleVoice = async () => {
206
+ // 正在录 → 停 + 转写 + 粘贴
207
+ if (voice.recording) {
208
+ const stopped = await voice.stop()
209
+ if (!stopped.ok) {
210
+ lastVoice = { at: new Date().toISOString(), ok: false, stage: 'record', reason: stopped.reason }
211
+ diag('asr: 录音失败 ' + stopped.reason)
212
+ return lastVoice
213
+ }
214
+ const { key, source } = loadDeepSeekKey({ dataDir, config: asrConfig })
215
+ let result = await transcribe({ file: stopped.file, apiKey: key, baseUrl: asrConfig.baseUrl })
216
+ let via = 'deepseek'
217
+ // B 保底:云端不通/没 key 时,试本地识别命令
218
+ if (!result.ok && asrConfig.localCommand) {
219
+ diag(`asr: 云端失败(${result.reason}),转本地:${asrConfig.localCommand}`)
220
+ const local = await transcribeLocal({ file: stopped.file, command: asrConfig.localCommand })
221
+ if (local.ok) {
222
+ result = local
223
+ via = 'local'
224
+ }
225
+ }
226
+ if (!result.ok) {
227
+ lastVoice = { at: new Date().toISOString(), ok: false, stage: 'transcribe', reason: result.reason, file: stopped.file }
228
+ diag('asr: 转写失败 ' + result.reason)
229
+ return lastVoice
230
+ }
231
+ const pasted = await pasteText(result.text, { autoEnter: asrConfig.autoEnter })
232
+ try {
233
+ store?.recorder?.record?.({ op: 'voice', via, key_source: source, chars: result.text.length, ms: result.durationMs ?? stopped.ms })
234
+ } catch {
235
+ /* 审计失败不影响 */
236
+ }
237
+ lastVoice = {
238
+ at: new Date().toISOString(),
239
+ ok: true,
240
+ stage: 'done',
241
+ text: result.text,
242
+ via,
243
+ ms: result.durationMs ?? stopped.ms,
244
+ pasted: pasted.ok,
245
+ file: stopped.file,
246
+ }
247
+ return lastVoice
248
+ }
249
+ // 没在录 → 开始录
250
+ const started = await voice.start()
251
+ lastVoice = started.ok
252
+ ? { at: new Date().toISOString(), ok: true, stage: 'recording', file: started.file }
253
+ : { at: new Date().toISOString(), ok: false, stage: 'record', reason: started.reason }
254
+ if (!started.ok) diag('asr: 开始录音失败 ' + started.reason)
255
+ return lastVoice
256
+ }
257
+
196
258
  // 全局热键:按一个键唤起系统语音听写(Win+H)。默认关闭,开了才注册。
197
259
  const hotkeyConfig = resolveHotkeyConfig(config.hotkey, dataDir)
198
260
  const hotkey = new HotkeyListener({
@@ -203,6 +265,10 @@ export function apply(ctx, config = {}) {
203
265
  try {
204
266
  if (ev.type === 'press') {
205
267
  store?.recorder?.record?.({ op: 'hotkey', hotkey: ev.hotkey, action: hotkeyConfig.action })
268
+ // 动作是 asr 时,按下热键 = 开始/结束录音(录音和识别都在 Node 侧做)
269
+ if (hotkeyConfig.action === 'asr') {
270
+ toggleVoice().catch((error) => diag('asr: 热键流程异常 ' + (error?.message ?? error)))
271
+ }
206
272
  } else if (ev.type === 'conflict') {
207
273
  logger?.warn?.(`memory-core: 全局热键 ${ev.hotkey} 被占用,换一个键或关掉这个功能`)
208
274
  }
@@ -359,6 +425,30 @@ export function apply(ctx, config = {}) {
359
425
 
360
426
  const host = new ToolHost(ctx)
361
427
  host.hotkey = { listener: hotkey, dataDir, enabled: hotkeyConfig.enabled }
428
+ host.voice = {
429
+ recorder: voice,
430
+ toggle: toggleVoice,
431
+ status: () => ({
432
+ recording: voice.recording,
433
+ device: asrConfig.device,
434
+ baseUrl: asrConfig.baseUrl,
435
+ localCommand: asrConfig.localCommand,
436
+ lastVoice,
437
+ }),
438
+ transcribeFile: async (file) => {
439
+ const { key } = loadDeepSeekKey({ dataDir, config: asrConfig })
440
+ let r = await transcribe({ file, apiKey: key, baseUrl: asrConfig.baseUrl })
441
+ let via = 'deepseek'
442
+ if (!r.ok && asrConfig.localCommand) {
443
+ const local = await transcribeLocal({ file, command: asrConfig.localCommand })
444
+ if (local.ok) {
445
+ r = local
446
+ via = 'local'
447
+ }
448
+ }
449
+ return { ...r, via }
450
+ },
451
+ }
362
452
  const registry = store ? buildRegistry(store, host) : null
363
453
  host.definitions = registry
364
454
  ? new Map([...registry.entries()].map(([toolName, item]) => [toolName, item.definition]))
@@ -0,0 +1,341 @@
1
+ /**
2
+ * asr.js —— 按热键说话 → 录音 → DeepSeek 语音识别 → 文字。
3
+ *
4
+ * 链路:ffmpeg(dshow) 录一段 WAV → POST https://api.deepseek.com/v1/tools/asr → text
5
+ *
6
+ * 设计取舍:
7
+ * - 录音用 ffmpeg(系统自带没有,但 DSH 桌面版塞了一份在 ~/.dsh/tools/ffmpeg/bin),零新依赖;
8
+ * - 只做"一段一段"的识别,不做流式——接口本身就不支持流式,假装流式只会更难用;
9
+ * - 识别失败绝不吞掉录音:WAV 留在磁盘上,下次还能重试或人工听。
10
+ *
11
+ * 保底(B):配置 `asr.localCommand` 指向任意本地识别程序(sherpa-onnx / whisper.cpp 都行),
12
+ * 约定"给一个 wav 路径,stdout 输出文本"。云端不通时自动走它。
13
+ *
14
+ * @module memory/asr
15
+ */
16
+ import { spawn } from 'node:child_process'
17
+ import fs from 'node:fs'
18
+ import os from 'node:os'
19
+ import path from 'node:path'
20
+
21
+ export const DEFAULT_BASE_URL = 'https://api.deepseek.com'
22
+ export const MAX_SECONDS = 120
23
+ export const MAX_BYTES = 8 * 1024 * 1024
24
+
25
+ /** 找一个可用的 ffmpeg(和 see-now 一样的顺序)。 */
26
+ export function resolveFfmpeg(env = process.env) {
27
+ const explicit = env.DSH_FFMPEG_PATH || env.FFMPEG_PATH
28
+ if (explicit && fs.existsSync(explicit)) return explicit
29
+ const home = env.DSH_HOME || path.join(env.USERPROFILE || env.HOME || os.homedir(), '.dsh')
30
+ for (const candidate of [path.join(home, 'tools', 'ffmpeg', 'bin', 'ffmpeg.exe'), path.join(home, 'bin', 'ffmpeg.exe')]) {
31
+ if (fs.existsSync(candidate)) return candidate
32
+ }
33
+ return 'ffmpeg.exe'
34
+ }
35
+
36
+ /**
37
+ * 读 DeepSeek key:显式配置 > 环境变量 > ~/.dsh/.credentials.yaml 的 refs。
38
+ * 只读 `refs` 段的明文键,不碰加密记录。
39
+ * @returns {{key:string, source:string}}
40
+ */
41
+ export function loadDeepSeekKey({ dataDir = '', config = {}, env = process.env } = {}) {
42
+ if (config.apiKey) return { key: String(config.apiKey), source: 'config' }
43
+ if (env.DEEPSEEK_API_KEY) return { key: String(env.DEEPSEEK_API_KEY), source: 'env' }
44
+ const home = env.DSH_HOME || path.join(env.USERPROFILE || env.HOME || os.homedir(), '.dsh')
45
+ const file = path.join(home, '.credentials.yaml')
46
+ try {
47
+ const raw = fs.readFileSync(file, 'utf8')
48
+ const m = /DEEPSEEK_API_KEY:\s*(\S+)/.exec(raw)
49
+ if (m && m[1]) return { key: m[1].replace(/^["']|["']$/g, ''), source: 'credentials' }
50
+ } catch {
51
+ /* 读不到就算了 */
52
+ }
53
+ return { key: '', source: 'none' }
54
+ }
55
+
56
+ /**
57
+ * 列音频输入设备(ffmpeg -list_devices 的输出解析)。
58
+ * @returns {string[]} 设备友好名,按出现顺序
59
+ */
60
+ export function parseAudioDevices(output) {
61
+ const names = []
62
+ for (const line of String(output ?? '').split(/\r?\n/)) {
63
+ const m = /"([^"]+)"\s*\(audio\)\s*$/.exec(line.trim())
64
+ if (m) names.push(m[1])
65
+ }
66
+ return names
67
+ }
68
+
69
+ export function listAudioDevices({ ffmpegPath = resolveFfmpeg(), timeoutMs = 8000 } = {}) {
70
+ return new Promise((resolve) => {
71
+ let out = ''
72
+ let child
73
+ try {
74
+ child = spawn(ffmpegPath, ['-hide_banner', '-list_devices', 'true', '-f', 'dshow', '-i', 'dummy'], {
75
+ windowsHide: true,
76
+ stdio: ['ignore', 'ignore', 'pipe'],
77
+ })
78
+ } catch {
79
+ resolve([])
80
+ return
81
+ }
82
+ const timer = setTimeout(() => {
83
+ try {
84
+ child.kill()
85
+ } catch {
86
+ /* 忽略 */
87
+ }
88
+ resolve(parseAudioDevices(out))
89
+ }, timeoutMs)
90
+ child.stderr.on('data', (c) => {
91
+ out += c.toString('utf8')
92
+ })
93
+ child.on('error', () => {
94
+ clearTimeout(timer)
95
+ resolve([])
96
+ })
97
+ child.on('exit', () => {
98
+ clearTimeout(timer)
99
+ resolve(parseAudioDevices(out))
100
+ })
101
+ })
102
+ }
103
+
104
+ /**
105
+ * 录音器:一台机器同时只该有一个。start/stop 成对使用。
106
+ */
107
+ export class VoiceRecorder {
108
+ constructor({ ffmpegPath = resolveFfmpeg(), device = '', outDir = '', maxSeconds = MAX_SECONDS, logger = null } = {}) {
109
+ this.ffmpegPath = ffmpegPath
110
+ this.device = device
111
+ this.outDir = outDir || path.join(os.tmpdir(), 'dsh-memory-voice')
112
+ this.maxSeconds = Math.min(Number(maxSeconds) || MAX_SECONDS, MAX_SECONDS)
113
+ this.log = logger ?? (() => {})
114
+ this.child = null
115
+ this.file = ''
116
+ this.startedAt = 0
117
+ }
118
+
119
+ get recording() {
120
+ return Boolean(this.child)
121
+ }
122
+
123
+ /** @returns {Promise<{ok:boolean, file?:string, device?:string, reason?:string}>} */
124
+ async start({ device = this.device } = {}) {
125
+ if (this.child) return { ok: false, reason: '已经在录了' }
126
+ let dev = device
127
+ if (!dev) {
128
+ const devices = await listAudioDevices({ ffmpegPath: this.ffmpegPath })
129
+ dev = devices[0] ?? ''
130
+ }
131
+ if (!dev) return { ok: false, reason: '没有找到麦克风设备' }
132
+
133
+ fs.mkdirSync(this.outDir, { recursive: true })
134
+ const file = path.join(this.outDir, `voice-${Date.now()}.wav`)
135
+ const args = [
136
+ '-hide_banner', '-loglevel', 'error',
137
+ '-f', 'dshow', '-i', `audio=${dev}`,
138
+ '-ac', '1', '-ar', '16000', '-t', String(this.maxSeconds),
139
+ '-y', file,
140
+ ]
141
+ let child
142
+ try {
143
+ child = spawn(this.ffmpegPath, args, { windowsHide: true, stdio: ['pipe', 'ignore', 'pipe'] })
144
+ } catch (error) {
145
+ return { ok: false, reason: error.message }
146
+ }
147
+ this.child = child
148
+ this.file = file
149
+ this.device = dev
150
+ this.startedAt = Date.now()
151
+ child.stderr.on('data', (c) => this.log(c.toString('utf8').trim().slice(0, 200)))
152
+ child.on('exit', () => {
153
+ if (this.child === child) this.child = null
154
+ })
155
+ return { ok: true, file, device: dev }
156
+ }
157
+
158
+ /** 停止并等文件落盘。 @returns {Promise<{ok:boolean, file?:string, ms?:number, reason?:string}>} */
159
+ async stop() {
160
+ const child = this.child
161
+ if (!child) return { ok: false, reason: '没有在录' }
162
+ this.child = null
163
+ const ms = Date.now() - this.startedAt
164
+ await new Promise((resolve) => {
165
+ const done = () => resolve()
166
+ child.once('exit', done)
167
+ try {
168
+ child.stdin.write('q\n')
169
+ } catch {
170
+ /* 某些平台写不进去 */
171
+ }
172
+ setTimeout(() => {
173
+ try {
174
+ child.kill()
175
+ } catch {
176
+ /* 已经退出 */
177
+ }
178
+ resolve()
179
+ }, 1500)
180
+ })
181
+ // ffmpeg 写 WAV 头需要一点时间
182
+ await new Promise((r) => setTimeout(r, 150))
183
+ if (!fs.existsSync(this.file)) return { ok: false, reason: '录音文件没生成(麦克风被占用?)' }
184
+ const size = fs.statSync(this.file).size
185
+ if (size < 2048) {
186
+ return { ok: false, reason: `录音太短(${size} 字节)`, file: this.file }
187
+ }
188
+ return { ok: true, file: this.file, ms }
189
+ }
190
+ }
191
+
192
+ /**
193
+ * 调 DeepSeek ASR 接口。
194
+ * @returns {Promise<{ok:boolean, text?:string, durationMs?:number, reason?:string}>}
195
+ */
196
+ export async function transcribe({ file, apiKey, baseUrl = DEFAULT_BASE_URL, timeoutMs = 60000, fetchImpl = fetch } = {}) {
197
+ if (!apiKey) return { ok: false, reason: '没有 DeepSeek API key(配置 asr.apiKey 或环境变量 DEEPSEEK_API_KEY)' }
198
+ if (!file || !fs.existsSync(file)) return { ok: false, reason: '音频文件不存在' }
199
+ const size = fs.statSync(file).size
200
+ if (size > MAX_BYTES) return { ok: false, reason: `音频超过 8MB(${Math.round(size / 1048576)}MB)` }
201
+
202
+ const form = new FormData()
203
+ const buf = fs.readFileSync(file)
204
+ form.append('file', new Blob([buf], { type: 'audio/wav' }), path.basename(file))
205
+
206
+ const url = `${String(baseUrl).replace(/\/+$/, '')}/v1/tools/asr`
207
+ try {
208
+ const res = await fetchImpl(url, {
209
+ method: 'POST',
210
+ headers: { authorization: `Bearer ${apiKey}` },
211
+ body: form,
212
+ signal: AbortSignal.timeout(timeoutMs),
213
+ })
214
+ const body = await res.text()
215
+ let json = null
216
+ try {
217
+ json = JSON.parse(body)
218
+ } catch {
219
+ /* 非 JSON */
220
+ }
221
+ if (!res.ok) {
222
+ const detail = json?.error?.message ?? json?.message ?? body.slice(0, 200)
223
+ return { ok: false, reason: `ASR ${res.status}:${detail}` }
224
+ }
225
+ return { ok: true, text: String(json?.text ?? ''), durationMs: Number(json?.duration_ms ?? 0) }
226
+ } catch (error) {
227
+ return { ok: false, reason: `ASR 请求失败:${error?.message ?? error}` }
228
+ }
229
+ }
230
+
231
+ /** 覆盖文件:和 hotkey.json 放一起。apiKey 故意不落盘。 */
232
+ export function asrOverridesPath(dataDir) {
233
+ return path.join(String(dataDir ?? ''), 'meta', 'asr.json')
234
+ }
235
+
236
+ function readAsrOverrides(dataDir) {
237
+ try {
238
+ const raw = fs.readFileSync(asrOverridesPath(dataDir), 'utf8').replace(/^\uFEFF/, '')
239
+ const obj = JSON.parse(raw)
240
+ return obj && typeof obj === 'object' ? obj : {}
241
+ } catch {
242
+ return {}
243
+ }
244
+ }
245
+
246
+ /**
247
+ * 合并三层:cordis 配置 > meta/asr.json > 默认值。
248
+ * 默认**关闭**:录音会占麦克风,不主动开。
249
+ */
250
+ export function resolveAsrConfig(config = {}, dataDir = '') {
251
+ const stored = readAsrOverrides(dataDir)
252
+ const pick = (k, fallback) => (config && config[k] !== undefined ? config[k] : stored[k] !== undefined ? stored[k] : fallback)
253
+ return {
254
+ enabled: Boolean(pick('enabled', false)),
255
+ baseUrl: String(pick('baseUrl', DEFAULT_BASE_URL)),
256
+ localCommand: String(pick('localCommand', '')),
257
+ device: String(pick('device', '')),
258
+ autoEnter: Boolean(pick('autoEnter', false)),
259
+ apiKey: config?.apiKey ? String(config.apiKey) : '',
260
+ }
261
+ }
262
+
263
+ /** 写覆盖文件(工具改配置时用)。apiKey 不进文件。 */
264
+ export function saveAsrConfig(dataDir, patch = {}) {
265
+ const next = { ...readAsrOverrides(dataDir) }
266
+ for (const k of ['enabled', 'baseUrl', 'localCommand', 'device', 'autoEnter']) {
267
+ if (patch[k] !== undefined) next[k] = patch[k]
268
+ }
269
+ const file = asrOverridesPath(dataDir)
270
+ fs.mkdirSync(path.dirname(file), { recursive: true })
271
+ fs.writeFileSync(file, JSON.stringify(next, null, 2), 'utf8')
272
+ return next
273
+ }
274
+
275
+ /** 保底:把 wav 交给本地识别程序,stdout 当前第一行非空文本。 */export function transcribeLocal({ file, command, timeoutMs = 60000 } = {}) {
276
+ return new Promise((resolve) => {
277
+ if (!command) {
278
+ resolve({ ok: false, reason: '没有配置本地识别命令' })
279
+ return
280
+ }
281
+ let out = ''
282
+ let child
283
+ // Windows 上子进程默认按 OEM 码页(936)输出,直接当 UTF-8 读会变乱码。
284
+ // 先 chcp 65001 把控制台切到 UTF-8,再执行命令。
285
+ const finalCommand = command.replace(/\{file\}/g, `"${file}"`)
286
+ const shellCommand = process.platform === 'win32' ? `chcp 65001 >nul & ${finalCommand}` : finalCommand
287
+ try {
288
+ child = spawn(shellCommand, { shell: true, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
289
+ } catch (error) {
290
+ resolve({ ok: false, reason: error.message })
291
+ return
292
+ }
293
+ child.stdout.setEncoding('utf8')
294
+ const timer = setTimeout(() => {
295
+ try {
296
+ child.kill()
297
+ } catch {
298
+ /* 忽略 */
299
+ }
300
+ }, timeoutMs)
301
+ child.stdout.on('data', (c) => {
302
+ out += c.toString('utf8')
303
+ })
304
+ child.on('error', (error) => {
305
+ clearTimeout(timer)
306
+ resolve({ ok: false, reason: error.message })
307
+ })
308
+ child.on('exit', () => {
309
+ clearTimeout(timer)
310
+ const text = out.split(/\r?\n/).map((s) => s.trim()).find(Boolean) ?? ''
311
+ resolve(text ? { ok: true, text } : { ok: false, reason: '本地识别没有输出' })
312
+ })
313
+ })
314
+ }
315
+
316
+ /**
317
+ * 把文本送进当前焦点输入框:写剪贴板 + 模拟 Ctrl+V。
318
+ * 故意**不自动回车**——粘错了还能改,自动发送就救不回来了。
319
+ */
320
+ export function pasteText(text, { autoEnter = false } = {}) {
321
+ return new Promise((resolve) => {
322
+ const esc = String(text).replace(/`/g, '``').replace(/'/g, "''")
323
+ const script = [
324
+ `Add-Type -AssemblyName System.Windows.Forms`,
325
+ `Set-Clipboard -Value '${esc}'`,
326
+ `Add-Type @"`,
327
+ `using System;using System.Runtime.InteropServices;`,
328
+ `public class P { [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra); }`,
329
+ `"@`,
330
+ `[P]::keybd_event(0x11,0,0,[UIntPtr]::Zero)`,
331
+ `[P]::keybd_event(0x56,0,0,[UIntPtr]::Zero)`,
332
+ `Start-Sleep -Milliseconds 40`,
333
+ `[P]::keybd_event(0x56,0,2,[UIntPtr]::Zero)`,
334
+ `[P]::keybd_event(0x11,0,2,[UIntPtr]::Zero)`,
335
+ autoEnter ? `Start-Sleep -Milliseconds 80; [P]::keybd_event(0x0D,0,0,[UIntPtr]::Zero); [P]::keybd_event(0x0D,0,2,[UIntPtr]::Zero)` : `'pasted'`,
336
+ ].join('\n')
337
+ const child = spawn('powershell.exe', ['-NoProfile', '-Command', script], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
338
+ child.on('error', (error) => resolve({ ok: false, reason: error.message }))
339
+ child.on('exit', (code) => resolve({ ok: code === 0, reason: code === 0 ? '' : `粘贴进程退出 ${code}` }))
340
+ })
341
+ }
@@ -26,13 +26,15 @@ public class HKHelper {
26
26
  function Invoke-Action {
27
27
  param([string]$Name)
28
28
  if ($Name -eq 'dictation') {
29
- # Win+H:唤起 Windows 语音听写
29
+ # Win+H:唤起 Windows 语音听写。
30
+ # 注意按键序列必须成对:LWIN↓ H↓ H↑ LWIN↑,LWIN 是扩展键(EXTENDEDKEY=1,KEYUP=2)。
31
+ # 旧写法多按了一次 LWIN↓,会把 Win 键留在按下状态,后续组合键全部失灵。
30
32
  [HKHelper]::keybd_event(0x5B, 0, 1, [UIntPtr]::Zero)
31
- Start-Sleep -Milliseconds 40
33
+ Start-Sleep -Milliseconds 50
32
34
  [HKHelper]::keybd_event(0x48, 0, 0, [UIntPtr]::Zero)
33
- Start-Sleep -Milliseconds 40
35
+ Start-Sleep -Milliseconds 50
34
36
  [HKHelper]::keybd_event(0x48, 0, 2, [UIntPtr]::Zero)
35
- [HKHelper]::keybd_event(0x5B, 0, 1, [UIntPtr]::Zero)
37
+ Start-Sleep -Milliseconds 30
36
38
  [HKHelper]::keybd_event(0x5B, 0, 3, [UIntPtr]::Zero)
37
39
  }
38
40
  }
@@ -103,8 +103,9 @@ export class HotkeyListener {
103
103
  }
104
104
 
105
105
  _spawn() {
106
+ let child
106
107
  try {
107
- this.child = spawn(
108
+ child = spawn(
108
109
  'powershell.exe',
109
110
  ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', HELPER, '-Key', this.parsed.key, '-Mods', String(this.parsed.mods), '-Action', this.action],
110
111
  { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] },
@@ -115,10 +116,12 @@ export class HotkeyListener {
115
116
  this.log(`热键启动失败:${error.message}`)
116
117
  return
117
118
  }
119
+ this.child = child
118
120
 
119
121
  let buf = ''
120
- this.child.stdout.setEncoding('utf8')
121
- this.child.stdout.on('data', (chunk) => {
122
+ child.stdout.setEncoding('utf8')
123
+ child.stdout.on('data', (chunk) => {
124
+ if (this.child !== child) return
122
125
  buf += chunk
123
126
  let i
124
127
  while ((i = buf.indexOf('\n')) >= 0) {
@@ -127,12 +130,15 @@ export class HotkeyListener {
127
130
  this._onLine(line)
128
131
  }
129
132
  })
130
- this.child.stderr.on('data', () => {})
131
- this.child.on('error', (error) => {
133
+ child.stderr.on('data', () => {})
134
+ child.on('error', (error) => {
135
+ if (this.child !== child) return
132
136
  this.state = 'error'
133
137
  this.lastError = error.message
134
138
  })
135
- this.child.on('exit', (code) => {
139
+ child.on('exit', (code) => {
140
+ // 老的子进程(被 stop 掉的)退出时不能改当前状态
141
+ if (this.child !== child) return
136
142
  this.child = null
137
143
  if (this.stoppedByUs) {
138
144
  this.state = 'stopped'
@@ -180,13 +186,14 @@ export class HotkeyListener {
180
186
 
181
187
  stop() {
182
188
  this.stoppedByUs = true
183
- if (this.child) {
189
+ const child = this.child
190
+ this.child = null // 先置空:exit 回调看到 this.child !== child 就会跳过
191
+ if (child) {
184
192
  try {
185
- this.child.kill()
193
+ child.kill()
186
194
  } catch {
187
195
  /* 已经没了 */
188
196
  }
189
- this.child = null
190
197
  }
191
198
  this.state = 'stopped'
192
199
  }
@@ -250,10 +257,11 @@ export function resolveHotkeyConfig(config = {}, dataDir = '') {
250
257
  const stored = readOverrides(dataDir)
251
258
  const pick = (k, fallback) => (config && config[k] !== undefined ? config[k] : stored[k] !== undefined ? stored[k] : fallback)
252
259
  const action = String(pick('action', 'dictation'))
260
+ const ALLOWED = new Set(['dictation', 'asr', 'none'])
253
261
  return {
254
262
  enabled: Boolean(pick('enabled', false)),
255
263
  key: String(pick('key', DEFAULT_HOTKEY)),
256
- action: action === 'dictation' || action === 'none' ? action : 'dictation',
264
+ action: ALLOWED.has(action) ? action : 'dictation',
257
265
  }
258
266
  }
259
267
 
@@ -762,7 +762,11 @@ export function buildRegistry(store, host) {
762
762
  additionalProperties: false,
763
763
  properties: {
764
764
  key: { type: 'string', description: '热键,如 Alt+V / Ctrl+Shift+F9;必须带修饰键' },
765
- action: { type: 'string', enum: ['dictation', 'none'], description: 'dictation=唤起系统听写;none=只记录不动作' },
765
+ action: {
766
+ type: 'string',
767
+ enum: ['dictation', 'asr', 'none'],
768
+ description: 'dictation=唤起系统听写;asr=录音并调 DeepSeek 识别后粘贴;none=只记录',
769
+ },
766
770
  enabled: { type: 'boolean', description: '开或关' },
767
771
  },
768
772
  },
@@ -810,6 +814,102 @@ export function buildRegistry(store, host) {
810
814
  { label: '全局热键', argsHint: 'mem_hotkey({ key?, action?, enabled? })', needsOpen: false },
811
815
  )
812
816
 
817
+ add(
818
+ {
819
+ name: 'mem_voice',
820
+ description:
821
+ '语音输入:不带参数查状态;start 开始录音、stop 停止并转写(DeepSeek ASR,失败自动走本地保底命令)、' +
822
+ 'file 直接转写一个已有音频文件。转写结果会粘到当前输入框(默认不自动回车)。',
823
+ parameters: {
824
+ type: 'object',
825
+ additionalProperties: false,
826
+ properties: {
827
+ action: { type: 'string', enum: ['status', 'start', 'stop', 'file'], description: '默认 status' },
828
+ file: { type: 'string', description: 'action=file 时的音频路径(16kHz 单声道 WAV 最佳)' },
829
+ },
830
+ },
831
+ output: {
832
+ schema: textOut({
833
+ state: { type: 'string' },
834
+ ok: { type: 'boolean' },
835
+ text: { type: 'string' },
836
+ via: { type: 'string' },
837
+ ms: { type: 'integer' },
838
+ reason: { type: 'string' },
839
+ file: { type: 'string' },
840
+ }),
841
+ render: renderText,
842
+ },
843
+ isConcurrencySafe: () => false,
844
+ execute: async (args) => {
845
+ const ctl = host?.voice
846
+ const action = String(args?.action ?? 'status')
847
+ if (!ctl) {
848
+ return { state: 'unavailable', ok: false, text: '', via: '', ms: 0, reason: '插件降级模式', file: '' }
849
+ }
850
+ if (action === 'start') {
851
+ const r = await ctl.recorder.start()
852
+ const st = r.ok ? 'recording' : 'idle'
853
+ return {
854
+ state: st,
855
+ ok: r.ok,
856
+ text: r.ok ? `开始录音(${r.device}),再调一次 stop 结束。` : `没开起来:${r.reason}`,
857
+ via: '',
858
+ ms: 0,
859
+ reason: r.reason ?? '',
860
+ file: r.file ?? '',
861
+ }
862
+ }
863
+ if (action === 'stop') {
864
+ const r = await ctl.toggle()
865
+ if (r?.stage === 'recording') {
866
+ return { state: 'recording', ok: true, text: '正在录音中…', via: '', ms: 0, reason: '', file: r.file ?? '' }
867
+ }
868
+ const ok = Boolean(r?.ok)
869
+ return {
870
+ state: ok ? 'done' : 'idle',
871
+ ok,
872
+ text: ok ? `识别完成(${r.via}/${r.ms}ms):${r.text}` : `失败:${r.reason ?? '未知'}`,
873
+ via: r?.via ?? '',
874
+ ms: Number(r?.ms ?? 0),
875
+ reason: r?.reason ?? '',
876
+ file: r?.file ?? '',
877
+ }
878
+ }
879
+ if (action === 'file') {
880
+ const file = String(args?.file ?? '').trim()
881
+ if (!file) return { state: 'idle', ok: false, text: '', via: '', ms: 0, reason: '需要 file', file: '' }
882
+ const r = await ctl.transcribeFile(file)
883
+ return {
884
+ state: r.ok ? 'done' : 'idle',
885
+ ok: r.ok,
886
+ text: r.ok ? `识别结果:${r.text}` : `失败:${r.reason}`,
887
+ via: r.via ?? '',
888
+ ms: Number(r.ms ?? 0),
889
+ reason: r.reason ?? '',
890
+ file,
891
+ }
892
+ }
893
+ const s = ctl.status()
894
+ return {
895
+ state: s.recording ? 'recording' : s.lastVoice?.ok ? 'done' : 'idle',
896
+ ok: true,
897
+ text: [
898
+ `录音:${s.recording ? '进行中' : '空闲'} · 设备:${s.device || '(自动)'}`,
899
+ `识别:${s.baseUrl}(云端)${s.localCommand ? ' / 本地保底已配' : ' / 本地保底未配'}`,
900
+ s.lastVoice ? `上次:${s.lastVoice.ok ? `「${s.lastVoice.text}」(${s.lastVoice.via})` : s.lastVoice.reason}` : '上次:还没有',
901
+ '热键动作设成 asr 后,按一下开始录、再按一下结束并转写。',
902
+ ].join('\n'),
903
+ via: s.lastVoice?.via ?? '',
904
+ ms: Number(s.lastVoice?.ms ?? 0),
905
+ reason: '',
906
+ file: s.lastVoice?.file ?? '',
907
+ }
908
+ },
909
+ },
910
+ { label: '语音输入', argsHint: 'mem_voice({ action?: start|stop|file|status, file? })', needsOpen: false },
911
+ )
912
+
813
913
  // ---------- 交接与体检(迁移自 luanyujia-workbench 记忆机制) ----------
814
914
 
815
915
  const SECTION_LABELS = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sixlayer-memory",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "private": false,
5
5
  "description": "DSH 工作台:六层记忆底座(每轮自动召回 + 候选沉淀 + 闸门审计)+ 零件化,支持 QQ 随身使用。",
6
6
  "type": "module",
@@ -64,6 +64,7 @@
64
64
  "mem_pending",
65
65
  "mem_conflicts",
66
66
  "mem_hotkey",
67
+ "mem_voice",
67
68
  "mem_resume",
68
69
  "mem_handoff",
69
70
  "mem_check",
package/tools/p32.mjs ADDED
@@ -0,0 +1,122 @@
1
+ /** p32:语音输入(DeepSeek ASR)—— 设备解析 / key 来源 / 真实转写 / 本地保底 */
2
+ import { execFileSync } from 'node:child_process'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import {
7
+ VoiceRecorder,
8
+ listAudioDevices,
9
+ loadDeepSeekKey,
10
+ parseAudioDevices,
11
+ resolveAsrConfig,
12
+ saveAsrConfig,
13
+ transcribe,
14
+ transcribeLocal,
15
+ } from '../lib/memory/asr.js'
16
+
17
+ let pass = 0
18
+ let fail = 0
19
+ function ok(name, cond, extra = '') {
20
+ if (cond) { pass += 1; console.log(' ok ' + name) } else { fail += 1; console.log(' FAIL ' + name + (extra ? ' :: ' + extra : '')) }
21
+ }
22
+
23
+ // ---------- 1. 设备解析 ----------
24
+ const sample = [
25
+ '[dshow @ 000] "本机麦克风 (适用于数字麦克风的英特尔® 智音技术)" (audio)',
26
+ '[dshow @ 000] Alternative name "@device_cm_{...}"',
27
+ '[dshow @ 000] "OBS Virtual Camera" (video)',
28
+ '[dshow @ 000] "麦克风 (USB Audio)" (audio)',
29
+ ].join('\r\n')
30
+ const devs = parseAudioDevices(sample)
31
+ ok('解析:只取 audio 设备', devs.length === 2 && devs[0].includes('本机麦克风'), JSON.stringify(devs))
32
+ ok('解析:video 设备不算', !devs.some((d) => d.includes('OBS')))
33
+ ok('解析:空输出返回空数组', parseAudioDevices('').length === 0)
34
+
35
+ // ---------- 2. key 来源 ----------
36
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'p32-'))
37
+ const home = path.join(tmp, 'home')
38
+ fs.mkdirSync(home, { recursive: true })
39
+ fs.writeFileSync(path.join(home, '.credentials.yaml'), 'version: 1\nrefs:\n DEEPSEEK_API_KEY: sk-test-123\n', 'utf8')
40
+ ok('key:配置优先', loadDeepSeekKey({ config: { apiKey: 'sk-cfg' }, env: { DSH_HOME: home } }).key === 'sk-cfg')
41
+ ok('key:环境变量次之', loadDeepSeekKey({ config: {}, env: { DSH_HOME: home, DEEPSEEK_API_KEY: 'sk-env' } }).key === 'sk-env')
42
+ const fromCred = loadDeepSeekKey({ config: {}, env: { DSH_HOME: home } })
43
+ ok('key:从 credentials 的 refs 读', fromCred.key === 'sk-test-123' && fromCred.source === 'credentials', JSON.stringify(fromCred))
44
+ ok('key:都没有时返回空', loadDeepSeekKey({ config: {}, env: { DSH_HOME: path.join(tmp, 'nope') } }).key === '')
45
+
46
+ // ---------- 3. 配置三层 ----------
47
+ ok('配置:默认关闭', resolveAsrConfig({}, tmp).enabled === false)
48
+ saveAsrConfig(tmp, { enabled: true, localCommand: 'whisper {file}' })
49
+ const cfg = resolveAsrConfig({}, tmp)
50
+ ok('配置:写入后读回', cfg.enabled === true && cfg.localCommand === 'whisper {file}', JSON.stringify(cfg))
51
+ ok('配置:apiKey 不落盘', !JSON.stringify(fs.readFileSync(path.join(tmp, 'meta', 'asr.json'), 'utf8')).includes('sk-'))
52
+ ok('配置:cordis 优先', resolveAsrConfig({ baseUrl: 'http://x' }, tmp).baseUrl === 'http://x')
53
+
54
+ // ---------- 4. 真机:列设备 + 录 2 秒 ----------
55
+ const devices = await listAudioDevices()
56
+ ok('真机:至少一个麦克风', devices.length >= 1, JSON.stringify(devices))
57
+
58
+ if (devices.length > 0) {
59
+ const rec = new VoiceRecorder({ outDir: path.join(tmp, 'voice'), device: devices[0] })
60
+ const started = await rec.start()
61
+ ok('录音:开始成功', started.ok === true, JSON.stringify(started))
62
+ await new Promise((r) => setTimeout(r, 2000))
63
+ const stopped = await rec.stop()
64
+ ok('录音:停止后有文件', stopped.ok === true && fs.existsSync(stopped.file), JSON.stringify(stopped))
65
+ if (stopped.ok) {
66
+ const size = fs.statSync(stopped.file).size
67
+ ok('录音:文件大小合理(>16KB)', size > 16000, `${size} 字节`)
68
+ const again = await rec.start()
69
+ ok('录音:停止后能再开', again.ok === true, JSON.stringify(again))
70
+ await new Promise((r) => setTimeout(r, 300))
71
+ await rec.stop()
72
+ }
73
+ }
74
+
75
+ // ---------- 5. 真实转写(SAPI 合成一句中文) ----------
76
+ const wav = path.join(tmp, 'speech.wav')
77
+ try {
78
+ execFileSync(
79
+ 'powershell.exe',
80
+ ['-NoProfile', '-Command', `
81
+ Add-Type -AssemblyName System.Speech
82
+ $s = New-Object System.Speech.Synthesis.SpeechSynthesizer
83
+ $v = $s.GetInstalledVoices() | Where-Object { $_.VoiceInfo.Culture.Name -like 'zh*' } | Select-Object -First 1
84
+ if (-not $v) { exit 2 }
85
+ $s.SelectVoice($v.VoiceInfo.Name)
86
+ $s.SetOutputToWaveFile('${wav.replace(/\\/g, '\\\\')}')
87
+ $s.Speak('帮我看一下后室第三关怎么走')
88
+ $s.Dispose()
89
+ `],
90
+ { windowsHide: true, timeout: 30000 },
91
+ )
92
+ } catch {
93
+ /* 没中文语音就跳过 */
94
+ }
95
+
96
+ const realKey = loadDeepSeekKey({})
97
+ if (fs.existsSync(wav) && realKey.key) {
98
+ const r = await transcribe({ file: wav, apiKey: realKey.key })
99
+ ok('转写:调用成功', r.ok === true, JSON.stringify(r))
100
+ if (r.ok) {
101
+ console.log(' 识别到:' + r.text)
102
+ ok('转写:内容对得上(含"后室/后世"与"第三关")', /后[室世]/.test(r.text) && /第三关/.test(r.text), r.text)
103
+ ok('转写:返回时长', Number(r.durationMs) > 1000, String(r.durationMs))
104
+ }
105
+ } else {
106
+ console.log(' (跳过真实转写:没有 wav 或没有 key)')
107
+ ok('转写:没 key 时给明确原因', (await transcribe({ file: wav || 'x', apiKey: '' })).ok === false)
108
+ }
109
+
110
+ // ---------- 6. 错误路径 ----------
111
+ const noKey = await transcribe({ file: wav || 'x', apiKey: '' })
112
+ ok('转写:没 key → 明确报错而不是崩', noKey.ok === false && /key/i.test(noKey.reason), noKey.reason)
113
+ const badFile = await transcribe({ file: path.join(tmp, 'nope.wav'), apiKey: 'sk-x' })
114
+ ok('转写:文件不存在 → 报错', badFile.ok === false && /不存在/.test(badFile.reason), badFile.reason)
115
+ const local = await transcribeLocal({ file: 'x.wav', command: `powershell -NoProfile -Command "Write-Output '本地结果'"` })
116
+ ok('本地保底:能取到 stdout 第一行', local.ok === true && local.text === '本地结果', JSON.stringify(local))
117
+ const noLocal = await transcribeLocal({ file: 'x.wav', command: '' })
118
+ ok('本地保底:没配命令时报错不崩', noLocal.ok === false)
119
+
120
+ fs.rmSync(tmp, { recursive: true, force: true })
121
+ console.log(`\nP32 ${fail === 0 ? 'OK' : 'FAIL'} pass=${pass} fail=${fail}`)
122
+ process.exit(fail === 0 ? 0 : 1)