dsh-voice 0.6.0 → 0.7.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/lib/tools.js CHANGED
@@ -3,13 +3,16 @@
3
3
  *
4
4
  * @module dsh-voice/tools
5
5
  */
6
- import { readFileSync, statSync } from 'node:fs';
7
- import { basename, join } from 'node:path';
8
- import { synthesizeSpeech } from './edge-tts.js';
9
- import { assertAudioFile, ensureWorkspaceDirectory, resolveOutputPath, writeWorkspaceFile } from './paths.js';
6
+ import { openAsBlob, readFileSync, statSync } from 'node:fs';
7
+ import { basename, extname, join } from 'node:path';
8
+ import { isLoopbackBaseUrl, isValidProsody } from './config.js';
9
+ import { synthesizeSpeech, synthesizeSpeechWithMetadata } from './edge-tts.js';
10
+ import { rateToSpeed, synthesizeOpenAiSpeech } from './openai-tts.js';
11
+ import { assertAudioFile, assertWorkspaceFile, ensureWorkspaceDirectory, resolveOutputPath, writeWorkspaceFile } from './paths.js';
10
12
  import { createProxyFetch } from './proxy-fetch.js';
11
- import { assertAudioSize, transcribe } from './stt.js';
12
- import { isValidVoiceId, VOICES } from './voices.js';
13
+ import { assertAudioSize, formatSttSubtitles, hasFfmpeg, prepareAudioForAsr, transcribe } from './stt.js';
14
+ import { cleanMarkdownForSpeech, concatMp3Buffers, createSilenceMp3, estimateMp3DurationMs, formatSubtitles, offsetCues, renderPreviewHtml, splitTextIntoChunks, } from './tts-text.js';
15
+ import { filterVoices, isValidVoiceId, VOICES } from './voices.js';
13
16
  function compileParameters(spec) {
14
17
  const properties = {};
15
18
  const required = [];
@@ -25,6 +28,16 @@ function compileParameters(spec) {
25
28
  node.enum = prop.enum;
26
29
  if (prop?.items !== undefined)
27
30
  node.items = prop.items;
31
+ if (prop?.properties !== undefined)
32
+ node.properties = prop.properties;
33
+ if (Array.isArray(prop?.required))
34
+ node.required = prop.required;
35
+ if (prop?.default !== undefined)
36
+ node.default = prop.default;
37
+ if (typeof prop?.minimum === 'number')
38
+ node.minimum = prop.minimum;
39
+ if (typeof prop?.maximum === 'number')
40
+ node.maximum = prop.maximum;
28
41
  properties[key] = node;
29
42
  }
30
43
  return { type: 'object', properties, ...(required.length > 0 ? { required } : {}) };
@@ -87,6 +100,23 @@ function sessionCwd(exec) {
87
100
  const cwd = exec?.agent?.session?.header?.cwd;
88
101
  return typeof cwd === 'string' && cwd.trim() !== '' ? cwd : process.cwd();
89
102
  }
103
+ function mimeFromPath(filePath) {
104
+ const ext = extname(filePath).toLowerCase();
105
+ const table = {
106
+ '.mp3': 'audio/mpeg',
107
+ '.wav': 'audio/wav',
108
+ '.m4a': 'audio/mp4',
109
+ '.mp4': 'audio/mp4',
110
+ '.ogg': 'audio/ogg',
111
+ '.opus': 'audio/ogg',
112
+ '.flac': 'audio/flac',
113
+ '.webm': 'audio/webm',
114
+ };
115
+ return table[ext] ?? 'application/octet-stream';
116
+ }
117
+ function subtitleFormatOf(filePath) {
118
+ return extname(filePath).toLowerCase() === '.vtt' ? 'vtt' : 'srt';
119
+ }
90
120
  const voiceItemSchema = {
91
121
  type: 'object',
92
122
  properties: { id: { type: 'string' }, gender: { type: 'string' }, locale: { type: 'string' } },
@@ -106,6 +136,8 @@ const ttsSchema = {
106
136
  rate: { type: 'string' },
107
137
  pitch: { type: 'string' },
108
138
  textLength: { type: 'integer' },
139
+ chunks: { type: 'integer' },
140
+ subtitleFile: { type: 'string' },
109
141
  },
110
142
  additionalProperties: true,
111
143
  };
@@ -117,6 +149,7 @@ const sttSchema = {
117
149
  language: { type: 'string' },
118
150
  audio: { type: 'string' },
119
151
  transcriptFile: { type: 'string' },
152
+ subtitleFile: { type: 'string' },
120
153
  },
121
154
  additionalProperties: true,
122
155
  };
@@ -127,21 +160,31 @@ const previewSchema = {
127
160
  samples: { type: 'array', items: { type: 'object', additionalProperties: true } },
128
161
  failed: { type: 'array', items: { type: 'object', additionalProperties: true } },
129
162
  text: { type: 'string' },
163
+ indexHtml: { type: 'string' },
130
164
  },
131
165
  additionalProperties: true,
132
166
  };
133
167
  /** 自定义端点没配 asrModel 时的兜底模型名。 */
134
168
  const FALLBACK_ASR_MODEL = 'whisper-1';
169
+ /** 单次 TTS 最大字符上限(长文自动分段合成)。 */
170
+ const MAX_TTS_CHARS = 100000;
171
+ /** 多角色对话/播客分段数上限。 */
172
+ const MAX_TTS_SEGMENTS = 50;
173
+ /** OpenAI 兼容 TTS 默认模型。 */
174
+ const FALLBACK_TTS_MODEL = 'gpt-4o-mini-tts';
175
+ /** ASR 直传上限(25MB)。 */
176
+ const MAX_ASR_BYTES = 25 * 1024 * 1024;
135
177
  /** 默认试听文本(中英混合,便于感知发音差异)。 */
136
178
  export const DEFAULT_PREVIEW_TEXT = '你好,这是音色试听。Hello, this is a voice preview.';
137
179
  /** voice_preview 同时合成的音色数上限:有界并发,避免 8 个音色串行把最坏等待拖成 8 倍超时。 */
138
180
  const PREVIEW_CONCURRENCY = 3;
181
+ /** voice_tts 分段合成的并发上限。 */
182
+ const TTS_CHUNK_CONCURRENCY = 2;
139
183
  /**
140
184
  * 构建五个语音工具定义(支持静态配置对象或活引用配置 getter)。
141
185
  */
