dsh-notify-say 0.4.69 → 0.4.72

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.
@@ -1,421 +1,429 @@
1
- /**
2
- * dsh-notify-say 的可持久配置层(host 半侧,无外部依赖)。
3
- *
4
- * ## 为什么需要它
5
- *
6
- * 本插件的配置原本只来自 `cordis.patch.yml`(profile 补丁层)。改一个音量都要
7
- * 编辑 YAML 再重启宿主,成本太高;而 GUI/CLI 又**绝不能写** profile 补丁层
8
- * —— 同族的 `dsh-model-seat-favorites` 在源码注释里把这条写成了硬规则:
9
- *
10
- * > the profile patch layer is the one file this project must not start writing to.
11
- *
12
- * 所以本模块拥有**恰好一个文件**:`$DSH_HOME/storages/dsh-notify-say/config.json`。
13
- * 其它任何文件(凭据、patch、别的插件数据)一概不读不写。
14
- *
15
- * ## 三层优先级(后覆盖前)
16
- *
17
- * 1. 内置 DEFAULTS(lib/index.js 的 DEFAULTS)
18
- * 2. `cordis.patch.yml` 传入的 config ← 用户手写的静态默认值
19
- * 3. 本文件 `storages/.../config.json` ← GUI/CLI 运行时改的值
20
- *
21
- * 这样职责分离:patch 层是「出厂/手写默认」,storages 层是「运行时偏好」。
22
- * 两者不打架,也不产生「改了 GUI 但 patch 里还是旧值」的分裂。
23
- *
24
- * ## fail-closed 契约
25
- *
26
- * - 每个方法**永不抛异常**,失败一律返回 `{ ok: false, reason }`;
27
- * - 磁盘上的文档格式不对 → 报 `corrupt` 且**不回写**(保留用户原文件,便于人工救);
28
- * - 写入前先做形状校验,调用方的 bug 不会把文件写成半截文档;
29
- * - 未知键**丢弃**(白名单),防止 GUI 传进来污染配置文件。
30
- */
31
-
32
- import { readFileSync, writeFileSync, mkdirSync, renameSync, existsSync, unlinkSync } from 'node:fs';
33
- import { join, dirname } from 'node:path';
34
-
35
- /** 相对 `$DSH_HOME` 的持久文件路径(本插件唯一拥有的文件)。 */
36
- export const CONFIG_RELATIVE_PATH = 'storages/dsh-notify-say/config.json';
37
-
38
- /** 写入文档的 schema 版本。 */
39
- export const CONFIG_VERSION = 1;
40
-
41
- /**
42
- * 允许持久化的键(白名单)与其值校验器。
43
- *
44
- * 只收「用户在 GUI/CLI 里真会改」的东西。刻意**不收** debounce / idleGateTimeout
45
- * 这类内部节流值 —— 它们改错了只会让人困惑,且不属于界面想解决的问题。
46
- */
47
- const BOOL_KEYS = ['voice', 'notifyOnComplete', 'notifyOnError', 'notifyOnBlocked',
48
- 'notifyOnAborted', 'notifyOnApproval', 'notifyOnQuestion', 'subagents', 'idleGate',
49
- // v0.4.2
50
- 'showToast', 'jumpWhenBackground', 'jumpWhenForeground', 'multiJumpRule',
51
- // v0.4.11:devReload。GUI 早就有这个开关,但白名单里没有 →
52
- // 保存时被 sanitize 当未知键丢弃,返回 nothing-to-write(实测踩到)。
53
- 'devReload',
54
- // v0.4.16:自定义音频是否标准化(默认关:尊重用户原文件的响度)。
55
- 'normalizeCustomAudio'];
56
-
57
- /** 合法音源 id(与 lib/audio-source.js 的 AUDIO_SOURCES 保持一致)。 */
58
- const AUDIO_SOURCES = ['tts', 'bundled', 'system', 'custom', 'none'];
59
-
60
- /**
61
- * 校验自定义音频路径:必须是**绝对路径** + 合法扩展名。
62
- *
63
- * 拒绝相对路径的原因:播放进程的 cwd 不确定,相对路径会随启动方式漂移,
64
- * 属于"看起来能用、实际随机失败"的坑(与 lib/audio-source.js 同口径)。
65
- *
66
- * @param {any} v
67
- * @returns {string|undefined} 合法则返回原值,否则 undefined(表示丢弃)
68
- */
69
- function absAudioPath(v) {
70
- if (typeof v !== 'string') return undefined;
71
- const p = v.trim();
72
- if (!p || p.length > 512) return undefined;
73
- const isAbs = /^[a-zA-Z]:[\\/]/.test(p) || /^\\\\/.test(p);
74
- if (!isAbs) return undefined;
75
- // 拒绝设备命名空间前缀(\\?\ / \\.\),它们能绕开路径规范化
76
- if (/^\\\\[?.]\\/.test(p)) return undefined;
77
- if (!/\.(wav|mp3|m4a|flac|ogg)$/i.test(p)) return undefined;
78
- return p;
79
- }
80
-
81
- const RULES = {
82
- voiceMode: (v) => (v === 'fixed' || v === 'random' ? v : undefined),
83
- voiceName: (v) => (typeof v === 'string' && /^\w[\w-]*$/.test(v) ? v : undefined),
84
- volume: (v) => {
85
- const n = Number(v);
86
- return Number.isFinite(n) && n >= 0 && n <= 100 ? Math.round(n) : undefined;
87
- },
88
- // v0.4.2:音源与 TTS
89
- audioSource: (v) => (typeof v === 'string' && AUDIO_SOURCES.includes(v) ? v : undefined),
90
- // v0.4.34 日志级别:只有 info / debug 两个值,其余拒绝(回落到默认)。
91
- // 这里必须显式校验:logLevel 会决定「要不要把用户台词写进日志」,
92
- // 拼错一个字母就静默退回 info 是安全的,但反过来(错值被当 debug)不安全。
93
- logLevel: (v) => (v === 'info' || v === 'debug' ? v : undefined),
94
- // 发音人名可能含空格(如 "Microsoft Huihui Desktop"),只做长度与类型校验
95
- ttsVoice: (v) => (typeof v === 'string' && v.length <= 120 ? v : undefined),
96
- ttsRate: (v) => {
97
- const n = Number(v);
98
- return Number.isFinite(n) && n >= -10 && n <= 10 ? Math.round(n) : undefined;
99
- },
100
- // v0.4.16:语音包数字增益(1.0 = 原样,2.0 = 放大一倍)。
101
- // 素材峰值中位仅 40.4%,而 MCI 音量上限只有 1.0 倍,必须靠数字增益补。
102
- voiceGain: (v) => {
103
- const n = Number(v);
104
- if (!Number.isFinite(n)) return undefined;
105
- if (n < 1.0 || n > 4.0) return undefined;
106
- return Math.round(n * 10) / 10;
107
- },
108
- // v0.4.4:自定义音频(按事件一个绝对路径)
109
- //
110
- // 为什么按事件分开:用户可能想让"完成"放自己的音乐、"失败"放另一段。
111
- // 存储形态是扁平的两个键(customFileDone / customFileFail …),
112
- // 因为 config-store 的白名单只认扁平的标量键;audio-source 那边再拼成
113
- // `customFiles: { done: ... }` 供读取逻辑用。
114
- customFileDone: (v) => absAudioPath(v),
115
- customFileFail: (v) => absAudioPath(v),
116
- customFileQuestion: (v) => absAudioPath(v),
117
- customFileApproval: (v) => absAudioPath(v),
118
- customFileBlocked: (v) => absAudioPath(v),
119
-
120
- // v0.4.5:按事件覆盖音源(高级功能)
121
- //
122
- // 用户可能想让「完成」听日语语音包、而「失败」听系统警告音。
123
- // 存成扁平键(kindSourceFail = 'system'),因为白名单只认标量;
124
- // 空串表示"跟随全局默认"。
125
- kindSourceDone: (v) => kindSourceOf(v),
126
- kindSourceFail: (v) => kindSourceOf(v),
127
- kindSourceQuestion: (v) => kindSourceOf(v),
128
- kindSourceApproval: (v) => kindSourceOf(v),
129
- kindSourceBlocked: (v) => kindSourceOf(v),
130
-
131
- // v0.4.7:冷却(用户明确要求可调)
132
- //
133
- // 原注释说"刻意不收 debounce —— 改错了只会让人困惑"。但用户 2026-10-17
134
- // 明确要求:"同一会话的冷却我们可以给它关了,甚至可以把不同会话的冷却加上"。
135
- // 需求优先:两类人诉求相反,必须让用户自己调。
136
- // 范围限制在 0..3600 秒(1 小时封顶),0 表示关闭。
137
- debounceSeconds: (v) => {
138
- const n = Number(v);
139
- return Number.isFinite(n) && n >= 0 && n <= 3600 ? Math.round(n) : undefined;
140
- },
141
- globalCooldownSeconds: (v) => {
142
- const n = Number(v);
143
- return Number.isFinite(n) && n >= 0 && n <= 3600 ? Math.round(n) : undefined;
144
- },
145
-
146
- // v0.4.8:TTS 自定义台词(每种事件一段,空串 = 用内置台词库)
147
- //
148
- // 长度上限 60 字:SAPI 念 60 字约 5 秒,符合"一句话提醒"的定位。
149
- // 再长会让用户"点了完成、十秒后才出声",也容易被命令行长度上限截断。
150
- ttsTextDone: (v) => cleanTtsText(v),
151
- ttsTextFail: (v) => cleanTtsText(v),
152
- ttsTextQuestion: (v) => cleanTtsText(v),
153
- ttsTextApproval: (v) => cleanTtsText(v),
154
- ttsTextBlocked: (v) => cleanTtsText(v),
155
- };
156
-
157
- // ── v0.4.9:每种音源的参数都按事件可调 ────────────────────────────────────
158
- //
159
- // 用户 2026-10-17 指出:高级区每行只选了音源类型,但选完之后
160
- // **念什么话、什么声音、什么音效** 都得回上面用全局的,不合逻辑。
161
- // 而且不只 TTS —— 语音包、系统音效各有自己的参数,都要能按事件设。
162
- //
163
- // 参数矩阵:
164
- // tts → 发音人 ttsVoiceK + 语速 ttsRateK + 台词 ttsTextK(已有)
165
- // bundled → 音色模式 kindVoiceModeK + 音色名 kindVoiceNameK
166
- // system → 系统音效 kindSystemSoundK
167
- // custom → 文件 customFileK(已有)
168
- //
169
- // 命名规则:`kind<Param><Kind>`(如 kindSystemSoundFail),
170
- // 这样一眼能看出"是按事件的覆盖",也不会与全局键(ttsVoice/voiceName)混淆。
171
- // 空串一律表示"跟随全局"。
172
- const KINDS = ['Done', 'Fail', 'Question', 'Approval', 'Blocked'];
173
-
174
- /** 合法系统音效名(与 lib/audio-source.js 的 SYSTEM_SOUNDS 一致)。 */
175
- const SYSTEM_SOUNDS = ['Asterisk', 'Beep', 'Exclamation', 'Hand', 'Question'];
176
-
177
- for (const k of KINDS) {
178
- // 发音人:与全局 ttsVoice 同口径(允许空格,如 "Microsoft Huihui Desktop")
179
- RULES['kindTtsVoice' + k] = (v) => (typeof v === 'string' && v.length <= 120 ? v : undefined);
180
- // 语速:-10..10,空串表示跟随全局
181
- RULES['kindTtsRate' + k] = (v) => {
182
- if (v === '' || v === null) return '';
183
- const n = Number(v);
184
- return Number.isFinite(n) && n >= -10 && n <= 10 ? Math.round(n) : undefined;
185
- };
186
- // 音色模式:fixed | random | 空(跟随全局)
187
- RULES['kindVoiceMode' + k] = (v) => {
188
- if (v === '') return '';
189
- return (v === 'fixed' || v === 'random') ? v : undefined;
190
- };
191
- // 音色名:与全局 voiceName 同口径
192
- RULES['kindVoiceName' + k] = (v) => {
193
- if (v === '') return '';
194
- return (typeof v === 'string' && /^\w[\w-]*$/.test(v)) ? v : undefined;
195
- };
196
- // 系统音效名:合法值或空
197
- RULES['kindSystemSound' + k] = (v) => {
198
- if (v === '') return '';
199
- return (typeof v === 'string' && SYSTEM_SOUNDS.includes(v)) ? v : undefined;
200
- };
201
- }
202
-
203
- /**
204
- * 规整用户自定义 TTS 台词:去掉换行/控制字符、压空白、限长。
205
- *
206
- * 与 lib/tts-lines.js 的 sanitizeTtsText 同口径(那里也有一份,
207
- * 因为它在浏览器端也要能独立工作;两处都由测试覆盖)。
208
- *
209
- * @param {any} v
210
- * @returns {string|undefined} 空串表示"清除自定义";非字符串返回 undefined(丢弃)
211
- */
212
- function cleanTtsText(v) {
213
- if (typeof v !== 'string') return undefined;
214
- const s = v.replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ').replace(/\s+/g, ' ').trim();
215
- if (!s) return '';
216
- return s.length > 60 ? s.slice(0, 60).trim() : s;
217
- }
218
-
219
- /**
220
- * 校验"某事件的音源覆盖":合法音源 id 或空串(表示跟随默认)。
221
- * @param {any} v
222
- * @returns {string|undefined}
223
- */
224
- function kindSourceOf(v) {
225
- if (typeof v !== 'string') return undefined;
226
- const s = v.trim().toLowerCase();
227
- if (!s) return ''; // 空 = 清除覆盖
228
- return AUDIO_SOURCES.includes(s) ? s : undefined;
229
- }
230
-
231
- for (const k of BOOL_KEYS) RULES[k] = (v) => (typeof v === 'boolean' ? v : undefined);
232
-
233
- /** 所有可持久键(供 CLI/GUI 列出)。 */
234
- export const CONFIG_KEYS = Object.keys(RULES);
235
-
236
- /**
237
- * 解析 `$DSH_HOME`(与官方插件同款取法)。
238
- * @param {object} [env] 环境包,默认 `process.env`
239
- * @returns {string} 归一化后的绝对路径;取不到时返回空串
240
- */
241
- export function safeHome(env) {
242
- try {
243
- const src = env != null ? env : (typeof process !== 'undefined' ? process.env : undefined);
244
- const raw = src != null ? src.DSH_HOME : '';
245
- return typeof raw === 'string' && raw.length > 0 ? raw.replace(/[\\/]+$/, '') : '';
246
- } catch {
247
- return '';
248
- }
249
- }
250
-
251
- /**
252
- * 计算持久文件的绝对路径。
253
- * @param {object} [env]
254
- * @returns {string} 绝对路径;`$DSH_HOME` 缺失时返回空串
255
- */
256
- export function configPath(env) {
257
- const home = safeHome(env);
258
- if (!home) return '';
259
- return join(home, CONFIG_RELATIVE_PATH);
260
- }
261
-
262
- /**
263
- * 把任意输入收敛成合法配置片段。
264
- *
265
- * 未知键与非法值一律**丢弃**(不是报错),这样 GUI 传错一个字段不会让整次保存失败,
266
- * 也不会让脏数据落盘。
267
- *
268
- * @param {object} raw
269
- * @returns {{ ok: boolean, value?: object, dropped?: string[] }}
270
- */
271
- export function sanitize(raw) {
272
- if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {
273
- return { ok: false, value: {}, dropped: [] };
274
- }
275
- const out = {};
276
- const dropped = [];
277
- for (const [k, v] of Object.entries(raw)) {
278
- const rule = RULES[k];
279
- if (!rule) { dropped.push(k); continue; }
280
- const got = rule(v);
281
- if (got === undefined) { dropped.push(k); continue; }
282
- out[k] = got;
283
- }
284
- return { ok: true, value: out, dropped };
285
- }
286
-
287
- /**
288
- * 读取持久配置。文件不存在视为「没有运行时偏好」(不是错误)。
289
- *
290
- * @param {object} [env]
291
- * @returns {{ ok: boolean, value: object, reason?: string }}
292
- * - `ok:true, value:{}` 文件不存在或为空 → 调用方用 patch 默认值
293
- * - `ok:true, value:{...}` 读到并校验通过
294
- * - `ok:false, reason:'corrupt'` 文件在但解析失败/形状不对 → **不回写**
295
- * - `ok:false, reason:'read:...'` 读失败
296
- */
297
- export function readConfig(env) {
298
- const p = configPath(env);
299
- if (!p) return { ok: false, value: {}, reason: 'no-home' };
300
- let text;
301
- try {
302
- if (!existsSync(p)) return { ok: true, value: {} };
303
- text = readFileSync(p, 'utf8');
304
- } catch (ex) {
305
- return { ok: false, value: {}, reason: 'read:' + String(ex && ex.message ? ex.message : ex) };
306
- }
307
- if (!text.trim()) return { ok: true, value: {} };
308
- let doc;
309
- try {
310
- doc = JSON.parse(text);
311
- } catch {
312
- return { ok: false, value: {}, reason: 'corrupt' };
313
- }
314
- if (doc == null || typeof doc !== 'object' || Array.isArray(doc)) {
315
- return { ok: false, value: {}, reason: 'corrupt' };
316
- }
317
- if (doc.version !== CONFIG_VERSION) {
318
- // 版本不认识:当作 corrupt,不覆盖(可能是别的版本写的,人工处理)
319
- return { ok: false, value: {}, reason: 'corrupt' };
320
- }
321
- const values = doc.values;
322
- if (values == null || typeof values !== 'object' || Array.isArray(values)) {
323
- return { ok: false, value: {}, reason: 'corrupt' };
324
- }
325
- const s = sanitize(values);
326
- return { ok: true, value: s.value };
327
- }
328
-
329
- /**
330
- * 原子写入持久配置:先写 `.tmp` 再 rename,避免半截文件。
331
- *
332
- * @param {object} patch 要合并进去的键值(只写白名单内的)
333
- * @param {object} [env]
334
- * @returns {{ ok: boolean, value?: object, written?: string[], reason?: string }}
335
- */
336
- export function writeConfig(patch, env) {
337
- const p = configPath(env);
338
- if (!p) return { ok: false, reason: 'no-home' };
339
- const s = sanitize(patch);
340
- if (!s.ok) return { ok: false, reason: 'bad-input' };
341
- if (Object.keys(s.value).length === 0) {
342
- return { ok: false, reason: 'nothing-to-write', dropped: s.dropped };
343
- }
344
-
345
- // 读现有值再合并(读失败时不静默覆盖用户的坏文件)
346
- const cur = readConfig(env);
347
- if (cur.ok === false && cur.reason === 'corrupt') {
348
- return { ok: false, reason: 'corrupt' };
349
- }
350
- const merged = { ...(cur.ok ? cur.value : {}), ...s.value };
351
- const doc = { version: CONFIG_VERSION, values: merged };
352
-
353
- const tmp = p + '.tmp';
354
- try {
355
- mkdirSync(dirname(p), { recursive: true });
356
- writeFileSync(tmp, JSON.stringify(doc, null, 2) + '\n', 'utf8');
357
- renameSync(tmp, p);
358
- } catch (ex) {
359
- try { if (existsSync(tmp)) unlinkSync(tmp); } catch { /* best effort */ }
360
- return { ok: false, reason: 'write:' + String(ex && ex.message ? ex.message : ex) };
361
- }
362
- return { ok: true, value: merged, written: Object.keys(s.value), path: p };
363
- }
364
-
365
- /**
366
- * 把「patch 层配置」与「运行时偏好」合并成最终生效配置。
367
- *
368
- * 优先级:`fileValues` 覆盖 `patchConfig`。两者都不含的键由调用方的 DEFAULTS 兜底。
369
- *
370
- * @param {object} patchConfig `cordis.patch.yml` 传来的 config(可能含 camelCase 键)
371
- * @param {object} fileValues `readConfig().value`
372
- * @returns {object} 合并后的原始配置(交给 normalizeConfig)
373
- */
374
- export function mergeConfig(patchConfig, fileValues) {
375
- const base = patchConfig != null && typeof patchConfig === 'object' ? patchConfig : {};
376
- const over = fileValues != null && typeof fileValues === 'object' ? fileValues : {};
377
- return { ...base, ...over };
378
- }
379
-
380
- /**
381
- * 把 patch 用的 `*Seconds` 键转成归一化后的毫秒值说明(仅供 CLI/GUI 展示)。
382
- * 本模块不参与这两项的持久化,故只做只读呈现。
383
- *
384
- * @param {object} cfg normalizeConfig 的输出
385
- * @returns {object} 便于人读的摘要
386
- */
387
- export function describe(cfg) {
388
- return {
389
- voice: cfg.voice,
390
- voiceMode: cfg.voiceMode,
391
- voiceName: cfg.voiceName,
392
- volume: cfg.volume,
393
- notifyOnComplete: cfg.notifyOnComplete,
394
- notifyOnError: cfg.notifyOnError,
395
- notifyOnBlocked: cfg.notifyOnBlocked,
396
- notifyOnAborted: cfg.notifyOnAborted,
397
- notifyOnApproval: cfg.notifyOnApproval,
398
- notifyOnQuestion: cfg.notifyOnQuestion,
399
- subagents: cfg.subagents,
400
- idleGate: cfg.idleGate,
401
- // v0.4.2+:这些也要进摘要,否则改了它们"配置变更签名"不变,
402
- // 日志就不会打印新配置,排查时看不出变化。
403
- audioSource: cfg.audioSource,
404
- showToast: cfg.showToast,
405
- ttsVoice: cfg.ttsVoice,
406
- ttsRate: cfg.ttsRate,
407
- jumpWhenBackground: cfg.jumpWhenBackground,
408
- jumpWhenForeground: cfg.jumpWhenForeground,
409
- multiJumpRule: cfg.multiJumpRule,
410
- devReload: cfg.devReload,
411
- logLevel: cfg.logLevel,
412
- audioSourceByKind: cfg.audioSourceByKind,
413
- ttsTexts: cfg.ttsTexts,
414
- kindSystemSound: cfg.kindSystemSound,
415
- kindVoiceName: cfg.kindVoiceName,
416
- customFiles: cfg.customFiles,
417
- debounceSeconds: Math.round((Number(cfg.debounceMs) || 0) / 1000),
418
- globalCooldownSeconds: Math.round((Number(cfg.globalCooldownMs) || 0) / 1000),
419
- idleGateTimeoutSeconds: Math.round((Number(cfg.idleGateTimeoutMs) || 0) / 1000),
420
- };
421
- }
1
+ /**
2
+ * dsh-notify-say 的可持久配置层(host 半侧,无外部依赖)。
3
+ *
4
+ * ## 为什么需要它
5
+ *
6
+ * 本插件的配置原本只来自 `cordis.patch.yml`(profile 补丁层)。改一个音量都要
7
+ * 编辑 YAML 再重启宿主,成本太高;而 GUI/CLI 又**绝不能写** profile 补丁层
8
+ * —— 同族的 `dsh-model-seat-favorites` 在源码注释里把这条写成了硬规则:
9
+ *
10
+ * > the profile patch layer is the one file this project must not start writing to.
11
+ *
12
+ * 所以本模块拥有**恰好一个文件**:`$DSH_HOME/storages/dsh-notify-say/config.json`。
13
+ * 其它任何文件(凭据、patch、别的插件数据)一概不读不写。
14
+ *
15
+ * ## 三层优先级(后覆盖前)
16
+ *
17
+ * 1. 内置 DEFAULTS(lib/index.js 的 DEFAULTS)
18
+ * 2. `cordis.patch.yml` 传入的 config ← 用户手写的静态默认值
19
+ * 3. 本文件 `storages/.../config.json` ← GUI/CLI 运行时改的值
20
+ *
21
+ * 这样职责分离:patch 层是「出厂/手写默认」,storages 层是「运行时偏好」。
22
+ * 两者不打架,也不产生「改了 GUI 但 patch 里还是旧值」的分裂。
23
+ *
24
+ * ## fail-closed 契约
25
+ *
26
+ * - 每个方法**永不抛异常**,失败一律返回 `{ ok: false, reason }`;
27
+ * - 磁盘上的文档格式不对 → 报 `corrupt` 且**不回写**(保留用户原文件,便于人工救);
28
+ * - 写入前先做形状校验,调用方的 bug 不会把文件写成半截文档;
29
+ * - 未知键**丢弃**(白名单),防止 GUI 传进来污染配置文件。
30
+ */
31
+
32
+ import { readFileSync, writeFileSync, mkdirSync, renameSync, existsSync, unlinkSync } from 'node:fs';
33
+ import { join, dirname } from 'node:path';
34
+
35
+ /** 相对 `$DSH_HOME` 的持久文件路径(本插件唯一拥有的文件)。 */
36
+ export const CONFIG_RELATIVE_PATH = 'storages/dsh-notify-say/config.json';
37
+
38
+ /** 写入文档的 schema 版本。 */
39
+ export const CONFIG_VERSION = 1;
40
+
41
+ /**
42
+ * 允许持久化的键(白名单)与其值校验器。
43
+ *
44
+ * 只收「用户在 GUI/CLI 里真会改」的东西。刻意**不收** debounce / idleGateTimeout
45
+ * 这类内部节流值 —— 它们改错了只会让人困惑,且不属于界面想解决的问题。
46
+ */
47
+ const BOOL_KEYS = ['voice', 'notifyOnComplete', 'notifyOnError', 'notifyOnBlocked',
48
+ 'notifyOnAborted', 'notifyOnApproval', 'notifyOnQuestion', 'subagents', 'idleGate',
49
+ // v0.4.2
50
+ 'showToast', 'jumpWhenBackground', 'jumpWhenForeground',
51
+ // v0.4.68:子代理错误 / 长度上限 / Toast 精准跳转
52
+ 'notifyOnSubagentError', 'notifyOnMaxTokens', 'toastJumpSession',
53
+ // ⚠️ multiJumpRule 是**字符串**(clicked/earliest/latest/none),
54
+ // 不能放进 BOOL_KEYS —— 那会让 sanitize 按 boolean 校验并丢弃它。
55
+ // 它的校验在 RULES 里单独给出。
56
+ // v0.4.11:devReload。GUI 早就有这个开关,但白名单里没有 →
57
+ // 保存时被 sanitize 当未知键丢弃,返回 nothing-to-write(实测踩到)。
58
+ 'devReload',
59
+ // v0.4.16:自定义音频是否标准化(默认关:尊重用户原文件的响度)。
60
+ 'normalizeCustomAudio'];
61
+
62
+ /** 合法音源 id(与 lib/audio-source.js 的 AUDIO_SOURCES 保持一致)。 */
63
+ const AUDIO_SOURCES = ['tts', 'bundled', 'system', 'custom', 'none'];
64
+
65
+ /**
66
+ * 校验自定义音频路径:必须是**绝对路径** + 合法扩展名。
67
+ *
68
+ * 拒绝相对路径的原因:播放进程的 cwd 不确定,相对路径会随启动方式漂移,
69
+ * 属于"看起来能用、实际随机失败"的坑(与 lib/audio-source.js 同口径)。
70
+ *
71
+ * @param {any} v
72
+ * @returns {string|undefined} 合法则返回原值,否则 undefined(表示丢弃)
73
+ */
74
+ function absAudioPath(v) {
75
+ if (typeof v !== 'string') return undefined;
76
+ const p = v.trim();
77
+ if (!p || p.length > 512) return undefined;
78
+ const isAbs = /^[a-zA-Z]:[\\/]/.test(p) || /^\\\\/.test(p);
79
+ if (!isAbs) return undefined;
80
+ // 拒绝设备命名空间前缀(\\?\ / \\.\),它们能绕开路径规范化
81
+ if (/^\\\\[?.]\\/.test(p)) return undefined;
82
+ if (!/\.(wav|mp3|m4a|flac|ogg)$/i.test(p)) return undefined;
83
+ return p;
84
+ }
85
+
86
+ const RULES = {
87
+ // v0.4.71:multiJumpRule 是字符串枚举,必须在 RULES 里单独校验。
88
+ // 原先它被错放进 BOOL_KEYS(那是给 boolean 用的),保存时会被当未知类型丢弃。
89
+ multiJumpRule: (v) => (['clicked', 'earliest', 'latest', 'none'].includes(v) ? v : undefined),
90
+ voiceMode: (v) => (v === 'fixed' || v === 'random' ? v : undefined),
91
+ voiceName: (v) => (typeof v === 'string' && /^\w[\w-]*$/.test(v) ? v : undefined),
92
+ volume: (v) => {
93
+ const n = Number(v);
94
+ return Number.isFinite(n) && n >= 0 && n <= 100 ? Math.round(n) : undefined;
95
+ },
96
+ // v0.4.2:音源与 TTS
97
+ audioSource: (v) => (typeof v === 'string' && AUDIO_SOURCES.includes(v) ? v : undefined),
98
+ // v0.4.34 日志级别:只有 info / debug 两个值,其余拒绝(回落到默认)。
99
+ // 这里必须显式校验:logLevel 会决定「要不要把用户台词写进日志」,
100
+ // 拼错一个字母就静默退回 info 是安全的,但反过来(错值被当 debug)不安全。
101
+ logLevel: (v) => (v === 'info' || v === 'debug' ? v : undefined),
102
+ // 发音人名可能含空格(如 "Microsoft Huihui Desktop"),只做长度与类型校验
103
+ ttsVoice: (v) => (typeof v === 'string' && v.length <= 120 ? v : undefined),
104
+ ttsRate: (v) => {
105
+ const n = Number(v);
106
+ return Number.isFinite(n) && n >= -10 && n <= 10 ? Math.round(n) : undefined;
107
+ },
108
+ // v0.4.16:语音包数字增益(1.0 = 原样,2.0 = 放大一倍)。
109
+ // 素材峰值中位仅 40.4%,而 MCI 音量上限只有 1.0 倍,必须靠数字增益补。
110
+ voiceGain: (v) => {
111
+ const n = Number(v);
112
+ if (!Number.isFinite(n)) return undefined;
113
+ if (n < 1.0 || n > 4.0) return undefined;
114
+ return Math.round(n * 10) / 10;
115
+ },
116
+ // v0.4.4:自定义音频(按事件一个绝对路径)
117
+ //
118
+ // 为什么按事件分开:用户可能想让"完成"放自己的音乐、"失败"放另一段。
119
+ // 存储形态是扁平的两个键(customFileDone / customFileFail …),
120
+ // 因为 config-store 的白名单只认扁平的标量键;audio-source 那边再拼成
121
+ // `customFiles: { done: ... }` 供读取逻辑用。
122
+ customFileDone: (v) => absAudioPath(v),
123
+ customFileFail: (v) => absAudioPath(v),
124
+ customFileQuestion: (v) => absAudioPath(v),
125
+ customFileApproval: (v) => absAudioPath(v),
126
+ customFileBlocked: (v) => absAudioPath(v),
127
+
128
+ // v0.4.5:按事件覆盖音源(高级功能)
129
+ //
130
+ // 用户可能想让「完成」听日语语音包、而「失败」听系统警告音。
131
+ // 存成扁平键(kindSourceFail = 'system'),因为白名单只认标量;
132
+ // 空串表示"跟随全局默认"。
133
+ kindSourceDone: (v) => kindSourceOf(v),
134
+ kindSourceFail: (v) => kindSourceOf(v),
135
+ kindSourceQuestion: (v) => kindSourceOf(v),
136
+ kindSourceApproval: (v) => kindSourceOf(v),
137
+ kindSourceBlocked: (v) => kindSourceOf(v),
138
+
139
+ // v0.4.7:冷却(用户明确要求可调)
140
+ //
141
+ // 原注释说"刻意不收 debounce —— 改错了只会让人困惑"。但用户 2026-10-17
142
+ // 明确要求:"同一会话的冷却我们可以给它关了,甚至可以把不同会话的冷却加上"。
143
+ // 需求优先:两类人诉求相反,必须让用户自己调。
144
+ // 范围限制在 0..3600 秒(1 小时封顶),0 表示关闭。
145
+ debounceSeconds: (v) => {
146
+ const n = Number(v);
147
+ return Number.isFinite(n) && n >= 0 && n <= 3600 ? Math.round(n) : undefined;
148
+ },
149
+ globalCooldownSeconds: (v) => {
150
+ const n = Number(v);
151
+ return Number.isFinite(n) && n >= 0 && n <= 3600 ? Math.round(n) : undefined;
152
+ },
153
+
154
+ // v0.4.8:TTS 自定义台词(每种事件一段,空串 = 用内置台词库)
155
+ //
156
+ // 长度上限 60 字:SAPI 念 60 字约 5 秒,符合"一句话提醒"的定位。
157
+ // 再长会让用户"点了完成、十秒后才出声",也容易被命令行长度上限截断。
158
+ ttsTextDone: (v) => cleanTtsText(v),
159
+ ttsTextFail: (v) => cleanTtsText(v),
160
+ ttsTextQuestion: (v) => cleanTtsText(v),
161
+ ttsTextApproval: (v) => cleanTtsText(v),
162
+ ttsTextBlocked: (v) => cleanTtsText(v),
163
+ };
164
+
165
+ // ── v0.4.9:每种音源的参数都按事件可调 ────────────────────────────────────
166
+ //
167
+ // 用户 2026-10-17 指出:高级区每行只选了音源类型,但选完之后
168
+ // **念什么话、什么声音、什么音效** 都得回上面用全局的,不合逻辑。
169
+ // 而且不只 TTS —— 语音包、系统音效各有自己的参数,都要能按事件设。
170
+ //
171
+ // 参数矩阵:
172
+ // tts → 发音人 ttsVoiceK + 语速 ttsRateK + 台词 ttsTextK(已有)
173
+ // bundled → 音色模式 kindVoiceModeK + 音色名 kindVoiceNameK
174
+ // system → 系统音效 kindSystemSoundK
175
+ // custom → 文件 customFileK(已有)
176
+ //
177
+ // 命名规则:`kind<Param><Kind>`(如 kindSystemSoundFail),
178
+ // 这样一眼能看出"是按事件的覆盖",也不会与全局键(ttsVoice/voiceName)混淆。
179
+ // 空串一律表示"跟随全局"。
180
+ const KINDS = ['Done', 'Fail', 'Question', 'Approval', 'Blocked'];
181
+
182
+ /** 合法系统音效名(与 lib/audio-source.js 的 SYSTEM_SOUNDS 一致)。 */
183
+ const SYSTEM_SOUNDS = ['Asterisk', 'Beep', 'Exclamation', 'Hand', 'Question'];
184
+
185
+ for (const k of KINDS) {
186
+ // 发音人:与全局 ttsVoice 同口径(允许空格,如 "Microsoft Huihui Desktop")
187
+ RULES['kindTtsVoice' + k] = (v) => (typeof v === 'string' && v.length <= 120 ? v : undefined);
188
+ // 语速:-10..10,空串表示跟随全局
189
+ RULES['kindTtsRate' + k] = (v) => {
190
+ if (v === '' || v === null) return '';
191
+ const n = Number(v);
192
+ return Number.isFinite(n) && n >= -10 && n <= 10 ? Math.round(n) : undefined;
193
+ };
194
+ // 音色模式:fixed | random | 空(跟随全局)
195
+ RULES['kindVoiceMode' + k] = (v) => {
196
+ if (v === '') return '';
197
+ return (v === 'fixed' || v === 'random') ? v : undefined;
198
+ };
199
+ // 音色名:与全局 voiceName 同口径
200
+ RULES['kindVoiceName' + k] = (v) => {
201
+ if (v === '') return '';
202
+ return (typeof v === 'string' && /^\w[\w-]*$/.test(v)) ? v : undefined;
203
+ };
204
+ // 系统音效名:合法值或空
205
+ RULES['kindSystemSound' + k] = (v) => {
206
+ if (v === '') return '';
207
+ return (typeof v === 'string' && SYSTEM_SOUNDS.includes(v)) ? v : undefined;
208
+ };
209
+ }
210
+
211
+ /**
212
+ * 规整用户自定义 TTS 台词:去掉换行/控制字符、压空白、限长。
213
+ *
214
+ * 与 lib/tts-lines.js 的 sanitizeTtsText 同口径(那里也有一份,
215
+ * 因为它在浏览器端也要能独立工作;两处都由测试覆盖)。
216
+ *
217
+ * @param {any} v
218
+ * @returns {string|undefined} 空串表示"清除自定义";非字符串返回 undefined(丢弃)
219
+ */
220
+ function cleanTtsText(v) {
221
+ if (typeof v !== 'string') return undefined;
222
+ const s = v.replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ').replace(/\s+/g, ' ').trim();
223
+ if (!s) return '';
224
+ return s.length > 60 ? s.slice(0, 60).trim() : s;
225
+ }
226
+
227
+ /**
228
+ * 校验"某事件的音源覆盖":合法音源 id 或空串(表示跟随默认)。
229
+ * @param {any} v
230
+ * @returns {string|undefined}
231
+ */
232
+ function kindSourceOf(v) {
233
+ if (typeof v !== 'string') return undefined;
234
+ const s = v.trim().toLowerCase();
235
+ if (!s) return ''; // 空 = 清除覆盖
236
+ return AUDIO_SOURCES.includes(s) ? s : undefined;
237
+ }
238
+
239
+ for (const k of BOOL_KEYS) RULES[k] = (v) => (typeof v === 'boolean' ? v : undefined);
240
+
241
+ /** 所有可持久键(供 CLI/GUI 列出)。 */
242
+ export const CONFIG_KEYS = Object.keys(RULES);
243
+
244
+ /**
245
+ * 解析 `$DSH_HOME`(与官方插件同款取法)。
246
+ * @param {object} [env] 环境包,默认 `process.env`
247
+ * @returns {string} 归一化后的绝对路径;取不到时返回空串
248
+ */
249
+ export function safeHome(env) {
250
+ try {
251
+ const src = env != null ? env : (typeof process !== 'undefined' ? process.env : undefined);
252
+ const raw = src != null ? src.DSH_HOME : '';
253
+ return typeof raw === 'string' && raw.length > 0 ? raw.replace(/[\\/]+$/, '') : '';
254
+ } catch {
255
+ return '';
256
+ }
257
+ }
258
+
259
+ /**
260
+ * 计算持久文件的绝对路径。
261
+ * @param {object} [env]
262
+ * @returns {string} 绝对路径;`$DSH_HOME` 缺失时返回空串
263
+ */
264
+ export function configPath(env) {
265
+ const home = safeHome(env);
266
+ if (!home) return '';
267
+ return join(home, CONFIG_RELATIVE_PATH);
268
+ }
269
+
270
+ /**
271
+ * 把任意输入收敛成合法配置片段。
272
+ *
273
+ * 未知键与非法值一律**丢弃**(不是报错),这样 GUI 传错一个字段不会让整次保存失败,
274
+ * 也不会让脏数据落盘。
275
+ *
276
+ * @param {object} raw
277
+ * @returns {{ ok: boolean, value?: object, dropped?: string[] }}
278
+ */
279
+ export function sanitize(raw) {
280
+ if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {
281
+ return { ok: false, value: {}, dropped: [] };
282
+ }
283
+ const out = {};
284
+ const dropped = [];
285
+ for (const [k, v] of Object.entries(raw)) {
286
+ const rule = RULES[k];
287
+ if (!rule) { dropped.push(k); continue; }
288
+ const got = rule(v);
289
+ if (got === undefined) { dropped.push(k); continue; }
290
+ out[k] = got;
291
+ }
292
+ return { ok: true, value: out, dropped };
293
+ }
294
+
295
+ /**
296
+ * 读取持久配置。文件不存在视为「没有运行时偏好」(不是错误)。
297
+ *
298
+ * @param {object} [env]
299
+ * @returns {{ ok: boolean, value: object, reason?: string }}
300
+ * - `ok:true, value:{}` 文件不存在或为空 → 调用方用 patch 默认值
301
+ * - `ok:true, value:{...}` 读到并校验通过
302
+ * - `ok:false, reason:'corrupt'` 文件在但解析失败/形状不对 → **不回写**
303
+ * - `ok:false, reason:'read:...'` 读失败
304
+ */
305
+ export function readConfig(env) {
306
+ const p = configPath(env);
307
+ if (!p) return { ok: false, value: {}, reason: 'no-home' };
308
+ let text;
309
+ try {
310
+ if (!existsSync(p)) return { ok: true, value: {} };
311
+ text = readFileSync(p, 'utf8');
312
+ } catch (ex) {
313
+ return { ok: false, value: {}, reason: 'read:' + String(ex && ex.message ? ex.message : ex) };
314
+ }
315
+ if (!text.trim()) return { ok: true, value: {} };
316
+ let doc;
317
+ try {
318
+ doc = JSON.parse(text);
319
+ } catch {
320
+ return { ok: false, value: {}, reason: 'corrupt' };
321
+ }
322
+ if (doc == null || typeof doc !== 'object' || Array.isArray(doc)) {
323
+ return { ok: false, value: {}, reason: 'corrupt' };
324
+ }
325
+ if (doc.version !== CONFIG_VERSION) {
326
+ // 版本不认识:当作 corrupt,不覆盖(可能是别的版本写的,人工处理)
327
+ return { ok: false, value: {}, reason: 'corrupt' };
328
+ }
329
+ const values = doc.values;
330
+ if (values == null || typeof values !== 'object' || Array.isArray(values)) {
331
+ return { ok: false, value: {}, reason: 'corrupt' };
332
+ }
333
+ const s = sanitize(values);
334
+ return { ok: true, value: s.value };
335
+ }
336
+
337
+ /**
338
+ * 原子写入持久配置:先写 `.tmp` 再 rename,避免半截文件。
339
+ *
340
+ * @param {object} patch 要合并进去的键值(只写白名单内的)
341
+ * @param {object} [env]
342
+ * @returns {{ ok: boolean, value?: object, written?: string[], reason?: string }}
343
+ */
344
+ export function writeConfig(patch, env) {
345
+ const p = configPath(env);
346
+ if (!p) return { ok: false, reason: 'no-home' };
347
+ const s = sanitize(patch);
348
+ if (!s.ok) return { ok: false, reason: 'bad-input' };
349
+ if (Object.keys(s.value).length === 0) {
350
+ return { ok: false, reason: 'nothing-to-write', dropped: s.dropped };
351
+ }
352
+
353
+ // 读现有值再合并(读失败时不静默覆盖用户的坏文件)
354
+ const cur = readConfig(env);
355
+ if (cur.ok === false && cur.reason === 'corrupt') {
356
+ return { ok: false, reason: 'corrupt' };
357
+ }
358
+ const merged = { ...(cur.ok ? cur.value : {}), ...s.value };
359
+ const doc = { version: CONFIG_VERSION, values: merged };
360
+
361
+ const tmp = p + '.tmp';
362
+ try {
363
+ mkdirSync(dirname(p), { recursive: true });
364
+ writeFileSync(tmp, JSON.stringify(doc, null, 2) + '\n', 'utf8');
365
+ renameSync(tmp, p);
366
+ } catch (ex) {
367
+ try { if (existsSync(tmp)) unlinkSync(tmp); } catch { /* best effort */ }
368
+ return { ok: false, reason: 'write:' + String(ex && ex.message ? ex.message : ex) };
369
+ }
370
+ return { ok: true, value: merged, written: Object.keys(s.value), path: p };
371
+ }
372
+
373
+ /**
374
+ * 把「patch 层配置」与「运行时偏好」合并成最终生效配置。
375
+ *
376
+ * 优先级:`fileValues` 覆盖 `patchConfig`。两者都不含的键由调用方的 DEFAULTS 兜底。
377
+ *
378
+ * @param {object} patchConfig `cordis.patch.yml` 传来的 config(可能含 camelCase 键)
379
+ * @param {object} fileValues `readConfig().value`
380
+ * @returns {object} 合并后的原始配置(交给 normalizeConfig)
381
+ */
382
+ export function mergeConfig(patchConfig, fileValues) {
383
+ const base = patchConfig != null && typeof patchConfig === 'object' ? patchConfig : {};
384
+ const over = fileValues != null && typeof fileValues === 'object' ? fileValues : {};
385
+ return { ...base, ...over };
386
+ }
387
+
388
+ /**
389
+ * 把 patch 用的 `*Seconds` 键转成归一化后的毫秒值说明(仅供 CLI/GUI 展示)。
390
+ * 本模块不参与这两项的持久化,故只做只读呈现。
391
+ *
392
+ * @param {object} cfg normalizeConfig 的输出
393
+ * @returns {object} 便于人读的摘要
394
+ */
395
+ export function describe(cfg) {
396
+ return {
397
+ voice: cfg.voice,
398
+ voiceMode: cfg.voiceMode,
399
+ voiceName: cfg.voiceName,
400
+ volume: cfg.volume,
401
+ notifyOnComplete: cfg.notifyOnComplete,
402
+ notifyOnError: cfg.notifyOnError,
403
+ notifyOnBlocked: cfg.notifyOnBlocked,
404
+ notifyOnAborted: cfg.notifyOnAborted,
405
+ notifyOnApproval: cfg.notifyOnApproval,
406
+ notifyOnQuestion: cfg.notifyOnQuestion,
407
+ subagents: cfg.subagents,
408
+ idleGate: cfg.idleGate,
409
+ // v0.4.2+:这些也要进摘要,否则改了它们"配置变更签名"不变,
410
+ // 日志就不会打印新配置,排查时看不出变化。
411
+ audioSource: cfg.audioSource,
412
+ showToast: cfg.showToast,
413
+ ttsVoice: cfg.ttsVoice,
414
+ ttsRate: cfg.ttsRate,
415
+ jumpWhenBackground: cfg.jumpWhenBackground,
416
+ jumpWhenForeground: cfg.jumpWhenForeground,
417
+ multiJumpRule: cfg.multiJumpRule,
418
+ devReload: cfg.devReload,
419
+ logLevel: cfg.logLevel,
420
+ audioSourceByKind: cfg.audioSourceByKind,
421
+ ttsTexts: cfg.ttsTexts,
422
+ kindSystemSound: cfg.kindSystemSound,
423
+ kindVoiceName: cfg.kindVoiceName,
424
+ customFiles: cfg.customFiles,
425
+ debounceSeconds: Math.round((Number(cfg.debounceMs) || 0) / 1000),
426
+ globalCooldownSeconds: Math.round((Number(cfg.globalCooldownMs) || 0) / 1000),
427
+ idleGateTimeoutSeconds: Math.round((Number(cfg.idleGateTimeoutMs) || 0) / 1000),
428
+ };
429
+ }