import { randomUUID } from 'node:crypto'; import { mkdir, realpath, rename, rm, writeFile } from 'node:fs/promises'; import { basename, dirname, join, relative, sep } from 'node:path'; import { z } from 'zod'; import { configService } from '../../config/configService.js'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import { pathContains } from '../../utils/pathContains.js'; import type { Tool, ToolResult } from '../../types.js'; import { resolveToolPath } from '../shared/fileUtils.js'; import { filePathField } from '../shared/schemas.js'; import { toToolParameters } from '../../utils/zodToJson.js'; const inputSchema = z.object({ text: z.string().min(1).max(10_000).describe('要合成的文本'), output: filePathField('写入').describe('工作目录内的 MP3 输出路径'), voice: z.string().optional().describe('MiniMax voice_id,默认 female-shaonv'), speed: z.number().min(0.5).max(2).optional().describe('语速,0.5 到 2.0,默认 1'), }); type SpeechInput = z.infer; type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise; async function callWith( input: SpeechInput, signal: AbortSignal | undefined, getConfig: () => ReturnType>, fetchImpl: FetchLike, cwd = getWorkingDir(), ): Promise { const output = resolveToolPath(input.output, cwd); if (!output.ok) return output; if (output.resolvedPath === cwd || !pathContains(cwd, output.resolvedPath) || !/\.mp3$/i.test(input.output)) return { ok: false, error: '输出必须是当前工作目录内的 .mp3 文件。' }; try { signal?.throwIfAborted(); const config = await getConfig(); if (!config) return { ok: false, error: '尚未配置 MiniMax 语音。请在 KakadeAI 设置 → 工具中配置。' }; const root = await realpath(cwd); let parent = root; for (const segment of relative(cwd, dirname(output.resolvedPath)).split(sep).filter(Boolean)) { const next = join(parent, segment); await mkdir(next, { recursive: true }); parent = await realpath(next); if (!pathContains(root, parent)) return { ok: false, error: '输出目录超出工作目录。' }; } signal?.throwIfAborted(); const url = new URL('/v1/t2a_v2', 'https://api.minimax.chat'); url.searchParams.set('GroupId', config.groupId); const response = await fetchImpl(url, { method: 'POST', signal, headers: { Authorization: `Bearer ${config.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'speech-01', text: input.text, voice_setting: { voice_id: input.voice ?? 'female-shaonv', speed: input.speed ?? 1 }, audio_setting: { format: 'mp3' }, }), }); const payload = await response.json().catch(() => null) as { data?: { audio?: string }; base_resp?: { status_code?: number; status_msg?: string }; } | null; const code = payload?.base_resp?.status_code; const hex = typeof payload?.data?.audio === 'string' ? payload.data.audio.replace(/\s+/g, '') : ''; if (!response.ok || (code !== undefined && code !== 0) || !hex || !/^[0-9a-f]+$/i.test(hex) || hex.length % 2 !== 0) { return { ok: false, error: `MiniMax 语音生成失败:HTTP ${response.status}${typeof code === 'number' ? ',业务状态 ' + code : ''}` }; } const audio = Buffer.from(hex, 'hex'); if (audio.length < 128 || !(audio.subarray(0, 3).equals(Buffer.from('ID3')) || (audio[0] === 0xff && (audio[1]! & 0xe0) === 0xe0))) return { ok: false, error: 'MiniMax 未返回可识别的 MP3 音频' }; signal?.throwIfAborted(); const temp = join(parent, '.' + randomUUID() + '.tmp'); try { await writeFile(temp, audio, { mode: 0o600, flag: 'wx' }); signal?.throwIfAborted(); await rename(temp, join(parent, basename(output.resolvedPath))); } finally { await rm(temp, { force: true }); } return { ok: true, content: `saved: ${input.output} (provider=minimax, size=${audio.length})` }; } catch (error) { if (signal?.aborted) return { ok: false, error: '语音生成已取消' }; return { ok: false, error: 'MiniMax 语音生成失败;请检查连接、配置和输出目录。' }; } } export function createGenerateSpeechTool( getConfig: () => ReturnType> = async () => configService.tool('textToSpeech'), fetchImpl: FetchLike = fetch, ): Tool { return { name: 'GenerateSpeech', description: '使用已配置的 MiniMax TTS 安全生成 MP3。凭据由受控工具读取,不会暴露给 Bash、日志或模型。', inputSchema, parameters: toToolParameters(inputSchema), isReadOnly: false, call: (input, signal) => callWith(input, signal, getConfig, fetchImpl), callWithContext: (input, signal, ctx) => callWith(input, signal, getConfig, fetchImpl, ctx.cwd), }; } export const generateSpeechTool = createGenerateSpeechTool();