dsh-sixlayer-memory 2.1.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,64 @@
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
+
34
+ ## 2.2.0 — 2026-12-05
35
+
36
+ 主题:**按一个键就能说话**。
37
+
38
+ ### 新增
39
+
40
+ - **全局热键 → 系统语音听写**(`lib/memory/hotkey.js` + `hotkey-helper.ps1`):注册一个系统级热键
41
+ (默认 `Alt+V`,必须带修饰键,裸键会被拒),按下即唤起 Windows 语音听写(`Win+H`),
42
+ 说完文字自动落到光标处——和你看到的主播那套"按键说话"是同一个思路,只是不依赖第三方插件。
43
+ - 实现零依赖:一个 PowerShell 子进程用 `RegisterHotKey` + 线程消息循环监听,Node 侧读 stdout
44
+ - 热键被占用会**明确报冲突**(不是静默失效);子进程崩了自动重拉(最多 5 次);全部失败只降级不影响记忆主流程
45
+ - 每次触发记一条 `op: 'hotkey'` 审计
46
+ - **`mem_hotkey` 工具**(第 34 个):查状态 / 改键 / 开关 / 换动作(`dictation` 或 `none`),
47
+ 改动立即生效并写进 `memory-data/meta/hotkey.json`(优先级:cordis 配置 > 覆盖文件 > 默认)
48
+ - 配置项 `hotkey: { enabled, key, action }`,**默认关闭**——热键会抢系统按键,开了才注册
49
+
50
+ ### 回归
51
+
52
+ - 新增 `p31`(24 项):热键解析 8 种写法、真实注册 + 合成按键、同键冲突检测、非法键不抛、配置三层合并
53
+ - 全量 **34 个套件全绿**,工具 34 个
54
+
55
+ ### 说明
56
+
57
+ - 只支持 Windows(`RegisterHotKey` 是 Win32 API);macOS/Linux 会返回"不支持"而不是假装启动
58
+ - 要"按一下 → 说 → 它回话(声音)",还差回话这一侧:那需要 TTS 的 key(Breeze)或用别的通道
59
+
60
+ ---
61
+
3
62
  ## 2.1.0 — 2026-12-02
4
63
 
