| 1 | //! Model-visible speech/TTS generation tool for Xiaomi MiMo, DeepSeek and MiniMax. |
| 2 | //! |
| 3 | //! This mirrors the CLI `speech` / `tts` command as a first-class API tool so |
| 4 | //! the TUI model can generate narrated audio without shelling out to a nested |
| 5 | //! CodeWhale process. |
| 6 | |
| 7 | use std::path::{Path, PathBuf}; |
| 8 | |
| 9 | use anyhow::Context as _; |
| 10 | use async_trait::async_trait; |
| 11 | use base64::{Engine as _, engine::general_purpose}; |
| 12 | use serde_json::{Value, json}; |
| 13 | |
| 14 | use crate::client::{CodewhaleClient, SpeechSynthesisRequest, minimax_speech}; |
| 15 | use codewhale_config::ProviderKind; |
| 16 | use codewhale_net::network_policy::{Decision, host_from_url}; |
| 17 | |
| 18 | use super::spec::{ |
| 19 | ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, |
| 20 | optional_str, required_str, |
| 21 | }; |
| 22 | |
| 23 | pub const DEFAULT_FORMAT: &str = "wav"; |
| 24 | pub const DEFAULT_VOICE: &str = "mimo_default"; |
| 25 | const VOICE_CLONE_MAX_RAW_BYTES: usize = 7_500_000; |
| 26 | const VOICE_CLONE_BASE64_MAX_BYTES: usize = 10 * 1024 * 1024; |
| 27 | pub const SUPPORTED_SPEECH_FORMATS: &[&str] = &["wav", "mp3", "pcm16"]; |
| 28 | |
| 29 | pub const SUPPORTED_XIAOMI_MIMO_SPEECH_MODELS: &[&str] = &[ |
| 30 | "mimo-v2.5-tts-voiceclone", |
| 31 | "mimo-v2.5-tts-voicedesign", |
| 32 | "mimo-v2.5-tts", |
| 33 | "mimo-v2-tts", |
| 34 | ]; |
| 35 | |
| 36 | pub const SPEECH_MODEL_EXAMPLES: &[&str] = &[ |
| 37 | "mimo-v2.5-tts", |
| 38 | "mimo-v2.5-tts-voicedesign", |
| 39 | "mimo-v2.5-tts-voiceclone", |
| 40 | "mimo-v2-tts", |
| 41 | ]; |
| 42 | |
| 43 | pub struct SpeechTool { |
| 44 | client: Option<CodewhaleClient>, |
| 45 | output_dir: Option<PathBuf>, |
| 46 | } |
| 47 | |
| 48 | impl SpeechTool { |
| 49 | #[must_use] |
| 50 | pub fn new(client: Option<CodewhaleClient>, output_dir: Option<PathBuf>) -> Self { |
| 51 | Self { client, output_dir } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | #[async_trait] |
| 56 | impl ToolSpec for SpeechTool { |
| 57 | fn name(&self) -> &str { |
| 58 | "speech" |
| 59 | } |
| 60 | |
| 61 | fn description(&self) -> &str { |
| 62 | if self |
| 63 | .client |
| 64 | .as_ref() |
| 65 | .is_some_and(CodewhaleClient::uses_minimax_speech) |
| 66 | { |
| 67 | return "Generate speech/audio (TTS) with MiniMax using a voice ID and write the audio to the workspace. Use this when the user asks for speech, TTS, narration or read-aloud."; |
| 68 | } |
| 69 | "Generate speech/audio through the configured speech (TTS) provider. Use this when the user asks for speech, TTS, narration, read-aloud, voice design, or voice cloning. The provider decides which models and voices exist; omit model to take its default." |
| 70 | } |
| 71 | |
| 72 | fn input_schema(&self) -> Value { |
| 73 | let mut schema = json!({ |
| 74 | "type": "object", |
| 75 | "properties": { |
| 76 | "text": { |
| 77 | "type": "string", |
| 78 | "description": "Text to synthesize; the spoken content. Provider style/audio tags may be included when the configured provider supports them." |
| 79 | }, |
| 80 | "output": { |
| 81 | "type": "string", |
| 82 | "description": "Audio file path to write, relative to the workspace unless absolute. Default: speech.<format> in output_dir, configured [speech].output_dir, or the workspace." |
| 83 | }, |
| 84 | "output_dir": { |
| 85 | "type": "string", |
| 86 | "description": "Directory for the default speech.<format> output file when output is omitted. Relative paths stay inside the workspace." |
| 87 | }, |
| 88 | "model": { |
| 89 | "type": "string", |
| 90 | "description": "TTS model. Omit to take the configured provider's default, or its voice-design/voice-clone model when voice_prompt/clone_voice is set (for the MiMo provider: mimo-v2.5-tts and variants).", |
| 91 | "enum": SPEECH_MODEL_EXAMPLES |
| 92 | }, |
| 93 | "voice": { |
| 94 | "type": "string", |
| 95 | "description": "Built-in voice ID from the configured provider (MiMo examples: mimo_default, 冰糖, 茉莉, 苏打, 白桦, Mia, Chloe, Milo, Dean) or a data:audio/...;base64,... URI for voice clone." |
| 96 | }, |
| 97 | "instruction": { |
| 98 | "type": "string", |
| 99 | "description": "Natural-language style, emotion, speed, scene, or performance instruction. It is not spoken verbatim." |
| 100 | }, |
| 101 | "voice_prompt": { |
| 102 | "type": "string", |
| 103 | "description": "Voice design prompt. When model is omitted the provider's voice-design model is used (MiMo: mimo-v2.5-tts-voicedesign)." |
| 104 | }, |
| 105 | "clone_voice": { |
| 106 | "type": "string", |
| 107 | "description": "Path to a .mp3 or .wav voice sample for cloning. When model is omitted the provider's voice-clone model is used (MiMo: mimo-v2.5-tts-voiceclone)." |
| 108 | }, |
| 109 | "format": { |
| 110 | "type": "string", |
| 111 | "description": "Requested audio format. Default: wav. Providers commonly document wav and pcm16; mp3 is accepted when the API returns it.", |
| 112 | "enum": SUPPORTED_SPEECH_FORMATS |
| 113 | } |
| 114 | }, |
| 115 | "required": ["text"] |
| 116 | }); |
| 117 | if self |
| 118 | .client |
| 119 | .as_ref() |
| 120 | .is_some_and(CodewhaleClient::uses_minimax_speech) |
| 121 | { |
| 122 | let properties = schema["properties"].as_object_mut().expect("schema object"); |
| 123 | properties.insert("model".into(), json!({"type":"string","enum":minimax_speech::MODELS,"default":minimax_speech::DEFAULT_MODEL})); |
| 124 | properties.insert( |
| 125 | "voice".into(), |
| 126 | json!({"type":"string","description":"MiniMax voice ID."}), |
| 127 | ); |
| 128 | properties.insert( |
| 129 | "format".into(), |
| 130 | json!({"type":"string","enum":minimax_speech::FORMATS,"default":DEFAULT_FORMAT}), |
| 131 | ); |
| 132 | for key in ["clone_voice", "voice_prompt", "instruction"] { |
| 133 | properties.remove(key); |
| 134 | } |
| 135 | } |
| 136 | schema |
| 137 | } |
| 138 | |
| 139 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 140 | vec![ |
| 141 | ToolCapability::WritesFiles, |
| 142 | ToolCapability::Network, |
| 143 | ToolCapability::Sandboxable, |
| 144 | ] |
| 145 | } |
| 146 | |
| 147 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 148 | // Speech generation is an explicit user-facing generation action. |
| 149 | // Path resolution still enforces workspace/trusted-root boundaries. |
| 150 | ApprovalRequirement::Auto |
| 151 | } |
| 152 | |
| 153 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 154 | let text = required_str(&input, "text")?.trim().to_string(); |
| 155 | if text.is_empty() { |
| 156 | return Err(ToolError::invalid_input("speech text cannot be empty")); |
| 157 | } |
| 158 | |
| 159 | let client = self.client.clone().ok_or_else(|| { |
| 160 | ToolError::not_available( |
| 161 | "speech tool requires an active Xiaomi MiMo, DeepSeek or MiniMax API client; configure provider = \"xiaomi-mimo\", \"deepseek\" or \"minimax\" and an API key first", |
| 162 | ) |
| 163 | })?; |
| 164 | let is_minimax = client.uses_minimax_speech(); |
| 165 | let is_deepseek = matches!( |
| 166 | client.api_provider(), |
| 167 | ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic |
| 168 | ); |
| 169 | |
| 170 | let requested_format_raw = optional_str(&input, "format")? |
| 171 | .map(str::trim) |
| 172 | .filter(|value| !value.is_empty()) |
| 173 | .unwrap_or(DEFAULT_FORMAT); |
| 174 | let requested_format = prepare_speech_format_for_route( |
| 175 | requested_format_raw, |
| 176 | SpeechSurface::Tool, |
| 177 | context, |
| 178 | is_minimax, |
| 179 | ) |
| 180 | .await?; |
| 181 | let requested_format = if is_deepseek { |
| 182 | let (wire_format, _) = |
| 183 | crate::deepseek_media::normalize_deepseek_tts_format(&requested_format) |
| 184 | .map_err(ToolError::invalid_input)?; |
| 185 | wire_format.to_string() |
| 186 | } else { |
| 187 | requested_format |
| 188 | }; |
| 189 | let output_raw = optional_str(&input, "output")? |
| 190 | .map(str::trim) |
| 191 | .filter(|value| !value.is_empty()); |
| 192 | let output_path = resolve_speech_output_path( |
| 193 | &input, |
| 194 | context, |
| 195 | output_raw, |
| 196 | &requested_format, |
| 197 | self.output_dir.as_ref(), |
| 198 | )?; |
| 199 | let output_label = output_raw |
| 200 | .map(str::to_string) |
| 201 | .unwrap_or_else(|| output_path.display().to_string()); |
| 202 | |
| 203 | let raw_voice = optional_str(&input, "voice")? |
| 204 | .map(str::trim) |
| 205 | .filter(|value| !value.is_empty()) |
| 206 | .map(str::to_string); |
| 207 | let raw_instruction = optional_str(&input, "instruction")? |
| 208 | .map(str::trim) |
| 209 | .filter(|value| !value.is_empty()) |
| 210 | .map(str::to_string); |
| 211 | let voice_prompt = optional_str(&input, "voice_prompt")? |
| 212 | .map(str::trim) |
| 213 | .filter(|value| !value.is_empty()) |
| 214 | .map(str::to_string); |
| 215 | let clone_voice = optional_str(&input, "clone_voice")? |
| 216 | .map(str::trim) |
| 217 | .filter(|value| !value.is_empty()) |
| 218 | .map(str::to_string); |
| 219 | |
| 220 | let plan = prepare_speech_options_for_route( |
| 221 | SpeechPreparation { |
| 222 | model: optional_str(&input, "model")?, |
| 223 | voice: raw_voice.as_deref(), |
| 224 | instruction: raw_instruction.clone(), |
| 225 | voice_prompt: voice_prompt.clone(), |
| 226 | has_clone_path: clone_voice.is_some(), |
| 227 | surface: SpeechSurface::Tool, |
| 228 | }, |
| 229 | context, |
| 230 | is_minimax, |
| 231 | ) |
| 232 | .await?; |
| 233 | let mut model = plan.model; |
| 234 | let instruction = plan.instruction; |
| 235 | let voice = if is_deepseek { |
| 236 | if clone_voice.is_some() |
| 237 | || raw_instruction.is_some() |
| 238 | || voice_prompt.is_some() |
| 239 | || instruction.is_some() |
| 240 | || model.contains("voiceclone") |
| 241 | || model.contains("voicedesign") |
| 242 | { |
| 243 | return Err(ToolError::invalid_input( |
| 244 | "DeepSeek TTS does not support voice cloning, voice design, or style instructions", |
| 245 | )); |
| 246 | } |
| 247 | if model == "mimo-v2.5-tts" || model == "mimo-v2-tts" { |
| 248 | model = crate::deepseek_media::DEEPSEEK_TTS_MODEL.to_string(); |
| 249 | } |
| 250 | let selected_voice = match plan.voice { |
| 251 | SpeechVoice::Clone => { |
| 252 | return Err(ToolError::invalid_input( |
| 253 | "DeepSeek TTS does not support voice cloning", |
| 254 | )); |
| 255 | } |
| 256 | SpeechVoice::Raw => raw_voice.as_deref(), |
| 257 | SpeechVoice::Default | SpeechVoice::Omit => None, |
| 258 | }; |
| 259 | let normalized_voice = |
| 260 | crate::deepseek_media::normalize_deepseek_voice_id(selected_voice) |
| 261 | .map_err(ToolError::invalid_input)?; |
| 262 | Some(normalized_voice.to_string()) |
| 263 | } else { |
| 264 | match plan.voice { |
| 265 | SpeechVoice::Clone => { |
| 266 | let clone_path = clone_voice.as_deref().ok_or_else(|| { |
| 267 | ToolError::execution_failed( |
| 268 | "speech adapter requested an uncaptured clone sample", |
| 269 | ) |
| 270 | })?; |
| 271 | Some(encode_voice_clone_data_uri(context, clone_path).await?) |
| 272 | } |
| 273 | SpeechVoice::Omit => None, |
| 274 | SpeechVoice::Raw => Some(raw_voice.ok_or_else(|| { |
| 275 | ToolError::execution_failed("speech adapter requested an uncaptured voice") |
| 276 | })?), |
| 277 | SpeechVoice::Default if is_minimax => None, |
| 278 | SpeechVoice::Default => Some(DEFAULT_VOICE.to_string()), |
| 279 | } |
| 280 | }; |
| 281 | |
| 282 | if is_deepseek && text.chars().count() > crate::deepseek_media::DEEPSEEK_TTS_MAX_CHARS { |
| 283 | return Err(ToolError::invalid_input(format!( |
| 284 | "speech text exceeds DeepSeek TTS limit of {} characters", |
| 285 | crate::deepseek_media::DEEPSEEK_TTS_MAX_CHARS |
| 286 | ))); |
| 287 | } |
| 288 | |
| 289 | let policy_base_url = if is_deepseek { |
| 290 | crate::deepseek_media::deepseek_root_url(client.base_url()) |
| 291 | } else { |
| 292 | client.base_url().to_string() |
| 293 | }; |
| 294 | check_network_policy(context, &policy_base_url)?; |
| 295 | |
| 296 | let response = client |
| 297 | .synthesize_speech(SpeechSynthesisRequest { |
| 298 | model: model.clone(), |
| 299 | text, |
| 300 | instruction, |
| 301 | audio_format: requested_format, |
| 302 | voice, |
| 303 | }) |
| 304 | .await |
| 305 | .map_err(|err| { |
| 306 | ToolError::execution_failed(format!("speech synthesis failed: {err}")) |
| 307 | })?; |
| 308 | |
| 309 | if let Some(parent) = output_path |
| 310 | .parent() |
| 311 | .filter(|path| !path.as_os_str().is_empty()) |
| 312 | { |
| 313 | tokio::fs::create_dir_all(parent).await.map_err(|err| { |
| 314 | ToolError::execution_failed(format!( |
| 315 | "failed to create output directory {}: {err}", |
| 316 | parent.display() |
| 317 | )) |
| 318 | })?; |
| 319 | } |
| 320 | let audio_len = response.audio_bytes.len(); |
| 321 | super::file::run_blocking_write_atomic(&output_path, response.audio_bytes).await?; |
| 322 | |
| 323 | let result = if is_minimax { |
| 324 | json!({ |
| 325 | "mode": "speech", |
| 326 | "success": true, |
| 327 | "api": "MiniMax HTTP speech synthesis", |
| 328 | "base_url": client.base_url(), |
| 329 | "model": response.model, |
| 330 | "format": response.audio_format, |
| 331 | "output": output_label, |
| 332 | "absolute_output": output_path.display().to_string(), |
| 333 | "bytes": audio_len, |
| 334 | "voice": response.voice, |
| 335 | "transcript": response.transcript, |
| 336 | "supported_formats": minimax_speech::FORMATS, |
| 337 | }) |
| 338 | } else if is_deepseek { |
| 339 | json!({ |
| 340 | "mode": "speech", |
| 341 | "success": true, |
| 342 | "api": "DeepSeek Tools TTS (/v1/tools/tts)", |
| 343 | "base_url": crate::deepseek_media::deepseek_root_url(client.base_url()), |
| 344 | "model": response.model, |
| 345 | "format": response.audio_format, |
| 346 | "output": output_label, |
| 347 | "absolute_output": output_path.display().to_string(), |
| 348 | "bytes": audio_len, |
| 349 | "voice": response.voice.as_deref().map(describe_speech_voice), |
| 350 | "transcript": response.transcript, |
| 351 | "supported_formats": ["wav", "pcm"], |
| 352 | "supported_deepseek_voices": crate::deepseek_media::DEEPSEEK_TTS_VOICES, |
| 353 | }) |
| 354 | } else { |
| 355 | json!({ |
| 356 | "mode": "speech", |
| 357 | "success": true, |
| 358 | "api": "Xiaomi MiMo OpenAI-compatible chat/completions speech synthesis", |
| 359 | "base_url": openai_compatible_base_url(client.base_url()), |
| 360 | "model": response.model, |
| 361 | "format": response.audio_format, |
| 362 | "output": output_label, |
| 363 | "absolute_output": output_path.display().to_string(), |
| 364 | "bytes": audio_len, |
| 365 | "voice": response.voice.as_deref().map(describe_speech_voice), |
| 366 | "transcript": response.transcript, |
| 367 | "supported_formats": SUPPORTED_SPEECH_FORMATS, |
| 368 | "supported_xiaomi_mimo_models": SUPPORTED_XIAOMI_MIMO_SPEECH_MODELS, |
| 369 | }) |
| 370 | }; |
| 371 | ToolResult::json(&result).map_err(|err| { |
| 372 | ToolError::execution_failed(format!("failed to serialize result: {err}")) |
| 373 | }) |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | /// Both CLI and ToolSpec use this one preparation seam. Provider aliases, |
| 378 | /// files, embedded samples, credentials and writes remain Core-owned. |
| 379 | #[derive(Clone, Copy)] |
| 380 | pub enum SpeechSurface { |
| 381 | Tool, |
| 382 | Cli, |
| 383 | } |
| 384 | impl SpeechSurface { |
| 385 | fn as_str(self) -> &'static str { |
| 386 | match self { |
| 387 | Self::Tool => "tool", |
| 388 | Self::Cli => "cli", |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | #[derive(serde::Deserialize, Debug, PartialEq, Eq)] |
| 393 | #[serde(rename_all = "snake_case")] |
| 394 | pub enum SpeechVoice { |
| 395 | Clone, |
| 396 | Omit, |
| 397 | Raw, |
| 398 | Default, |
| 399 | } |
| 400 | #[derive(serde::Deserialize, Debug, PartialEq, Eq)] |
| 401 | #[serde(deny_unknown_fields)] |
| 402 | pub struct SpeechOptions { |
| 403 | pub model: String, |
| 404 | pub instruction: Option<String>, |
| 405 | pub voice: SpeechVoice, |
| 406 | } |
| 407 | |
| 408 | pub async fn prepare_speech_format( |
| 409 | format: &str, |
| 410 | surface: SpeechSurface, |
| 411 | context: &ToolContext, |
| 412 | ) -> Result<String, ToolError> { |
| 413 | prepare_speech_format_for_route(format, surface, context, false).await |
| 414 | } |
| 415 | |
| 416 | async fn prepare_speech_format_for_route( |
| 417 | format: &str, |
| 418 | surface: SpeechSurface, |
| 419 | context: &ToolContext, |
| 420 | minimax: bool, |
| 421 | ) -> Result<String, ToolError> { |
| 422 | if context |
| 423 | .features |
| 424 | .enabled(codewhale_runtime::features::Feature::SpeechHost) |
| 425 | { |
| 426 | let metadata = speech_projection( |
| 427 | crate::extension_host::StockOperation::SpeechFormat, |
| 428 | json!({"format":format,"surface":surface.as_str(),"minimax":minimax}), |
| 429 | context, |
| 430 | ) |
| 431 | .await?; |
| 432 | #[derive(serde::Deserialize)] |
| 433 | #[serde(deny_unknown_fields)] |
| 434 | struct Format { |
| 435 | format: String, |
| 436 | } |
| 437 | return serde_json::from_value::<Format>(metadata) |
| 438 | .map(|value| value.format) |
| 439 | .map_err(|_| { |
| 440 | ToolError::execution_failed("speech format adapter returned a malformed plan") |
| 441 | }); |
| 442 | } |
| 443 | if minimax { |
| 444 | let normalized = format.trim().to_ascii_lowercase(); |
| 445 | let normalized = if normalized == "pcm16" { |
| 446 | "pcm" |
| 447 | } else { |
| 448 | &normalized |
| 449 | }; |
| 450 | return minimax_speech::FORMATS |
| 451 | .contains(&normalized) |
| 452 | .then(|| normalized.to_owned()) |
| 453 | .ok_or_else(|| ToolError::invalid_input("unsupported MiniMax speech format")); |
| 454 | } |
| 455 | normalize_speech_format(format).ok_or_else(|| { |
| 456 | ToolError::invalid_input(match surface { |
| 457 | SpeechSurface::Tool => format!( |
| 458 | "unsupported speech format '{format}' (allowed: {})", |
| 459 | SUPPORTED_SPEECH_FORMATS.join(", ") |
| 460 | ), |
| 461 | SpeechSurface::Cli => { |
| 462 | format!("Unsupported speech format '{format}' (allowed: wav, mp3, pcm16)") |
| 463 | } |
| 464 | }) |
| 465 | }) |
| 466 | } |
| 467 | |
| 468 | pub struct SpeechPreparation<'a> { |
| 469 | pub model: Option<&'a str>, |
| 470 | pub voice: Option<&'a str>, |
| 471 | pub instruction: Option<String>, |
| 472 | pub voice_prompt: Option<String>, |
| 473 | pub has_clone_path: bool, |
| 474 | pub surface: SpeechSurface, |
| 475 | } |
| 476 | pub async fn prepare_speech_options( |
| 477 | input: SpeechPreparation<'_>, |
| 478 | context: &ToolContext, |
| 479 | ) -> Result<SpeechOptions, ToolError> { |
| 480 | prepare_speech_options_for_route(input, context, false).await |
| 481 | } |
| 482 | |
| 483 | async fn prepare_speech_options_for_route( |
| 484 | input: SpeechPreparation<'_>, |
| 485 | context: &ToolContext, |
| 486 | minimax: bool, |
| 487 | ) -> Result<SpeechOptions, ToolError> { |
| 488 | let SpeechPreparation { |
| 489 | model, |
| 490 | voice, |
| 491 | instruction, |
| 492 | voice_prompt, |
| 493 | has_clone_path, |
| 494 | surface, |
| 495 | } = input; |
| 496 | // The provider's existing canonical alias map is the only route authority. |
| 497 | // The host receives an optional canonical model hint, never a client/base URL. |
| 498 | let model_hint = if minimax { |
| 499 | let model = model |
| 500 | .map(str::trim) |
| 501 | .filter(|value| !value.is_empty()) |
| 502 | .unwrap_or(minimax_speech::DEFAULT_MODEL); |
| 503 | if !minimax_speech::MODELS.contains(&model) { |
| 504 | return Err(ToolError::invalid_input("unsupported MiniMax speech model")); |
| 505 | } |
| 506 | if has_clone_path |
| 507 | || voice_prompt.is_some() |
| 508 | || instruction.is_some() |
| 509 | || voice.is_some_and(|v| v.trim().starts_with("data:")) |
| 510 | { |
| 511 | return Err(ToolError::invalid_input( |
| 512 | "MiniMax speech accepts spoken text and a voice ID", |
| 513 | )); |
| 514 | } |
| 515 | Some(model.to_owned()) |
| 516 | } else { |
| 517 | model |
| 518 | .map(str::trim) |
| 519 | .filter(|value| !value.is_empty()) |
| 520 | .map(|value| { |
| 521 | codewhale_config::route::resolve_model(ProviderKind::XiaomiMimo, value, None) |
| 522 | .map_or_else(|_| value.into(), |resolved| resolved.wire_id) |
| 523 | }) |
| 524 | }; |
| 525 | let voice_is_data_uri = voice |
| 526 | .map(str::trim) |
| 527 | .is_some_and(|value| value.starts_with("data:audio/")); |
| 528 | if context |
| 529 | .features |
| 530 | .enabled(codewhale_runtime::features::Feature::SpeechHost) |
| 531 | { |
| 532 | let metadata = speech_projection( |
| 533 | crate::extension_host::StockOperation::SpeechOptions, |
| 534 | json!({"surface":surface.as_str(),"minimax":minimax,"model":model_hint,"instruction":instruction, |
| 535 | "voice_prompt":voice_prompt,"has_clone_path":has_clone_path, |
| 536 | "has_voice":voice.is_some(),"voice_nonempty":voice.is_some_and(|value| !value.trim().is_empty()), |
| 537 | "voice_is_data_uri":voice_is_data_uri}), context, |
| 538 | ).await?; |
| 539 | return serde_json::from_value(metadata).map_err(|_| { |
| 540 | ToolError::execution_failed("speech options adapter returned a malformed plan") |
| 541 | }); |
| 542 | } |
| 543 | if minimax { |
| 544 | return Ok(SpeechOptions { |
| 545 | model: model_hint.expect("validated MiniMax speech model"), |
| 546 | instruction: None, |
| 547 | voice: if voice.is_some_and(|value| !value.trim().is_empty()) { |
| 548 | SpeechVoice::Raw |
| 549 | } else { |
| 550 | SpeechVoice::Default |
| 551 | }, |
| 552 | }); |
| 553 | } |
| 554 | if has_clone_path && voice.is_some() { |
| 555 | return Err(ToolError::invalid_input(match surface { |
| 556 | SpeechSurface::Tool => { |
| 557 | "use either clone_voice or voice for cloned voice data, not both" |
| 558 | } |
| 559 | SpeechSurface::Cli => { |
| 560 | "Use either --clone-voice or --voice for cloned voice data, not both" |
| 561 | } |
| 562 | })); |
| 563 | } |
| 564 | let model = infer_speech_model( |
| 565 | model_hint.as_deref(), |
| 566 | has_clone_path || voice_is_data_uri, |
| 567 | voice_prompt.is_some(), |
| 568 | ); |
| 569 | let lower = model.to_ascii_lowercase(); |
| 570 | if !lower.contains("tts") { |
| 571 | return Err(ToolError::invalid_input(match surface { |
| 572 | SpeechSurface::Tool => format!( |
| 573 | "speech tool requires a TTS model (examples: {}), got '{model}'", |
| 574 | SPEECH_MODEL_EXAMPLES.join(", ") |
| 575 | ), |
| 576 | SpeechSurface::Cli => format!( |
| 577 | "speech requires a TTS model (examples: {}); got {model}", |
| 578 | SPEECH_MODEL_EXAMPLES.join(", ") |
| 579 | ), |
| 580 | })); |
| 581 | } |
| 582 | let instruction = combine_speech_instructions(instruction, voice_prompt); |
| 583 | if lower.contains("voicedesign") |
| 584 | && instruction |
| 585 | .as_deref() |
| 586 | .is_none_or(|value| value.trim().is_empty()) |
| 587 | { |
| 588 | return Err(ToolError::invalid_input(match surface { |
| 589 | SpeechSurface::Tool => "mimo-v2.5-tts-voicedesign requires voice_prompt or instruction", |
| 590 | SpeechSurface::Cli => { |
| 591 | "mimo-v2.5-tts-voicedesign requires --voice-prompt or --instruction to describe the voice" |
| 592 | } |
| 593 | })); |
| 594 | } |
| 595 | let voice = if has_clone_path { |
| 596 | SpeechVoice::Clone |
| 597 | } else if lower.contains("voicedesign") { |
| 598 | SpeechVoice::Omit |
| 599 | } else if voice.is_some_and(|value| !value.trim().is_empty()) { |
| 600 | SpeechVoice::Raw |
| 601 | } else if lower.contains("voiceclone") { |
| 602 | return Err(ToolError::invalid_input(match surface { |
| 603 | SpeechSurface::Tool => { |
| 604 | "mimo-v2.5-tts-voiceclone requires clone_voice <mp3|wav> or voice <data-uri>" |
| 605 | } |
| 606 | SpeechSurface::Cli => { |
| 607 | "mimo-v2.5-tts-voiceclone requires --clone-voice <mp3|wav> or --voice <data-uri>" |
| 608 | } |
| 609 | })); |
| 610 | } else { |
| 611 | SpeechVoice::Default |
| 612 | }; |
| 613 | Ok(SpeechOptions { |
| 614 | model, |
| 615 | instruction, |
| 616 | voice, |
| 617 | }) |
| 618 | } |
| 619 | |
| 620 | async fn speech_projection( |
| 621 | operation: crate::extension_host::StockOperation, |
| 622 | input: Value, |
| 623 | context: &ToolContext, |
| 624 | ) -> Result<Value, ToolError> { |
| 625 | let result = crate::extension_host::manager() |
| 626 | .execute_stock( |
| 627 | operation, |
| 628 | input, |
| 629 | context, |
| 630 | std::time::Duration::from_secs(30), |
| 631 | ) |
| 632 | .await?; |
| 633 | let metadata = result |
| 634 | .metadata |
| 635 | .ok_or_else(|| ToolError::execution_failed("speech adapter result is missing"))?; |
| 636 | if !result.success { |
| 637 | let error = metadata |
| 638 | .get("error") |
| 639 | .and_then(Value::as_str) |
| 640 | .ok_or_else(|| { |
| 641 | ToolError::execution_failed("speech adapter validation failure is malformed") |
| 642 | })?; |
| 643 | return Err(ToolError::invalid_input(error)); |
| 644 | } |
| 645 | Ok(metadata) |
| 646 | } |
| 647 | |
| 648 | pub fn infer_speech_model( |
| 649 | model: Option<&str>, |
| 650 | has_clone_voice: bool, |
| 651 | has_voice_prompt: bool, |
| 652 | ) -> String { |
| 653 | match model.map(str::trim).filter(|value| !value.is_empty()) { |
| 654 | Some(value) => { |
| 655 | codewhale_config::route::resolve_model(ProviderKind::XiaomiMimo, value, None) |
| 656 | .map_or_else(|_| value.into(), |resolved| resolved.wire_id) |
| 657 | } |
| 658 | None if has_clone_voice => "mimo-v2.5-tts-voiceclone".to_string(), |
| 659 | None if has_voice_prompt => "mimo-v2.5-tts-voicedesign".to_string(), |
| 660 | None => "mimo-v2.5-tts".to_string(), |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | pub fn combine_speech_instructions( |
| 665 | instruction: Option<String>, |
| 666 | voice_prompt: Option<String>, |
| 667 | ) -> Option<String> { |
| 668 | match (instruction, voice_prompt) { |
| 669 | (Some(instruction), Some(voice_prompt)) => { |
| 670 | let instruction = instruction.trim(); |
| 671 | let voice_prompt = voice_prompt.trim(); |
| 672 | if instruction.is_empty() { |
| 673 | Some(voice_prompt.to_string()).filter(|value| !value.is_empty()) |
| 674 | } else if voice_prompt.is_empty() { |
| 675 | Some(instruction.to_string()).filter(|value| !value.is_empty()) |
| 676 | } else { |
| 677 | Some(format!("{voice_prompt}\n\n{instruction}")) |
| 678 | } |
| 679 | } |
| 680 | (Some(value), None) | (None, Some(value)) => { |
| 681 | let value = value.trim().to_string(); |
| 682 | if value.is_empty() { None } else { Some(value) } |
| 683 | } |
| 684 | (None, None) => None, |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | pub fn normalize_speech_format(format: &str) -> Option<String> { |
| 689 | let normalized = format.trim().to_ascii_lowercase(); |
| 690 | match normalized.as_str() { |
| 691 | "wav" | "mp3" | "pcm16" => Some(normalized), |
| 692 | "pcm" => Some("pcm16".to_string()), |
| 693 | _ => None, |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | #[cfg(any(test, feature = "test-support"))] |
| 698 | pub fn default_speech_output_name(format: &str) -> String { |
| 699 | format!( |
| 700 | "speech.{}", |
| 701 | normalize_speech_format(format) |
| 702 | .as_deref() |
| 703 | .unwrap_or(DEFAULT_FORMAT) |
| 704 | ) |
| 705 | } |
| 706 | |
| 707 | fn resolve_speech_output_path( |
| 708 | input: &Value, |
| 709 | context: &ToolContext, |
| 710 | output_raw: Option<&str>, |
| 711 | format: &str, |
| 712 | configured_output_dir: Option<&PathBuf>, |
| 713 | ) -> Result<PathBuf, ToolError> { |
| 714 | if let Some(output) = output_raw { |
| 715 | return context.resolve_path(output); |
| 716 | } |
| 717 | |
| 718 | // Both selected backends have already validated/canonicalized the format. |
| 719 | let filename = format!("speech.{format}"); |
| 720 | if let Some(output_dir) = optional_str(input, "output_dir")? |
| 721 | .map(str::trim) |
| 722 | .filter(|value| !value.is_empty()) |
| 723 | { |
| 724 | return Ok(context.resolve_path(output_dir)?.join(filename)); |
| 725 | } |
| 726 | |
| 727 | if let Some(output_dir) = configured_output_dir { |
| 728 | return Ok(output_dir.join(filename)); |
| 729 | } |
| 730 | |
| 731 | Ok(context.workspace.join(filename)) |
| 732 | } |
| 733 | |
| 734 | async fn encode_voice_clone_data_uri( |
| 735 | context: &ToolContext, |
| 736 | raw_path: &str, |
| 737 | ) -> Result<String, ToolError> { |
| 738 | let plan = |
| 739 | crate::tools::file::resolve_read_open_plan(context, raw_path, "speech", false, false) |
| 740 | .await?; |
| 741 | let display_path = plan.file_path.clone(); |
| 742 | let (bytes, fd_path) = crate::tools::file::open_and_read_verified_bytes( |
| 743 | plan, |
| 744 | Some((VOICE_CLONE_MAX_RAW_BYTES + 1) as u64), |
| 745 | false, |
| 746 | "failed to read voice clone sample", |
| 747 | ) |
| 748 | .await? |
| 749 | .ok_or_else(|| { |
| 750 | ToolError::execution_failed(format!( |
| 751 | "failed to read voice clone sample {}: file not found", |
| 752 | display_path.display() |
| 753 | )) |
| 754 | })?; |
| 755 | if bytes.len() > VOICE_CLONE_MAX_RAW_BYTES { |
| 756 | return Err(ToolError::invalid_input(format!( |
| 757 | "voice clone sample exceeds maximum raw size ({} bytes > {} bytes)", |
| 758 | bytes.len(), |
| 759 | VOICE_CLONE_MAX_RAW_BYTES |
| 760 | ))); |
| 761 | } |
| 762 | let ext_path = if fd_path.extension().is_some() { |
| 763 | fd_path.as_path() |
| 764 | } else { |
| 765 | display_path.as_path() |
| 766 | }; |
| 767 | |
| 768 | voice_clone_data_uri_from_bytes(ext_path, &bytes) |
| 769 | .map_err(|err| ToolError::invalid_input(err.to_string())) |
| 770 | } |
| 771 | |
| 772 | pub fn encode_voice_clone_sample_data_uri(path: &Path) -> anyhow::Result<String> { |
| 773 | use std::io::Read as _; |
| 774 | |
| 775 | let file = codewhale_util::fs_confined::open_user_read(path) |
| 776 | .with_context(|| format!("Failed to read voice clone sample {}", path.display()))?; |
| 777 | let metadata = file |
| 778 | .metadata() |
| 779 | .with_context(|| format!("Failed to read voice clone sample {}", path.display()))?; |
| 780 | if metadata.len() > VOICE_CLONE_MAX_RAW_BYTES as u64 { |
| 781 | anyhow::bail!( |
| 782 | "voice clone sample exceeds maximum raw size ({} bytes > {} bytes)", |
| 783 | metadata.len(), |
| 784 | VOICE_CLONE_MAX_RAW_BYTES |
| 785 | ); |
| 786 | } |
| 787 | let mut bytes = Vec::new(); |
| 788 | file.take((VOICE_CLONE_MAX_RAW_BYTES + 1) as u64) |
| 789 | .read_to_end(&mut bytes) |
| 790 | .with_context(|| format!("Failed to read voice clone sample {}", path.display()))?; |
| 791 | if bytes.len() > VOICE_CLONE_MAX_RAW_BYTES { |
| 792 | anyhow::bail!( |
| 793 | "voice clone sample exceeds maximum raw size ({} bytes > {} bytes)", |
| 794 | bytes.len(), |
| 795 | VOICE_CLONE_MAX_RAW_BYTES |
| 796 | ); |
| 797 | } |
| 798 | |
| 799 | voice_clone_data_uri_from_bytes(path, &bytes) |
| 800 | } |
| 801 | |
| 802 | fn voice_clone_mime_for_sample(path: &Path, bytes: &[u8]) -> anyhow::Result<&'static str> { |
| 803 | let extension = path |
| 804 | .extension() |
| 805 | .and_then(|value| value.to_str()) |
| 806 | .unwrap_or_default() |
| 807 | .to_ascii_lowercase(); |
| 808 | match extension.as_str() { |
| 809 | "mp3" => { |
| 810 | let valid_mp3 = bytes.starts_with(b"ID3") |
| 811 | || (bytes.len() >= 2 && bytes[0] == 0xFF && (bytes[1] & 0xE0) == 0xE0); |
| 812 | if !valid_mp3 { |
| 813 | anyhow::bail!( |
| 814 | "voice clone sample '{}' is not a valid MP3 audio file", |
| 815 | path.display() |
| 816 | ); |
| 817 | } |
| 818 | Ok("audio/mpeg") |
| 819 | } |
| 820 | "wav" => { |
| 821 | let valid_wav = |
| 822 | bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WAVE"; |
| 823 | if !valid_wav { |
| 824 | anyhow::bail!( |
| 825 | "voice clone sample '{}' is not a valid WAV audio file", |
| 826 | path.display() |
| 827 | ); |
| 828 | } |
| 829 | Ok("audio/wav") |
| 830 | } |
| 831 | other => { |
| 832 | anyhow::bail!("unsupported voice clone sample extension '{other}'. Use .mp3 or .wav."); |
| 833 | } |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | fn voice_clone_data_uri_from_bytes(path: &Path, bytes: &[u8]) -> anyhow::Result<String> { |
| 838 | if bytes.len() > VOICE_CLONE_MAX_RAW_BYTES { |
| 839 | anyhow::bail!( |
| 840 | "voice clone sample exceeds maximum raw size ({} bytes > {} bytes)", |
| 841 | bytes.len(), |
| 842 | VOICE_CLONE_MAX_RAW_BYTES |
| 843 | ); |
| 844 | } |
| 845 | let mime = voice_clone_mime_for_sample(path, bytes)?; |
| 846 | let base64_audio = general_purpose::STANDARD.encode(bytes); |
| 847 | if base64_audio.len() > VOICE_CLONE_BASE64_MAX_BYTES { |
| 848 | anyhow::bail!( |
| 849 | "voice clone sample is too large after base64 encoding ({} bytes > 10 MB)", |
| 850 | base64_audio.len() |
| 851 | ); |
| 852 | } |
| 853 | |
| 854 | Ok(format!("data:{mime};base64,{base64_audio}")) |
| 855 | } |
| 856 | |
| 857 | pub fn describe_speech_voice(voice: &str) -> String { |
| 858 | if voice.starts_with("data:") { |
| 859 | "embedded voice clone sample".to_string() |
| 860 | } else { |
| 861 | voice.to_string() |
| 862 | } |
| 863 | } |
| 864 | |
| 865 | fn openai_compatible_base_url(base_url: &str) -> String { |
| 866 | let trimmed = base_url.trim_end_matches('/'); |
| 867 | if trimmed.ends_with("/v1") || trimmed.ends_with("/beta") { |
| 868 | trimmed.to_string() |
| 869 | } else { |
| 870 | format!("{trimmed}/v1") |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | fn check_network_policy(context: &ToolContext, base_url: &str) -> Result<(), ToolError> { |
| 875 | let Some(decider) = context.network_policy.as_ref() else { |
| 876 | return Ok(()); |
| 877 | }; |
| 878 | let display_url = openai_compatible_base_url(base_url); |
| 879 | let Some(host) = host_from_url(&display_url) else { |
| 880 | return Err(ToolError::invalid_input(format!( |
| 881 | "invalid speech base URL '{base_url}'" |
| 882 | ))); |
| 883 | }; |
| 884 | match decider.evaluate(&host, "speech") { |
| 885 | Decision::Allow => Ok(()), |
| 886 | Decision::Deny => Err(ToolError::permission_denied(format!( |
| 887 | "speech network call to '{host}' blocked by network policy" |
| 888 | ))), |
| 889 | Decision::Prompt => Err(ToolError::permission_denied(format!( |
| 890 | "speech network call to '{host}' requires approval; re-run after `/network allow {host}` or set network.default = \"allow\" in config" |
| 891 | ))), |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | #[cfg(test)] |
| 896 | mod tests { |
| 897 | use super::*; |
| 898 | |
| 899 | #[test] |
| 900 | fn infers_speech_model_from_requested_mode() { |
| 901 | assert_eq!(infer_speech_model(None, false, false), "mimo-v2.5-tts"); |
| 902 | assert_eq!( |
| 903 | infer_speech_model(None, false, true), |
| 904 | "mimo-v2.5-tts-voicedesign" |
| 905 | ); |
| 906 | assert_eq!( |
| 907 | infer_speech_model(None, true, false), |
| 908 | "mimo-v2.5-tts-voiceclone" |
| 909 | ); |
| 910 | assert_eq!( |
| 911 | infer_speech_model(Some("mimo-tts"), false, false), |
| 912 | "mimo-v2.5-tts" |
| 913 | ); |
| 914 | assert_eq!( |
| 915 | infer_speech_model(Some("mimo-v2-tts"), false, false), |
| 916 | "mimo-v2-tts" |
| 917 | ); |
| 918 | } |
| 919 | |
| 920 | #[test] |
| 921 | fn combines_voice_prompt_before_instruction() { |
| 922 | assert_eq!( |
| 923 | combine_speech_instructions( |
| 924 | Some("Speak warmly.".to_string()), |
| 925 | Some("Young Chinese female voice".to_string()) |
| 926 | ) |
| 927 | .as_deref(), |
| 928 | Some("Young Chinese female voice\n\nSpeak warmly.") |
| 929 | ); |
| 930 | assert_eq!( |
| 931 | combine_speech_instructions(Some(" calm ".to_string()), None).as_deref(), |
| 932 | Some("calm") |
| 933 | ); |
| 934 | } |
| 935 | |
| 936 | #[test] |
| 937 | fn normalizes_documented_speech_formats() { |
| 938 | assert_eq!(normalize_speech_format("WAV").as_deref(), Some("wav")); |
| 939 | assert_eq!(normalize_speech_format("pcm16").as_deref(), Some("pcm16")); |
| 940 | assert_eq!(normalize_speech_format("pcm").as_deref(), Some("pcm16")); |
| 941 | assert_eq!(normalize_speech_format("flac"), None); |
| 942 | } |
| 943 | |
| 944 | #[test] |
| 945 | fn supported_xiaomi_mimo_speech_models_are_tts_only() { |
| 946 | assert!( |
| 947 | SUPPORTED_XIAOMI_MIMO_SPEECH_MODELS |
| 948 | .iter() |
| 949 | .all(|model| model.to_ascii_lowercase().contains("tts")), |
| 950 | "model-visible speech list must not include chat-only MiMo models" |
| 951 | ); |
| 952 | assert!(SUPPORTED_XIAOMI_MIMO_SPEECH_MODELS.contains(&"mimo-v2.5-tts")); |
| 953 | assert!(!SUPPORTED_XIAOMI_MIMO_SPEECH_MODELS.contains(&"mimo-v2.5-pro")); |
| 954 | assert!(!SUPPORTED_XIAOMI_MIMO_SPEECH_MODELS.contains(&"mimo-v2.5")); |
| 955 | } |
| 956 | |
| 957 | #[test] |
| 958 | fn configured_output_dir_is_used_for_default_tool_output() { |
| 959 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 960 | let context = ToolContext::new(tmp.path().to_path_buf()); |
| 961 | let configured = tmp.path().join("speech-artifacts"); |
| 962 | |
| 963 | let output = resolve_speech_output_path( |
| 964 | &json!({"text": "hello"}), |
| 965 | &context, |
| 966 | None, |
| 967 | "pcm16", |
| 968 | Some(&configured), |
| 969 | ) |
| 970 | .expect("output path"); |
| 971 | |
| 972 | assert_eq!(output, configured.join("speech.pcm16")); |
| 973 | } |
| 974 | |
| 975 | #[test] |
| 976 | fn displays_openai_compatible_base_url() { |
| 977 | assert_eq!( |
| 978 | openai_compatible_base_url("https://api.xiaomimimo.com"), |
| 979 | "https://api.xiaomimimo.com/v1" |
| 980 | ); |
| 981 | assert_eq!( |
| 982 | openai_compatible_base_url("https://api.xiaomimimo.com/v1"), |
| 983 | "https://api.xiaomimimo.com/v1" |
| 984 | ); |
| 985 | } |
| 986 | |
| 987 | #[tokio::test] |
| 988 | async fn minimax_speech_tool_synthesizes_audio_and_preserves_output_on_failure() { |
| 989 | use wiremock::matchers::{body_json, header, method, path}; |
| 990 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 991 | |
| 992 | let _home = crate::test_support::SealedHome::new(); |
| 993 | let server = MockServer::start().await; |
| 994 | let workspace = tempfile::tempdir().unwrap(); |
| 995 | let config: codewhale_runtime::config::Config = toml::from_str(&format!( |
| 996 | "provider = 'minimax'\n[providers.minimax]\napi_key = 'test-key'\nbase_url = '{}/v1'", |
| 997 | server.uri() |
| 998 | )) |
| 999 | .unwrap(); |
| 1000 | let tool = SpeechTool::new(Some(CodewhaleClient::new(&config).unwrap()), None); |
| 1001 | let ctx = ToolContext::new(workspace.path()); |
| 1002 | let schema = tool.input_schema(); |
| 1003 | assert_eq!(schema["properties"]["model"]["default"], "speech-2.8-hd"); |
| 1004 | assert!(schema["properties"].get("clone_voice").is_none()); |
| 1005 | assert!( |
| 1006 | ["speech", "TTS", "read-aloud"] |
| 1007 | .iter() |
| 1008 | .all(|word| tool.description().contains(word)) |
| 1009 | ); |
| 1010 | let endpoint = || { |
| 1011 | Mock::given(method("POST")) |
| 1012 | .and(path("/v1/t2a_v2")) |
| 1013 | .and(header("Authorization", "Bearer test-key")) |
| 1014 | }; |
| 1015 | endpoint().and(body_json(json!({ |
| 1016 | "model":"speech-2.8-hd", "text":"Hello", "stream":false, "output_format":"hex", |
| 1017 | "voice_setting":{"voice_id":"English_expressive_narrator"}, "audio_setting":{"format":"wav"} |
| 1018 | }))).respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 1019 | "base_resp":{"status_code":0}, "data":{"status":2, "audio":"52494646"} |
| 1020 | }))).expect(1).mount(&server).await; |
| 1021 | let result = tool.execute(json!({"text":"Hello"}), &ctx).await.unwrap(); |
| 1022 | let parsed: Value = serde_json::from_str(&result.content).unwrap(); |
| 1023 | assert_eq!(parsed["bytes"], 4); |
| 1024 | let output = workspace.path().join("speech.wav"); |
| 1025 | assert_eq!(std::fs::read(&output).unwrap(), b"RIFF"); |
| 1026 | endpoint().and(body_json(json!({ |
| 1027 | "model":"speech-2.8-turbo", "text":"Again", "stream":false, "output_format":"hex", |
| 1028 | "voice_setting":{"voice_id":"English_Graceful_Lady"}, "audio_setting":{"format":"flac"} |
| 1029 | }))).respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 1030 | "base_resp":{"status_code":2013}, "data":{"status":2,"audio":"00"} |
| 1031 | }))).expect(1).mount(&server).await; |
| 1032 | let error = tool |
| 1033 | .execute( |
| 1034 | json!({"text":"Again", "model":"speech-2.8-turbo", |
| 1035 | "format":"flac", "voice":"English_Graceful_Lady", "output":"speech.wav"}), |
| 1036 | &ctx, |
| 1037 | ) |
| 1038 | .await |
| 1039 | .unwrap_err(); |
| 1040 | assert!(error.to_string().contains("2013")); |
| 1041 | assert!( |
| 1042 | tool.execute(json!({"text":"Hello","clone_voice":"sample.wav"}), &ctx) |
| 1043 | .await |
| 1044 | .is_err() |
| 1045 | ); |
| 1046 | assert_eq!(std::fs::read(output).unwrap(), b"RIFF"); |
| 1047 | } |
| 1048 | |
| 1049 | #[test] |
| 1050 | fn speech_tool_is_auto_approved_but_not_read_only() { |
| 1051 | let tool = SpeechTool::new(None, None); |
| 1052 | assert_eq!(tool.name(), "speech"); |
| 1053 | assert_eq!(tool.approval_requirement(), ApprovalRequirement::Auto); |
| 1054 | assert!(!tool.is_read_only()); |
| 1055 | let schema = tool.input_schema(); |
| 1056 | assert!(schema.to_string().contains("mimo-v2.5-tts-voiceclone")); |
| 1057 | assert!(schema.to_string().contains("pcm16")); |
| 1058 | assert!(schema["properties"].get("stream").is_none()); |
| 1059 | } |
| 1060 | |
| 1061 | #[tokio::test] |
| 1062 | async fn speech_tool_supports_deepseek_tts_and_rejects_clone_or_mp3() { |
| 1063 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 1064 | use wiremock::matchers::{method, path}; |
| 1065 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 1066 | |
| 1067 | let server = MockServer::start().await; |
| 1068 | Mock::given(method("POST")) |
| 1069 | .and(path("/v1/tools/tts")) |
| 1070 | .respond_with(ResponseTemplate::new(200).set_body_bytes(b"RIFF_DEEPSEEK".to_vec())) |
| 1071 | .mount(&server) |
| 1072 | .await; |
| 1073 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1074 | |
| 1075 | let _lock = lock_test_env(); |
| 1076 | let _cli_source = EnvVarGuard::remove(codewhale_config::CLI_API_KEY_SOURCE_ENV); |
| 1077 | let _legacy_cli_source = |
| 1078 | EnvVarGuard::remove(codewhale_config::LEGACY_CLI_API_KEY_SOURCE_ENV); |
| 1079 | let _cli_key = EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 1080 | |
| 1081 | let config: codewhale_runtime::config::Config = toml::from_str(&format!( |
| 1082 | "provider = \"deepseek\"\n\n[providers.deepseek]\napi_key = \"ds-speech-key\"\nbase_url = \"{}/v1\"\nmodel = \"deepseek-v4\"\n", |
| 1083 | server.uri() |
| 1084 | )) |
| 1085 | .expect("deepseek config parses"); |
| 1086 | let client = CodewhaleClient::new(&config).expect("client"); |
| 1087 | let ctx = ToolContext::new(tmp.path().to_path_buf()); |
| 1088 | let tool = SpeechTool::new(Some(client), None); |
| 1089 | |
| 1090 | let result = tool |
| 1091 | .execute( |
| 1092 | json!({"text": "Hello from DeepSeek", "voice": "tide"}), |
| 1093 | &ctx, |
| 1094 | ) |
| 1095 | .await |
| 1096 | .expect("deepseek speech tool succeeds"); |
| 1097 | assert!(result.success); |
| 1098 | let parsed: Value = serde_json::from_str(&result.content).expect("json"); |
| 1099 | assert_eq!(parsed["model"], "deepseek-tts"); |
| 1100 | assert_eq!(parsed["voice"], "tide"); |
| 1101 | assert_eq!(parsed["format"], "wav"); |
| 1102 | assert_eq!(parsed["base_url"], server.uri()); |
| 1103 | assert_eq!( |
| 1104 | std::fs::read(tmp.path().join("speech.wav")).unwrap(), |
| 1105 | b"RIFF_DEEPSEEK" |
| 1106 | ); |
| 1107 | |
| 1108 | assert!( |
| 1109 | tool.execute(json!({"text": "Hello", "format": "mp3"}), &ctx) |
| 1110 | .await |
| 1111 | .is_err() |
| 1112 | ); |
| 1113 | assert!( |
| 1114 | tool.execute(json!({"text": "Hello", "instruction": "whisper"}), &ctx) |
| 1115 | .await |
| 1116 | .is_err() |
| 1117 | ); |
| 1118 | } |
| 1119 | |
| 1120 | #[allow(clippy::await_holding_lock)] |
| 1121 | #[tokio::test] |
| 1122 | async fn speech_clone_voice_refuses_denied_credential_non_audio_and_oversized_samples() { |
| 1123 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 1124 | |
| 1125 | let _lock = lock_test_env(); |
| 1126 | let workspace = tempfile::tempdir().expect("workspace"); |
| 1127 | let ws_canon = workspace.path().canonicalize().expect("canon ws"); |
| 1128 | let cw_home = ws_canon.join("cw-home"); |
| 1129 | std::fs::create_dir_all(&cw_home).expect("mkdir cw-home"); |
| 1130 | let _cw_home_guard = EnvVarGuard::set("CODEWHALE_HOME", &cw_home); |
| 1131 | let _cfg_guard = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"); |
| 1132 | let _legacy_cfg_guard = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"); |
| 1133 | |
| 1134 | let valid_wav = b"RIFF\x24\x00\x00\x00WAVEfmt "; |
| 1135 | let valid_mp3 = b"ID3\x03\x00\x00\x00\x00\x00\x00"; |
| 1136 | std::fs::write(ws_canon.join(".env"), valid_wav).expect("write .env"); |
| 1137 | std::fs::write(cw_home.join("config.toml"), valid_wav).expect("write config.toml"); |
| 1138 | std::fs::write(ws_canon.join("spoof.wav"), b"SECRET_KEY=123456\n").expect("write spoof"); |
| 1139 | std::fs::write(ws_canon.join("spoof.mp3"), b"NOT_AN_MP3_FILE\n").expect("write spoof mp3"); |
| 1140 | std::fs::write(ws_canon.join("ok.wav"), valid_wav).expect("write ok wav"); |
| 1141 | std::fs::write(ws_canon.join("ok.mp3"), valid_mp3).expect("write ok mp3"); |
| 1142 | let oversized = ws_canon.join("oversized.wav"); |
| 1143 | let oversized_file = std::fs::File::create(&oversized).expect("create oversized"); |
| 1144 | oversized_file |
| 1145 | .set_len((VOICE_CLONE_MAX_RAW_BYTES + 1) as u64) |
| 1146 | .expect("set_len"); |
| 1147 | drop(oversized_file); |
| 1148 | |
| 1149 | let ctx = ToolContext::new(&ws_canon); |
| 1150 | let env_err = encode_voice_clone_data_uri(&ctx, ".env") |
| 1151 | .await |
| 1152 | .expect_err(".env must be refused"); |
| 1153 | assert!( |
| 1154 | matches!(env_err, ToolError::PermissionDenied { .. }), |
| 1155 | "{env_err:?}" |
| 1156 | ); |
| 1157 | |
| 1158 | let trusted_ctx = ToolContext::new(&ws_canon).with_trust_mode(true); |
| 1159 | let cred_err = encode_voice_clone_data_uri( |
| 1160 | &trusted_ctx, |
| 1161 | &cw_home.join("config.toml").to_string_lossy(), |
| 1162 | ) |
| 1163 | .await |
| 1164 | .expect_err("credential path must be refused even in trust mode"); |
| 1165 | assert!( |
| 1166 | matches!(cred_err, ToolError::PermissionDenied { .. }), |
| 1167 | "{cred_err:?}" |
| 1168 | ); |
| 1169 | |
| 1170 | let spoof_wav_err = encode_voice_clone_data_uri(&ctx, "spoof.wav") |
| 1171 | .await |
| 1172 | .expect_err("non-WAV bytes must be refused"); |
| 1173 | assert!( |
| 1174 | matches!(spoof_wav_err, ToolError::InvalidInput { .. }) |
| 1175 | && spoof_wav_err.to_string().contains("not a valid WAV"), |
| 1176 | "{spoof_wav_err:?}" |
| 1177 | ); |
| 1178 | |
| 1179 | let spoof_mp3_err = encode_voice_clone_data_uri(&ctx, "spoof.mp3") |
| 1180 | .await |
| 1181 | .expect_err("non-MP3 bytes must be refused"); |
| 1182 | assert!( |
| 1183 | matches!(spoof_mp3_err, ToolError::InvalidInput { .. }) |
| 1184 | && spoof_mp3_err.to_string().contains("not a valid MP3"), |
| 1185 | "{spoof_mp3_err:?}" |
| 1186 | ); |
| 1187 | |
| 1188 | let ok_wav_uri = encode_voice_clone_data_uri(&ctx, "ok.wav") |
| 1189 | .await |
| 1190 | .expect("valid wav succeeds"); |
| 1191 | assert!(ok_wav_uri.starts_with("data:audio/wav;base64,")); |
| 1192 | let ok_mp3_uri = encode_voice_clone_data_uri(&ctx, "ok.mp3") |
| 1193 | .await |
| 1194 | .expect("valid mp3 succeeds"); |
| 1195 | assert!(ok_mp3_uri.starts_with("data:audio/mpeg;base64,")); |
| 1196 | |
| 1197 | let oversized_err = encode_voice_clone_data_uri(&ctx, "oversized.wav") |
| 1198 | .await |
| 1199 | .expect_err("oversized sample must fail before base64"); |
| 1200 | assert!( |
| 1201 | matches!(oversized_err, ToolError::InvalidInput { .. }) |
| 1202 | && oversized_err |
| 1203 | .to_string() |
| 1204 | .contains("exceeds maximum raw size"), |
| 1205 | "{oversized_err:?}" |
| 1206 | ); |
| 1207 | let cli_oversized_err = encode_voice_clone_sample_data_uri(&oversized) |
| 1208 | .expect_err("CLI sample encoder must enforce pre-encode cap"); |
| 1209 | assert!( |
| 1210 | cli_oversized_err |
| 1211 | .to_string() |
| 1212 | .contains("exceeds maximum raw size"), |
| 1213 | "{cli_oversized_err}" |
| 1214 | ); |
| 1215 | |
| 1216 | let ro_root = tempfile::tempdir().expect("ro_root"); |
| 1217 | let ro_wav = ro_root.path().join("ro.wav"); |
| 1218 | std::fs::write(&ro_wav, valid_wav).expect("write ro wav"); |
| 1219 | let ro_canon = ro_root.path().canonicalize().expect("canon ro"); |
| 1220 | let ro_ctx = ToolContext::new(&ws_canon).with_read_only_roots(vec![ro_canon]); |
| 1221 | let ro_err = encode_voice_clone_data_uri(&ro_ctx, &ro_wav.to_string_lossy()) |
| 1222 | .await |
| 1223 | .expect_err("speech must not widen onto read_only_roots"); |
| 1224 | assert!(matches!(ro_err, ToolError::PathEscape { .. }), "{ro_err:?}"); |
| 1225 | |
| 1226 | #[cfg(unix)] |
| 1227 | { |
| 1228 | let outside = tempfile::tempdir().expect("outside"); |
| 1229 | let orig = outside.path().join("orig.wav"); |
| 1230 | let linked = outside.path().join("linked.wav"); |
| 1231 | std::fs::write(&orig, valid_wav).expect("write orig wav"); |
| 1232 | std::fs::hard_link(&orig, &linked).expect("hardlink"); |
| 1233 | let link_err = encode_voice_clone_data_uri(&trusted_ctx, &linked.to_string_lossy()) |
| 1234 | .await |
| 1235 | .expect_err("outside hardlink must be refused"); |
| 1236 | assert!( |
| 1237 | matches!(link_err, ToolError::PermissionDenied { .. }), |
| 1238 | "{link_err:?}" |
| 1239 | ); |
| 1240 | } |
| 1241 | } |
| 1242 | } |
| 1243 | |
| 1244 | #[cfg(test)] |
| 1245 | #[path = "speech_host_tests.rs"] |
| 1246 | mod speech_host_tests; |
| 1247 | #[cfg(any(test, feature = "test-support"))] |
| 1248 | #[path = "speech_host_test_support.rs"] |
| 1249 | pub mod test_support; |
| 1250 |