142
186
  export function buildVoiceTools(config, deps = {}) {
143
187
  const getCfg = typeof config === 'function' ? config : () => config;
144
- const initialCfg = getCfg();
145
188
  let cachedProxyUrl = '';
146
189
  let cachedFetchImpl;
147
190
  const getProxyFetch = (proxyUrl) => {
@@ -153,11 +196,79 @@ export function buildVoiceTools(config, deps = {}) {
153
196
  }
154
197
  return cachedFetchImpl;
155
198
  };
199
+ const assertProsody = (rate, pitch) => {
200
+ if (!isValidProsody(rate))
201
+ throw new Error('语速 rate 不合法:' + rate + '。合法格式如 +10%、-2Hz、+1st。');
202
+ if (!isValidProsody(pitch))
203
+ throw new Error('音调 pitch 不合法:' + pitch + '。合法格式如 +10%、-2Hz、+1st。');
204
+ };
205
+ const assertTtsEngineReady = (cfg, useEdge) => {
206
+ if (useEdge)
207
+ return;
208
+ if (cfg.ttsBaseUrl === '') {
209
+ throw new Error('未配置 TTS 接口地址:ttsEngine=' + cfg.ttsEngine + ' 时必须在 DSH「设置 → 插件 → 语音」配置 ttsBaseUrl(保存即生效)。');
210
+ }
211
+ if (cfg.ttsApiKey === '' && !isLoopbackBaseUrl(cfg.ttsBaseUrl)) {
212
+ throw new Error('未配置 TTS 密钥:请在 DSH「设置 → 插件 → 语音」配置 ttsApiKey,或设置环境变量 DSH_VOICE_TTS_KEY。');
213
+ }
214
+ };
215
+ const assertTtsVoice = (voice, useEdge) => {
216
+ if (useEdge) {
217
+ if (!isValidVoiceId(voice)) {
218
+ throw new Error('音色 id 不合法:' + voice + '。请用 voice_list 查看常用音色,或在 DSH「设置 → 插件 → 语音」修改 ttsVoice(合法格式如 zh-CN-XiaoxiaoNeural)。');
219
+ }
220
+ return;
221
+ }
222
+ if (voice.trim() === '')
223
+ throw new Error('音色 id 不合法:不能为空。');
224
+ };
225
+ const synthesizeChunk = async (cfg, useEdge, chunkText, voice, rate, pitch, needSubtitles, signal) => {
226
+ if (useEdge) {
227
+ if (!needSubtitles) {
228
+ const ttsFn = deps.tts ?? (deps.ttsWithMeta !== undefined
229
+ ? async (opts, ttsDeps, timeoutMs, abortSig) => (await deps.ttsWithMeta(opts, ttsDeps, timeoutMs, abortSig)).audio
230
+ : synthesizeSpeech);
231
+ const audio = await raceAbort(ttsFn({ text: chunkText, voice, rate, pitch }, { proxyUrl: cfg.proxyUrl }, cfg.timeoutMs, signal), signal);
232
+ return { audio, cues: [] };
233
+ }
234
+ if (deps.ttsWithMeta !== undefined || deps.tts === undefined) {
235
+ const withMetaFn = deps.ttsWithMeta ?? synthesizeSpeechWithMetadata;
236
+ const res = await raceAbort(withMetaFn({ text: chunkText, voice, rate, pitch, boundary: 'sentence' }, { proxyUrl: cfg.proxyUrl }, cfg.timeoutMs, signal), signal);
237
+ const cues = res.cues.length > 0
238
+ ? res.cues
239
+ : [{ index: 1, startMs: 0, endMs: Math.max(1, estimateMp3DurationMs(res.audio)), text: chunkText }];
240
+ return { audio: res.audio, cues };
241
+ }
242
+ const audio = await raceAbort(deps.tts({ text: chunkText, voice, rate, pitch }, { proxyUrl: cfg.proxyUrl }, cfg.timeoutMs, signal), signal);
243
+ return {
244
+ audio,
245
+ cues: [{ index: 1, startMs: 0, endMs: Math.max(1, estimateMp3DurationMs(audio)), text: chunkText }],
246
+ };
247
+ }
248
+ const openaiFn = deps.openaiTts ?? synthesizeOpenAiSpeech;
249
+ const audio = await raceAbort(openaiFn(cfg.ttsBaseUrl, cfg.ttsApiKey, {
250
+ text: chunkText,
251
+ voice,
252
+ model: cfg.ttsModel !== '' ? cfg.ttsModel : FALLBACK_TTS_MODEL,
253
+ speed: rateToSpeed(rate),
254
+ signal,
255
+ }, getProxyFetch(cfg.proxyUrl) ?? globalThis.fetch, cfg.timeoutMs, signal), signal);
256
+ return {
257
+ audio,
258
+ cues: needSubtitles
259
+ ? [{ index: 1, startMs: 0, endMs: Math.max(1, estimateMp3DurationMs(audio)), text: chunkText }]
260
+ : [],
261
+ };
262
+ };
156
263
  const voiceList = {
157
264
  name: 'voice_list',
158
265
  isConcurrencySafe: () => true,
159
- description: '列出常用语音合成音色(edge-tts 微软神经语音,免费)。含普通话/方言/粤语/英/日/韩/法/德/俄/西。voice_tts 的 voice 参数也接受清单外的合法 edge 音色 id(如 zh-CN-XXXNeural)。',
160
- parameters: compileParameters({}),
266
+ description: '列出常用语音合成音色(edge-tts 微软神经语音,免费)。含普通话/方言/粤语/英/日/韩/法/德/俄/西及多语种音色,支持按 locale/gender/tag 筛选。voice_tts 的 voice 参数也接受清单外的合法 edge 音色 id。',
267
+ parameters: compileParameters({
268
+ locale: { type: 'string', description: '按语言/地区或名称关键字筛选(可选,如 zh-CN、en-US、粤语)。' },
269
+ gender: { type: 'string', enum: ['Female', 'Male'], description: '按性别筛选(可选:Female 或 Male)。' },
270
+ tag: { type: 'string', description: '按场景标签筛选(可选,如 podcast、multilingual、news、dialect)。' },
271
+ }),
161
272
  output: {
162
273
  schema: listSchema,
163
274
  render: (_args, value) => {
@@ -166,30 +277,61 @@ export function buildVoiceTools(config, deps = {}) {
166
277
  const lines = ['共 ' + voices.length + ' 个常用音色:'];
167
278
  for (const voice of voices) {
168
279
  const v = asRecord(voice);
169
- lines.push('- ' + v.id + '(' + v.locale + ')');
280
+ const tags = Array.isArray(v.tags) && v.tags.length > 0 ? ' [' + v.tags.join(', ') + ']' : '';
281
+ lines.push('- ' + v.id + '(' + v.locale + ')' + tags);
170
282
  }
171
283
  return [{ type: 'text', text: lines.join('\n') }];
172
284
  },
173
285
  },
174
- async execute() {
175
- return { count: VOICES.length, voices: VOICES };
286
+ async execute(rawArgs) {
287
+ const args = asRecord(rawArgs);
288
+ const locale = optionalString(args, 'locale');
289
+ const gender = optionalString(args, 'gender');
290
+ const tag = optionalString(args, 'tag');
291
+ const hasFilter = locale !== undefined || gender !== undefined || tag !== undefined;
292
+ const voices = hasFilter ? filterVoices({ locale, gender, tag }) : VOICES;
293
+ return { count: voices.length, voices };
176
294
  },
177
295
  };
178
296
  const voiceTts = {
179
297
  name: 'voice_tts',
180
- description: '文字转语音:调用 edge-tts(微软 Edge 朗读服务,免费)合成 MP3。text 必填(≤5000 字符,更长请分段);voice 可选(默认 zh-CN-XiaoxiaoNeural,清单见 voice_list);rate/pitch 如 +10%、-2Hz;输出默认 voice_output.mp3(同名自动加序号)。',
298
+ isConcurrencySafe: () => !getCfg().overwrite,
299
+ description: '文字转语音:默认调用 edge-tts(微软 Edge 朗读服务,免费)合成 MP3,也可在设置中切换 OpenAI/SiliconFlow/自定义 TTS 引擎。支持直接传 text(自动分段支持至 100000 字符)、读取工作区 inputFile(自动清理 Markdown)、多角色播客 segments 及导出 .srt/.vtt 字幕;输出默认 voice_output.mp3(同名自动加序号)。',
181
300
  parameters: compileParameters({
182
- text: { type: 'string', required: true, description: '要合成的文本(必填,≤5000 字符)。' },
301
+ text: { type: 'string', description: '要合成的文本(若提供 inputFile 或 segments 则可选;支持长文本自动分段,≤100000 字符)。' },
302
+ inputFile: { type: 'string', description: '工作区内文稿文件路径(可选,如 article.md;指定时直接从文件读取)。' },
303
+ cleanMarkdown: { type: 'boolean', description: '是否清理 Markdown 语法以便朗读(可选;inputFile 为 .md/.markdown 时默认 true)。' },
304
+ segments: {
305
+ type: 'array',
306
+ description: '多角色对话/播客分段(可选,最多 50 段):每段可独立指定 voice/text/rate/pitch/pauseMs。',
307
+ items: {
308
+ type: 'object',
309
+ properties: {
310
+ voice: { type: 'string' },
311
+ text: { type: 'string' },
312
+ rate: { type: 'string' },
313
+ pitch: { type: 'string' },
314
+ pauseMs: { type: 'number' },
315
+ },
316
+ required: ['text'],
317
+ },
318
+ },
183
319
  voice: { type: 'string', description: '音色 id(可选,默认配置的 ttsVoice)。' },
184
320
  rate: { type: 'string', description: '语速,如 +20% 或 -10%(可选)。' },
185
321
  pitch: { type: 'string', description: '音调,如 +2Hz 或 -1Hz(可选)。' },
186
322
  output: { type: 'string', description: '输出 MP3 路径(可选,相对路径按会话工作目录解析)。' },
323
+ subtitleOutput: { type: 'string', description: '导出同步字幕文件路径(可选,.srt 或 .vtt,相对路径按会话工作目录解析)。' },
187
324
  }),
188
325
  output: {
189
326
  schema: ttsSchema,
190
327
  render: (_args, value) => {
191
328
  const rec = asRecord(value);
192
- return [{ type: 'text', text: '语音合成完成:' + rec.output + '(' + rec.bytes + ' 字节,音色 ' + rec.voice + ')' }];
329
+ const chunksInfo = typeof rec.chunks === 'number' && rec.chunks > 1 ? ',共 ' + rec.chunks + ' 段' : '';
330
+ const lines = ['语音合成完成:' + rec.output + '(' + rec.bytes + ' 字节,音色 ' + rec.voice + chunksInfo + ')'];
331
+ const subtitleFile = typeof rec.subtitleFile === 'string' ? rec.subtitleFile : '';
332
+ if (subtitleFile !== '')
333
+ lines.push('字幕文件已写入:' + subtitleFile);
334
+ return [{ type: 'text', text: lines.join('\n') }];
193
335
  },
194
336
  },
195
337
  async execute(rawArgs, exec) {
@@ -197,30 +339,160 @@ export function buildVoiceTools(config, deps = {}) {
197
339
  const signal = execSignal(exec);
198
340
  throwIfAborted(signal);
199
341
  const args = asRecord(rawArgs);
200
- const text = requiredString(args, 'text', '要合成的文本');
201
- if (text.length > 5000)
202
- throw new Error('文本超过 5000 字符,请分段合成。');
203
- const voice = optionalString(args, 'voice') ?? cfg.ttsVoice;
204
- if (!isValidVoiceId(voice))
205
- throw new Error('音色 id 不合法:' + voice + '。请用 voice_list 查看常用音色,或在 DSH「设置 → 插件 → 语音」修改 ttsVoice(合法格式如 zh-CN-XiaoxiaoNeural)。');
206
- const rate = optionalString(args, 'rate') ?? cfg.ttsRate;
207
- const pitch = optionalString(args, 'pitch') ?? cfg.ttsPitch;
208
- for (const [value, label] of [[rate, '语速 rate'], [pitch, '音调 pitch']]) {
209
- if (!/^[+-]?\d+(\.\d+)?(%|Hz|st)$/.test(value))
210
- throw new Error(label + ' 不合法:' + value + '。合法格式如 +10%、-2Hz、+1st。');
342
+ const cwd = sessionCwd(exec);
343
+ const useEdge = cfg.ttsEngine === 'edge' || deps.tts !== undefined || deps.ttsWithMeta !== undefined;
344
+ const defaultVoice = optionalString(args, 'voice') ?? cfg.ttsVoice;
345
+ const defaultRate = optionalString(args, 'rate') ?? cfg.ttsRate;
346
+ const defaultPitch = optionalString(args, 'pitch') ?? cfg.ttsPitch;
347
+ const requested = optionalString(args, 'output');
348
+ const subtitleOutput = optionalString(args, 'subtitleOutput');
349
+ const needSubtitles = subtitleOutput !== undefined;
350
+ const rawSegments = Array.isArray(args.segments) && args.segments.length > 0 ? args.segments : undefined;
351
+ if (rawSegments !== undefined) {
352
+ if (rawSegments.length > MAX_TTS_SEGMENTS) {
353
+ throw new Error('segments 最多 ' + MAX_TTS_SEGMENTS + ' 段(当前 ' + rawSegments.length + ' 段)。');
354
+ }
355
+ assertTtsEngineReady(cfg, useEdge);
356
+ const parsedSegments = [];
357
+ let totalChars = 0;
358
+ for (let i = 0; i < rawSegments.length; i++) {
359
+ const seg = asRecord(rawSegments[i]);
360
+ const rawSegText = optionalString(seg, 'text');
361
+ if (rawSegText === undefined)
362
+ throw new Error('第 ' + (i + 1) + ' 段 text 不能为空。');
363
+ const segText = args.cleanMarkdown === true ? cleanMarkdownForSpeech(rawSegText).trim() : rawSegText;
364
+ if (segText === '')
365
+ throw new Error('第 ' + (i + 1) + ' 段清理 Markdown 后文本为空。');
366
+ totalChars += segText.length;
367
+ const segVoice = optionalString(seg, 'voice') ?? defaultVoice;
368
+ const segRate = optionalString(seg, 'rate') ?? defaultRate;
369
+ const segPitch = optionalString(seg, 'pitch') ?? defaultPitch;
370
+ assertTtsVoice(segVoice, useEdge);
371
+ assertProsody(segRate, segPitch);
372
+ const pauseMs = typeof seg.pauseMs === 'number' && Number.isFinite(seg.pauseMs) && seg.pauseMs >= 0
373
+ ? Math.min(10000, Math.round(seg.pauseMs))
374
+ : 300;
375
+ const chunks = segText.length > 4000 ? splitTextIntoChunks(segText, 2800) : [segText];
376
+ parsedSegments.push({ chunks, voice: segVoice, rate: segRate, pitch: segPitch, pauseMs });
377
+ }
378
+ if (totalChars > MAX_TTS_CHARS) {
379
+ throw new Error('segments 总文本超过 ' + MAX_TTS_CHARS + ' 字符上限(当前 ' + totalChars + ' 字符)。');
380
+ }
381
+ resolveOutputPath(requested, 'voice_output.mp3', cfg.overwrite, cwd);
382
+ if (subtitleOutput !== undefined)
383
+ resolveOutputPath(subtitleOutput, '', cfg.overwrite, cwd);
384
+ const tasks = [];
385
+ for (let s = 0; s < parsedSegments.length; s++) {
386
+ const seg = parsedSegments[s];
387
+ for (const chunkText of seg.chunks) {
388
+ tasks.push({ segIndex: s, text: chunkText, voice: seg.voice, rate: seg.rate, pitch: seg.pitch });
389
+ }
390
+ }
391
+ const chunkResults = await mapLimit(tasks, TTS_CHUNK_CONCURRENCY, signal, (task) => synthesizeChunk(cfg, useEdge, task.text, task.voice, task.rate, task.pitch, needSubtitles, signal));
392
+ throwIfAborted(signal);
393
+ const buffers = [];
394
+ const allCues = [];
395
+ let offsetMs = 0;
396
+ let cueIndex = 1;
397
+ let resultIdx = 0;
398
+ for (let s = 0; s < parsedSegments.length; s++) {
399
+ const seg = parsedSegments[s];
400
+ for (let c = 0; c < seg.chunks.length; c++) {
401
+ const res = chunkResults[resultIdx++];
402
+ buffers.push(res.audio);
403
+ const chunkDurationMs = estimateMp3DurationMs(res.audio);
404
+ if (needSubtitles) {
405
+ const shifted = offsetCues(res.cues, offsetMs, cueIndex);
406
+ allCues.push(...shifted);
407
+ cueIndex += shifted.length;
408
+ const cueSpan = shifted.length > 0 ? Math.max(0, shifted[shifted.length - 1].endMs - offsetMs) : 0;
409
+ offsetMs += Math.max(chunkDurationMs, cueSpan);
410
+ }
411
+ }
412
+ if (s < parsedSegments.length - 1 && seg.pauseMs > 0) {
413
+ const silence = createSilenceMp3(seg.pauseMs);
414
+ if (silence.length > 0) {
415
+ buffers.push(silence);
416
+ offsetMs += estimateMp3DurationMs(silence);
417
+ }
418
+ }
419
+ }
420
+ const audio = buffers.length === 1 ? buffers[0] : concatMp3Buffers(buffers);
421
+ const output = writeWorkspaceFile(resolveOutputPath(requested, 'voice_output.mp3', cfg.overwrite, cwd), audio, cwd, undefined, cfg.overwrite);
422
+ let subtitleFile = '';
423
+ if (subtitleOutput !== undefined) {
424
+ const formatted = formatSubtitles(allCues, subtitleFormatOf(subtitleOutput));
425
+ subtitleFile = writeWorkspaceFile(resolveOutputPath(subtitleOutput, '', cfg.overwrite, cwd), formatted, cwd, undefined, cfg.overwrite);
426
+ }
427
+ return { output, bytes: audio.length, voice: defaultVoice, rate: defaultRate, pitch: defaultPitch, textLength: totalChars, chunks: tasks.length, subtitleFile };
428
+ }
429
+ const inputFile = optionalString(args, 'inputFile');
430
+ let finalText;
431
+ if (inputFile !== undefined) {
432
+ const resolvedInput = assertWorkspaceFile(inputFile, cwd, '文稿文件');
433
+ const rawText = readFileSync(resolvedInput, 'utf8');
434
+ const shouldClean = typeof args.cleanMarkdown === 'boolean'
435
+ ? args.cleanMarkdown
436
+ : /\.(md|markdown)$/i.test(resolvedInput);
437
+ finalText = (shouldClean ? cleanMarkdownForSpeech(rawText) : rawText).trim();
438
+ if (finalText === '') {
439
+ throw new Error(shouldClean ? '文稿文件在清理 Markdown 后内容为空。' : '文稿文件内容为空。');
440
+ }
441
+ }
442
+ else {
443
+ const rawText = requiredString(args, 'text', '要合成的文本');
444
+ finalText = args.cleanMarkdown === true ? cleanMarkdownForSpeech(rawText).trim() : rawText;
445
+ if (finalText === '')
446
+ throw new Error('要合成的文本在清理 Markdown 后为空。');
211
447
  }
212
- const requested = optionalString(args, 'output'), cwd = sessionCwd(exec);
448
+ if (finalText.length > MAX_TTS_CHARS) {
449
+ throw new Error('文本超过 ' + MAX_TTS_CHARS + ' 字符上限(当前 ' + finalText.length + ' 字符),请拆分处理。');
450
+ }
451
+ assertTtsEngineReady(cfg, useEdge);
452
+ assertTtsVoice(defaultVoice, useEdge);
453
+ assertProsody(defaultRate, defaultPitch);
213
454
  resolveOutputPath(requested, 'voice_output.mp3', cfg.overwrite, cwd);
214
- const audio = await raceAbort((deps.tts ?? synthesizeSpeech)({ text, voice, rate, pitch }, { proxyUrl: cfg.proxyUrl }, cfg.timeoutMs, signal), signal);
455
+ if (subtitleOutput !== undefined)
456
+ resolveOutputPath(subtitleOutput, '', cfg.overwrite, cwd);
457
+ let audio;
458
+ let chunkCount = 1;
459
+ let subtitleFile = '';
460
+ if (finalText.length <= 5000 && !needSubtitles && useEdge) {
461
+ const res = await synthesizeChunk(cfg, true, finalText, defaultVoice, defaultRate, defaultPitch, false, signal);
462
+ audio = res.audio;
463
+ }
464
+ else {
465
+ const chunks = splitTextIntoChunks(finalText, 2800);
466
+ chunkCount = chunks.length;
467
+ const results = await mapLimit(chunks, TTS_CHUNK_CONCURRENCY, signal, (chunk) => synthesizeChunk(cfg, useEdge, chunk, defaultVoice, defaultRate, defaultPitch, needSubtitles, signal));
468
+ throwIfAborted(signal);
469
+ audio = results.length === 1 ? results[0].audio : concatMp3Buffers(results.map((r) => r.audio));
470
+ if (subtitleOutput !== undefined) {
471
+ const allCues = [];
472
+ let offsetMs = 0;
473
+ let cueIndex = 1;
474
+ for (const res of results) {
475
+ const shifted = offsetCues(res.cues, offsetMs, cueIndex);
476
+ allCues.push(...shifted);
477
+ cueIndex += shifted.length;
478
+ const chunkDurationMs = estimateMp3DurationMs(res.audio);
479
+ const cueSpan = shifted.length > 0 ? Math.max(0, shifted[shifted.length - 1].endMs - offsetMs) : 0;
480
+ offsetMs += Math.max(chunkDurationMs, cueSpan);
481
+ }
482
+ const formatted = formatSubtitles(allCues, subtitleFormatOf(subtitleOutput));
483
+ subtitleFile = writeWorkspaceFile(resolveOutputPath(subtitleOutput, '', cfg.overwrite, cwd), formatted, cwd, undefined, cfg.overwrite);
484
+ }
485
+ }
215
486
  throwIfAborted(signal);
216
487
  const output = writeWorkspaceFile(resolveOutputPath(requested, 'voice_output.mp3', cfg.overwrite, cwd), audio, cwd, undefined, cfg.overwrite);
217
- return { output, bytes: audio.length, voice, rate, pitch, textLength: text.length };
488
+ return { output, bytes: audio.length, voice: defaultVoice, rate: defaultRate, pitch: defaultPitch, textLength: finalText.length, chunks: chunkCount, subtitleFile };
218
489
  },
219
- timeoutMs: initialCfg.timeoutMs + 10000,
490
+ get timeoutMs() { return getCfg().timeoutMs + 10000; },
220
491
  };
221
492
  const voiceStt = {
222
493
  name: 'voice_stt',
223
- description: '语音转文字:调用 OpenAI 兼容 ASR 接口(默认 Groq whisper-large-v3-turbo;可切 openai/custom)。audio 为音频文件路径(mp3/wav/m4a/ogg/flac,≤25MB);language/prompt 可选;output 可把转写文本写成 .txt。密钥用环境变量 DSH_VOICE_ASR_KEY 或配置 asrApiKey。',
494
+ isConcurrencySafe: () => !getCfg().overwrite,
495
+ description: '语音转文字:调用 OpenAI 兼容 ASR 接口(默认 Groq whisper-large-v3-turbo;可切 openai/siliconflow/custom)。audio 为音频文件路径(mp3/wav/m4a/ogg/flac,≤25MB;超过 25MB 可设 autoCompress=true 用 ffmpeg 自动压缩分段);language/prompt 可选;output 可写 .txt,subtitleOutput 可写 .srt/.vtt 字幕。',
224
496
  parameters: compileParameters({
225
497
  audio: { type: 'string', required: true, description: '音频文件路径(必填)。' },
226
498
  engine: { type: 'string', enum: ['groq', 'openai', 'custom'], description: '引擎(可选):只接受与配置 asrEngine 相同的值,用于显式确认;接口地址与密钥始终取配置。' },
@@ -228,6 +500,9 @@ export function buildVoiceTools(config, deps = {}) {
228
500
  language: { type: 'string', description: '语言提示,如 zh(可选)。' },
229
501
  prompt: { type: 'string', description: '提示词(专有名词/术语纠偏,可选)。' },
230
502
  output: { type: 'string', description: '把转写文本写成 .txt 的路径(可选,相对路径按会话工作目录解析)。' },
503
+ subtitleOutput: { type: 'string', description: '导出字幕路径(可选,.srt 或 .vtt,相对路径按会话工作目录解析;指定时自动开启时间戳)。' },
504
+ timestamps: { type: 'boolean', description: '是否请求分段时间戳(可选,默认 false)。' },
505
+ autoCompress: { type: 'boolean', description: '超过 25MB 时是否自动调用本地 ffmpeg 压缩与分段转写(可选,默认 false)。' },
231
506
  }),
232
507
  output: {
233
508
  schema: sttSchema,
@@ -238,6 +513,9 @@ export function buildVoiceTools(config, deps = {}) {
238
513
  const saved = typeof rec.transcriptFile === 'string' ? rec.transcriptFile : '';
239
514
  if (saved !== '')
240
515
  lines.push('', '转写文本已写入:' + saved);
516
+ const subSaved = typeof rec.subtitleFile === 'string' ? rec.subtitleFile : '';
517
+ if (subSaved !== '')
518
+ lines.push('字幕文件已写入:' + subSaved);
241
519
  return [{ type: 'text', text: lines.join('\n') }];
242
520
  },
243
521
  },
@@ -249,49 +527,154 @@ export function buildVoiceTools(config, deps = {}) {
249
527
  const cwd = sessionCwd(exec);
250
528
  const audioPath = assertAudioFile(requiredString(args, 'audio', '音频文件'), cwd);
251
529
  const requestedEngine = optionalString(args, 'engine');
252
- if (requestedEngine !== undefined && !['groq', 'openai', 'custom'].includes(requestedEngine)) {
530
+ if (requestedEngine !== undefined && !['groq', 'openai', 'siliconflow', 'custom'].includes(requestedEngine)) {
253
531
  throw new Error('engine 必须是 groq / openai / custom 之一(当前:' + requestedEngine + ')。');
254
532
  }
255
533
  if (requestedEngine !== undefined && requestedEngine !== cfg.asrEngine) {
256
534
  throw new Error('voice_stt 不支持用 engine 参数临时换引擎(配置 asrEngine=' + cfg.asrEngine + ',本次传入 ' + requestedEngine + ')。接口地址与密钥是一组配置,混着用会把密钥发到非预期的服务;如需切换请在 DSH「设置 → 插件 → 语音」修改 asrEngine / asrBaseUrl(保存即生效)。');
257
535
  }
258
- // 接口地址一律取配置:openai/groq 预设已由 resolveConfig 回填,自定义端点原样使用。
536
+ // 接口地址一律取配置:openai/groq/siliconflow 预设已由 resolveConfig 回填,自定义端点原样使用。
259
537
  const baseUrl = cfg.asrBaseUrl;
260
538
  if (baseUrl === '')
261
539
  throw new Error('未配置 ASR 接口地址:asrEngine=custom 时必须在 DSH「设置 → 插件 → 语音」或配置里提供 asrBaseUrl(保存即生效)。');
262
- assertAudioSize(statSync(audioPath).size);
263
- const audio = readFileSync(audioPath);
264
- // 伪文件(如 procfs)stat 报 0 字节,按实际读到的长度再判一次。
265
- assertAudioSize(audio.length);
540
+ const output = optionalString(args, 'output');
541
+ const subtitleOutput = optionalString(args, 'subtitleOutput');
542
+ if (output !== undefined)
543
+ resolveOutputPath(output, '', cfg.overwrite, cwd);
544
+ if (subtitleOutput !== undefined)
545
+ resolveOutputPath(subtitleOutput, '', cfg.overwrite, cwd);
266
546
  const model = optionalString(args, 'model') ?? (cfg.asrModel !== '' ? cfg.asrModel : FALLBACK_ASR_MODEL);
267
- const { text } = await raceAbort((deps.stt ?? transcribe)(baseUrl, cfg.asrApiKey, {
268
- audio,
269
- filename: basename(audioPath),
270
- model,
271
- language: optionalString(args, 'language'),
272
- prompt: optionalString(args, 'prompt'),
273
- }, getProxyFetch(cfg.proxyUrl) ?? globalThis.fetch, cfg.timeoutMs, signal), signal);
274
- throwIfAborted(signal);
547
+ const language = optionalString(args, 'language');
548
+ const prompt = optionalString(args, 'prompt');
549
+ const needTimestamps = args.timestamps === true || subtitleOutput !== undefined;
550
+ const allowEmptyApiKey = cfg.asrEngine === 'custom' && isLoopbackBaseUrl(baseUrl);
551
+ const fetchImpl = getProxyFetch(cfg.proxyUrl) ?? globalThis.fetch;
552
+ const sttFn = deps.stt ?? transcribe;
553
+ const fileSize = statSync(audioPath).size;
554
+ let text = '';
555
+ let detectedLanguage = '';
556
+ let duration;
557
+ let segments;
558
+ if (fileSize > MAX_ASR_BYTES) {
559
+ if (args.autoCompress !== true)
560
+ assertAudioSize(fileSize);
561
+ if (deps.prepareAudio === undefined && !hasFfmpeg()) {
562
+ throw new Error('音频超过 25MB,且未检测到 ffmpeg;请先安装 ffmpeg(或使用 dsh-ffmpeg 压缩),再启用 autoCompress=true。');
563
+ }
564
+ const prep = await raceAbort((deps.prepareAudio ?? prepareAudioForAsr)(audioPath, signal), signal);
565
+ try {
566
+ const chunkResults = await mapLimit(prep.chunks, 2, signal, async (chunk) => {
567
+ const res = await raceAbort(sttFn(baseUrl, cfg.asrApiKey, {
568
+ audio: chunk.audio,
569
+ filename: chunk.filename,
570
+ model,
571
+ language,
572
+ prompt,
573
+ timestamps: needTimestamps,
574
+ allowEmptyApiKey,
575
+ }, fetchImpl, cfg.timeoutMs, signal), signal);
576
+ return { chunk, res };
577
+ });
578
+ throwIfAborted(signal);
579
+ text = chunkResults.map((item) => item.res.text.trim()).filter(Boolean).join('\n');
580
+ detectedLanguage = chunkResults.find((item) => typeof item.res.language === 'string' && item.res.language !== '')?.res.language ?? '';
581
+ let totalDuration = 0;
582
+ let hasDuration = false;
583
+ const mergedSegments = [];
584
+ let segId = 1;
585
+ for (const { chunk, res } of chunkResults) {
586
+ if (typeof res.duration === 'number' && Number.isFinite(res.duration)) {
587
+ totalDuration = Math.max(totalDuration, chunk.offsetSeconds + res.duration);
588
+ hasDuration = true;
589
+ }
590
+ if (Array.isArray(res.segments) && res.segments.length > 0) {
591
+ for (const seg of res.segments) {
592
+ mergedSegments.push({
593
+ id: segId++,
594
+ start: seg.start + chunk.offsetSeconds,
595
+ end: seg.end + chunk.offsetSeconds,
596
+ text: seg.text,
597
+ });
598
+ }
599
+ }
600
+ }
601
+ if (hasDuration)
602
+ duration = totalDuration;
603
+ if (mergedSegments.length > 0)
604
+ segments = mergedSegments;
605
+ }
606
+ finally {
607
+ prep.cleanup();
608
+ }
609
+ }
610
+ else {
611
+ let audioInput;
612
+ if (deps.stt !== undefined) {
613
+ // 保持单元测试兼容性:注入假 stt 时传 Buffer(部分测试会对 captured.audio 做扩展运算符迭代)。
614
+ const buf = readFileSync(audioPath);
615
+ assertAudioSize(buf.length);
616
+ audioInput = buf;
617
+ }
618
+ else {
619
+ let blob = await openAsBlob(audioPath, { type: mimeFromPath(audioPath) });
620
+ // 伪文件(如 procfs)size 报 0 字节,回退到 readFileSync 再判一次。
621
+ if (blob.size === 0)
622
+ blob = readFileSync(audioPath);
623
+ assertAudioSize(Buffer.isBuffer(blob) ? blob.length : blob.size);
624
+ audioInput = blob;
625
+ }
626
+ const res = await raceAbort(sttFn(baseUrl, cfg.asrApiKey, {
627
+ audio: audioInput,
628
+ filename: basename(audioPath),
629
+ model,
630
+ language,
631
+ prompt,
632
+ timestamps: needTimestamps,
633
+ allowEmptyApiKey,
634
+ }, fetchImpl, cfg.timeoutMs, signal), signal);
635
+ throwIfAborted(signal);
636
+ text = res.text;
637
+ detectedLanguage = res.language ?? '';
638
+ duration = res.duration;
639
+ segments = res.segments;
640
+ }
275
641
  let transcriptFile = '';
276
- const output = optionalString(args, 'output');
277
642
  if (output !== undefined) {
278
643
  const target = resolveOutputPath(output, '', cfg.overwrite, cwd);
279
644
  // 转写文本可能含隐私内容,只用 0600 写入。
280
645
  transcriptFile = writeWorkspaceFile(target, text, cwd, 0o600, cfg.overwrite);
281
646
  }
282
- // The output schema declares these as strings — never return null, or
283
- // dsh rejects the whole tool result (issue #1).
284
- return { text, model, language: optionalString(args, 'language') ?? '', audio: audioPath, transcriptFile };
647
+ let subtitleFile = '';
648
+ if (subtitleOutput !== undefined) {
649
+ const cueSegments = segments !== undefined && segments.length > 0
650
+ ? segments
651
+ : [{ id: 1, start: 0, end: duration !== undefined && duration > 0 ? duration : 5, text }];
652
+ const subText = formatSttSubtitles(cueSegments, subtitleFormatOf(subtitleOutput));
653
+ subtitleFile = writeWorkspaceFile(resolveOutputPath(subtitleOutput, '', cfg.overwrite, cwd), subText, cwd, 0o600, cfg.overwrite);
654
+ }
655
+ // The output schema declares string fields — never return null, or dsh rejects the whole tool result.
656
+ return {
657
+ text,
658
+ model,
659
+ language: language ?? detectedLanguage,
660
+ audio: audioPath,
661
+ transcriptFile,
662
+ subtitleFile,
663
+ ...(duration !== undefined ? { duration } : {}),
664
+ ...(segments !== undefined ? { segments } : {}),
665
+ };
285
666
  },
286
- timeoutMs: initialCfg.timeoutMs + 10000,
667
+ get timeoutMs() { return getCfg().timeoutMs + 10000; },
287
668
  };
288
669
  const voicePreview = {
289
670
  name: 'voice_preview',
290
- description: '音色试听:用一段固定试听文本批量生成短样例 MP3,方便挑选音色。voices 为音色 id 数组(可选,缺省 voice_list 前 4 个,最多 8 个);text 可自定义(≤200 字符);样例文件写入输出目录(默认会话工作目录 voice_previews),文件名含音色 id。单个音色失败不阻断其他。',
671
+ isConcurrencySafe: () => !getCfg().overwrite,
672
+ description: '音色试听:用一段固定试听文本批量生成短样例 MP3,并默认生成可直接在浏览器试听对比的 index.html。voices 为音色 id 数组(可选,缺省 voice_list 前 4 个,最多 8 个);text 可自定义(≤200 字符);样例文件写入输出目录(默认会话工作目录 voice_previews)。单个音色失败不阻断其他。',
291
673
  parameters: compileParameters({
292
674
  voices: { type: 'array', items: { type: 'string' }, description: '音色 id 数组(可选,缺省 voice_list 前 4 个,最多 8 个)。' },
293
675
  text: { type: 'string', description: '试听文本(可选,默认中英混合试听句,≤200 字符)。' },
294
676
  outputDir: { type: 'string', description: '输出目录(可选,默认会话工作目录下 voice_previews)。' },
677
+ htmlIndex: { type: 'boolean', default: true, description: '是否在输出目录生成可试听的 index.html 试听页(默认 true)。' },
295
678
  }),
296
679
  output: {
297
680
  schema: previewSchema,
@@ -308,6 +691,9 @@ export function buildVoiceTools(config, deps = {}) {
308
691
  const f = asRecord(item);
309
692
  lines.push('- ' + f.voice + ' 失败:' + String(f.error ?? ''));
310
693
  }
694
+ if (typeof rec.indexHtml === 'string' && rec.indexHtml !== '') {
695
+ lines.push('', '试听对比页:' + rec.indexHtml);
696
+ }
311
697
  return [{ type: 'text', text: lines.join('\n') }];
312
698
  },
313
699
  },
@@ -325,15 +711,20 @@ export function buildVoiceTools(config, deps = {}) {
325
711
  const text = optionalString(args, 'text') ?? DEFAULT_PREVIEW_TEXT;
326
712
  if (text.length > 200)
327
713
  throw new Error('试听文本请控制在 200 字以内(试听要短平快)。');
714
+ const useEdge = cfg.ttsEngine === 'edge' || deps.tts !== undefined;
715
+ assertTtsEngineReady(cfg, useEdge);
328
716
  const cwd = sessionCwd(exec);
329
717
  const outDir = ensureWorkspaceDirectory(optionalString(args, 'outputDir') ?? 'voice_previews', cwd);
330
718
  const outcomes = await mapLimit(targets, PREVIEW_CONCURRENCY, signal, async (voice) => {
331
719
  throwIfAborted(signal);
332
- if (!isValidVoiceId(voice)) {
720
+ if (useEdge && !isValidVoiceId(voice)) {
333
721
  return { voice, error: '音色 id 不合法(应为 zh-CN-XXXNeural 形式的 edge 音色)' };
334
722
  }
723
+ if (!useEdge && voice.trim() === '') {
724
+ return { voice, error: '音色 id 不合法:不能为空' };
725
+ }
335
726
  try {
336
- const audio = await raceAbort((deps.tts ?? synthesizeSpeech)({ text, voice, rate: cfg.ttsRate, pitch: cfg.ttsPitch }, { proxyUrl: cfg.proxyUrl }, cfg.timeoutMs, signal), signal);
727
+ const { audio } = await synthesizeChunk(cfg, useEdge, text, voice, cfg.ttsRate, cfg.ttsPitch, false, signal);
337
728
  throwIfAborted(signal);
338
729
  const name = 'voice-preview-' + voice.replace(/[^a-zA-Z0-9-]/g, '_') + '.mp3';
339
730
  // 复用 resolveOutputPath:overwrite=false 时改名加序号,不再直接覆盖同名样例。
@@ -354,15 +745,38 @@ export function buildVoiceTools(config, deps = {}) {
354
745
  else
355
746
  samples.push({ voice: outcome.voice, output: outcome.output, bytes: outcome.bytes });
356
747
  }
357
- return { count: samples.length, samples, failed, text };
748
+ let indexHtml = '';
749
+ if (samples.length > 0 && args.htmlIndex !== false) {
750
+ const voiceMap = new Map(VOICES.map((v) => [v.id, v]));
751
+ const htmlSamples = samples.map((s) => {
752
+ const id = String(s.voice);
753
+ const meta = voiceMap.get(id);
754
+ return {
755
+ voice: id,
756
+ fileName: basename(String(s.output)),
757
+ locale: meta?.locale,
758
+ gender: meta?.gender,
759
+ };
760
+ });
761
+ const html = renderPreviewHtml(htmlSamples, text);
762
+ try {
763
+ indexHtml = writeWorkspaceFile(resolveOutputPath(join(outDir, 'index.html'), '', true, cwd), html, cwd, undefined, true);
764
+ }
765
+ catch {
766
+ // 即使 index.html 遇到符号链接/硬链接保护,也不阻断试听样例生成本身。
767
+ }
768
+ }
769
+ return { count: samples.length, samples, failed, text, ...(indexHtml !== '' ? { indexHtml } : {}) };
358
770
  },
359
- timeoutMs: initialCfg.timeoutMs + 10000,
771
+ get timeoutMs() { return getCfg().timeoutMs * 3 + 15000; },
360
772
  };
361
773
  const voiceHealth = {
362
774
  name: 'voice_health',
363
775
  isConcurrencySafe: () => true,
364
- description: 'dsh-voice 自检:检查 TTS 音色合法性、代理配置与 ASR 引擎/接口地址/密钥就绪状态(不发起网络请求)。遇到问题时先运行本工具定位。',
365
- parameters: compileParameters({}),
776
+ description: 'dsh-voice 自检:检查 TTS 音色/引擎/语速音调、代理配置与 ASR 引擎/接口地址/密钥就绪状态(不发起网络请求)。支持按 scope(all/tts/stt)分别检查。',
777
+ parameters: compileParameters({
778
+ scope: { type: 'string', enum: ['all', 'tts', 'stt'], description: '检查范围(可选:all 全部 / tts 仅语音合成 / stt 仅语音转写,默认 all)。' },
779
+ }),
366
780
  output: {
367
781
  schema: { type: 'object', additionalProperties: true },
368
782
  render: (_args, value) => {
@@ -383,12 +797,19 @@ export function buildVoiceTools(config, deps = {}) {
383
797
  return [{ type: 'text', text: lines.join('\n') }];
384
798
  },
385
799
  },
386
- async execute() {
800
+ async execute(rawArgs) {
387
801
  const cfg = getCfg();
802
+ const args = asRecord(rawArgs);
803
+ const scopeArg = optionalString(args, 'scope');
804
+ if (scopeArg !== undefined && !['all', 'tts', 'stt'].includes(scopeArg)) {
805
+ throw new Error('scope 必须是 all / tts / stt 之一(当前:' + scopeArg + ')。');
806
+ }
807
+ const scope = scopeArg ?? 'all';
388
808
  const checks = [];
389
- const hints = [];
390
- let ok = true;
391
- const voiceOk = isValidVoiceId(cfg.ttsVoice);
809
+ const ttsHints = [];
810
+ const sttHints = [];
811
+ // 1. TTS 音色(保持 checks[0] 以兼容既有测试对 checks[0].detail 的断言)
812
+ const voiceOk = cfg.ttsEngine === 'edge' ? isValidVoiceId(cfg.ttsVoice) : cfg.ttsVoice.trim() !== '';
392
813
  checks.push({
393
814
  name: 'TTS 音色',
394
815
  ok: voiceOk,
@@ -396,34 +817,83 @@ export function buildVoiceTools(config, deps = {}) {
396
817
  ...(voiceOk ? {} : { hint: '运行 voice_list 挑一个清单内音色,在 DSH「设置 → 插件 → 语音」修改 ttsVoice(保存即生效);合法 id 形如 zh-CN-XiaoxiaoNeural。' }),
397
818
  });
398
819
  if (!voiceOk) {
399
- ok = false;
400
- hints.push('TTS 音色不合法:先用 voice_list 选音色,再在 DSH「设置 → 插件 → 语音」修改 ttsVoice(保存即生效);在此之前 voice_tts 调用会直接报错。');
820
+ ttsHints.push('TTS 音色不合法:先用 voice_list 选音色,再在 DSH「设置 → 插件 → 语音」修改 ttsVoice(保存即生效);在此之前 voice_tts 调用会直接报错。');
821
+ }
822
+ // 2. TTS 引擎
823
+ let ttsEngineOk = true;
824
+ let ttsEngineDetail = 'edge(免费零配置)';
825
+ let ttsEngineHint;
826
+ if (cfg.ttsEngine !== 'edge') {
827
+ const ttsBaseOk = cfg.ttsBaseUrl !== '';
828
+ const ttsKeyOk = cfg.ttsApiKey !== '' || (ttsBaseOk && isLoopbackBaseUrl(cfg.ttsBaseUrl));
829
+ ttsEngineOk = ttsBaseOk && ttsKeyOk;
830
+ if (!ttsBaseOk) {
831
+ ttsEngineDetail = '未配置:ttsEngine=' + cfg.ttsEngine + ' 时必须提供 ttsBaseUrl';
832
+ ttsEngineHint = '在 DSH「设置 → 插件 → 语音」补上 ttsBaseUrl(含 /v1 的 OpenAI 兼容地址),或改回 edge。';
833
+ ttsHints.push('TTS 接口地址缺失:当前 ttsEngine=' + cfg.ttsEngine + ',需配置 ttsBaseUrl 或切回免费 edge 引擎。');
834
+ }
835
+ else if (!ttsKeyOk) {
836
+ ttsEngineDetail = '未配置 TTS 密钥:需要 DSH_VOICE_TTS_KEY 或配置 ttsApiKey';
837
+ ttsEngineHint = '在 DSH「设置 → 插件 → 语音」填写 ttsApiKey,或设置环境变量 DSH_VOICE_TTS_KEY(或切回免费 edge 引擎)。';
838
+ ttsHints.push('缺 TTS 密钥:当前 ttsEngine=' + cfg.ttsEngine + ' 需要 ttsApiKey / DSH_VOICE_TTS_KEY,或改回零密钥的 edge。');
839
+ }
840
+ else {
841
+ ttsEngineDetail = cfg.ttsEngine + '(' + cfg.ttsBaseUrl + ')';
842
+ }
843
+ }
844
+ checks.push({
845
+ name: 'TTS 引擎',
846
+ ok: ttsEngineOk,
847
+ detail: ttsEngineDetail,
848
+ ...(ttsEngineHint !== undefined ? { hint: ttsEngineHint } : {}),
849
+ });
850
+ // 3. TTS 语速与音调
851
+ const prosodyOk = isValidProsody(cfg.ttsRate) && isValidProsody(cfg.ttsPitch);
852
+ checks.push({
853
+ name: 'TTS 语速与音调',
854
+ ok: prosodyOk,
855
+ detail: prosodyOk ? 'rate=' + cfg.ttsRate + ', pitch=' + cfg.ttsPitch : '不合法:rate=' + cfg.ttsRate + ', pitch=' + cfg.ttsPitch,
856
+ ...(prosodyOk ? {} : { hint: '语速/音调必须符合 +10%、-20%、+2Hz、-1st 格式,请在 DSH「设置 → 插件 → 语音」修正 ttsRate / ttsPitch。' }),
857
+ });
858
+ if (!prosodyOk) {
859
+ ttsHints.push('TTS 语速或音调格式不合法:请在设置中修正 ttsRate / ttsPitch(如 +0% / +0Hz)。');
401
860
  }
861
+ // 4. 特殊代理
402
862
  checks.push({ name: '特殊代理', ok: true, detail: cfg.proxyUrl !== '' ? '已配置 ' + cfg.proxyUrl : '未配置' });
863
+ // 5. ASR 引擎
403
864
  checks.push({ name: 'ASR 引擎', ok: true, detail: cfg.asrEngine });
865
+ // 6. ASR 接口地址
404
866
  const baseUrlOk = cfg.asrBaseUrl !== '';
405
867
  checks.push({
406
868
  name: 'ASR 接口地址',
407
869
  ok: baseUrlOk,
408
870
  detail: baseUrlOk ? cfg.asrBaseUrl : '未配置:asrEngine=custom 时必须提供 asrBaseUrl。',
409
- ...(baseUrlOk ? {} : { hint: '在 DSH「设置 → 插件 → 语音」补上 asrBaseUrl(含 /v1 的 OpenAI 兼容地址,保存即生效),或改回 groq / openai 预设。' }),
871
+ ...(baseUrlOk ? {} : { hint: '在 DSH「设置 → 插件 → 语音」补上 asrBaseUrl(含 /v1 的 OpenAI 兼容地址,保存即生效),或改回 groq / openai / siliconflow 预设。' }),
410
872
  });
411
873
  if (!baseUrlOk) {
412
- ok = false;
413
- hints.push('ASR 接口地址缺失:只有 voice_stt 受影响,voice_tts / voice_list / voice_preview 仍可零配置正常使用。');
874
+ sttHints.push('ASR 接口地址缺失:只有 voice_stt 受影响,voice_tts / voice_list / voice_preview 仍可零配置正常使用。');
414
875
  }
415
- const hasKey = cfg.asrApiKey !== '' || typeof process.env.DSH_VOICE_ASR_KEY === 'string' && process.env.DSH_VOICE_ASR_KEY !== '';
876
+ // 7. ASR 密钥(cfg.asrApiKey 已通过 resolveAsrApiKey 完成 trim;custom 本地回环端点免密钥)
877
+ const isLocalLoopbackAsr = cfg.asrEngine === 'custom' && cfg.asrBaseUrl !== '' && isLoopbackBaseUrl(cfg.asrBaseUrl);
878
+ const hasKey = cfg.asrApiKey !== '' || isLocalLoopbackAsr;
416
879
  checks.push({
417
880
  name: 'ASR 密钥',
418
881
  ok: hasKey,
419
- detail: hasKey ? '已配置' : '未配置:voice_stt 需要 DSH_VOICE_ASR_KEY 环境变量或在「设置 → 插件 → 语音」配置 asrApiKey',
882
+ detail: cfg.asrApiKey !== ''
883
+ ? '已配置'
884
+ : isLocalLoopbackAsr
885
+ ? '本地回环端点免密钥(' + cfg.asrBaseUrl + ')'
886
+ : '未配置:voice_stt 需要 DSH_VOICE_ASR_KEY 环境变量或在「设置 → 插件 → 语音」配置 asrApiKey',
420
887
  ...(hasKey ? {} : { hint: '在 DSH「设置 → 插件 → 语音」填写 asrApiKey(自动脱敏、保存即生效),或设置环境变量 DSH_VOICE_ASR_KEY;密钥缺失只影响 voice_stt。' }),
421
888
  });
422
889
  if (!hasKey) {
423
- ok = false;
424
- hints.push('缺 ASR 密钥:仅 voice_stt 录音转写需要密钥;文字转语音(voice_tts / voice_list / voice_preview)无需任何密钥,现在即可直接使用。');
890
+ sttHints.push('缺 ASR 密钥:仅 voice_stt 录音转写需要密钥;文字转语音(voice_tts / voice_list / voice_preview)无需任何密钥,现在即可直接使用。');
425
891
  }
426
- return { ok, plugin: 'dsh-voice', checks, ...(hints.length > 0 ? { hints } : {}) };
892
+ const ttsReady = voiceOk && ttsEngineOk && prosodyOk;
893
+ const sttReady = baseUrlOk && hasKey;
894
+ const ok = scope === 'tts' ? ttsReady : scope === 'stt' ? sttReady : (ttsReady && sttReady);
895
+ const hints = scope === 'tts' ? ttsHints : scope === 'stt' ? sttHints : [...ttsHints, ...sttHints];
896
+ return { ok, ttsReady, sttReady, plugin: 'dsh-voice', checks, ...(hints.length > 0 ? { hints } : {}) };
427
897
  },
428
898
  timeoutMs: 5000,
429
899
  };