5
64
  主题:**记忆会老、会说错、会改口**。补上时间、冲突、并发三处缺口。
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  dsh plugin --profile desktop add dsh-sixlayer-memory
12
12
  ```
13
13
 
14
- **当前版本**:2.1.0 · **33 个工具** · schema v9 · 零外部依赖 · 回归 33 个套件全绿
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
@@ -17,6 +17,8 @@ import { attachLifecycle, lifecycleSummary } 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
+ import { HotkeyListener, resolveHotkeyConfig } from './memory/hotkey.js'
21
+ import { VoiceRecorder, loadDeepSeekKey, pasteText, resolveAsrConfig, transcribe, transcribeLocal } from './memory/asr.js'
20
22
  import { createApiHandler, ensureApiToken, createApiServer } from './memory/api.js'
21
23
  import { createQqOfficialBridge } from './memory/qq-official.js'
22
24
  import { ingestQqSessions, affectReport } from './memory/affect-events.js'
@@ -192,6 +194,99 @@ export function apply(ctx, config = {}) {
192
194
  : null
193
195
  diag('injector ' + (injector ? 'ok' : 'skipped'))
194
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
+
258
+ // 全局热键:按一个键唤起系统语音听写(Win+H)。默认关闭,开了才注册。
259
+ const hotkeyConfig = resolveHotkeyConfig(config.hotkey, dataDir)
260
+ const hotkey = new HotkeyListener({
261
+ key: hotkeyConfig.key,
262
+ action: hotkeyConfig.action,
263
+ logger: (m) => diag('hotkey: ' + m),
264
+ onEvent: (ev) => {
265
+ try {
266
+ if (ev.type === 'press') {
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
+ }
272
+ } else if (ev.type === 'conflict') {
273
+ logger?.warn?.(`memory-core: 全局热键 ${ev.hotkey} 被占用,换一个键或关掉这个功能`)
274
+ }
275
+ } catch {
276
+ /* 热键事件失败不影响主流程 */
277
+ }
278
+ },
279
+ })
280
+ if (hotkeyConfig.enabled) {
281
+ ctx.effect(() => {
282
+ const r = hotkey.start()
283
+ diag('hotkey: ' + (r.ok ? `已注册 ${hotkeyConfig.key}(${hotkeyConfig.action})` : `未注册:${r.reason}`))
284
+ return () => hotkey.stop()
285
+ })
286
+ } else {
287
+ diag('hotkey: 未启用(config.hotkey.enabled=true 或 mem_hotkey 打开)')
288
+ }
289
+
195
290
  // QQ 机器人桥(OneBot v11 WebSocket 客户端):只有显式开 enabled 才连
196
291
  const qq = store ? createQqBridge({ store, config: config.qq ?? {}, log: (m) => diag(m) }) : null
197
292
  if (qq && qq.enabled) {
@@ -329,6 +424,31 @@ export function apply(ctx, config = {}) {
329
424
  // 服务化是增值功能,不能因为它失败导致工具不可用。
330
425
 
331
426
  const host = new ToolHost(ctx)
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
+ }
332
452
  const registry = store ? buildRegistry(store, host) : null
333
453
  host.definitions = registry
334
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
+ }
@@ -0,0 +1,74 @@
1
+ # hotkey-helper.ps1 -- registers one global hotkey and prints PRESS on each hit.
2
+ # Zero dependency: RegisterHotKey + thread message loop.
3
+ # Usage: powershell -NoProfile -ExecutionPolicy Bypass -File hotkey-helper.ps1 -Key V -Mods 1
4
+ param(
5
+ [Parameter(Mandatory = $true)][string]$Key,
6
+ [int]$Mods = 1,
7
+ [int]$Vk = 0,
8
+ [string]$Action = 'none'
9
+ )
10
+
11
+ $ErrorActionPreference = 'Stop'
12
+
13
+ Add-Type @"
14
+ using System;
15
+ using System.Runtime.InteropServices;
16
+ public class HKHelper {
17
+ [DllImport("user32.dll", SetLastError=true)] public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
18
+ [DllImport("user32.dll")] public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
19
+ [DllImport("user32.dll")] public static extern int GetMessage(out MSG lpMsg, IntPtr hWnd, uint min, uint max);
20
+ [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
21
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int x; public int y; }
22
+ [StructLayout(LayoutKind.Sequential)] public struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam; public IntPtr lParam; public uint time; public POINT pt; }
23
+ }
24
+ "@
25
+
26
+ function Invoke-Action {
27
+ param([string]$Name)
28
+ if ($Name -eq 'dictation') {
29
+ # Win+H:唤起 Windows 语音听写。
30
+ # 注意按键序列必须成对:LWIN↓ H↓ H↑ LWIN↑,LWIN 是扩展键(EXTENDEDKEY=1,KEYUP=2)。
31
+ # 旧写法多按了一次 LWIN↓,会把 Win 键留在按下状态,后续组合键全部失灵。
32
+ [HKHelper]::keybd_event(0x5B, 0, 1, [UIntPtr]::Zero)
33
+ Start-Sleep -Milliseconds 50
34
+ [HKHelper]::keybd_event(0x48, 0, 0, [UIntPtr]::Zero)
35
+ Start-Sleep -Milliseconds 50
36
+ [HKHelper]::keybd_event(0x48, 0, 2, [UIntPtr]::Zero)
37
+ Start-Sleep -Milliseconds 30
38
+ [HKHelper]::keybd_event(0x5B, 0, 3, [UIntPtr]::Zero)
39
+ }
40
+ }
41
+
42
+ $code = 0
43
+ if ($Vk -gt 0) {
44
+ $code = $Vk
45
+ } elseif ($Key.Length -eq 1) {
46
+ $code = [int][char]([string]$Key).ToUpper()
47
+ } else {
48
+ if ($Key -match '^F(\d{1,2})$') {
49
+ $n = [int]$Matches[1]
50
+ if ($n -ge 1 -and $n -le 24) { $code = 0x70 + ($n - 1) }
51
+ }
52
+ }
53
+
54
+ if ($code -eq 0) { Write-Output "BADKEY"; exit 2 }
55
+
56
+ if (-not [HKHelper]::RegisterHotKey([IntPtr]::Zero, 1, [uint32]$Mods, [uint32]$code)) {
57
+ Write-Output "REGFAIL"
58
+ exit 3
59
+ }
60
+
61
+ Write-Output "READY"
62
+ [Console]::Out.Flush()
63
+
64
+ $msg = New-Object HKHelper+MSG
65
+ while ($true) {
66
+ $ret = [HKHelper]::GetMessage([ref]$msg, [IntPtr]::Zero, 0, 0)
67
+ if ($ret -eq 0 -or $ret -eq -1) { break }
68
+ if ($msg.message -eq 0x0312) {
69
+ Write-Output "PRESS"
70
+ [Console]::Out.Flush()
71
+ if ($Action -ne 'none') { Invoke-Action -Name $Action }
72
+ }
73
+ }
74
+ [void][HKHelper]::UnregisterHotKey([IntPtr]::Zero, 1)