edgecrab-tools 0.1.0

Tool registry, ToolHandler trait, and 50+ tool implementations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! # tts — Text-to-speech conversion
//!
//! WHY TTS: Voice output is a key feature of hermes-agent for accessibility
//! and hands-free workflows. EdgeCrab supports three backends:
//!
//! ```text
//!   text_to_speech("Hello world")
//!//!       ├──→ ElevenLabs API (if ELEVENLABS_API_KEY is set)
//!       │         └──→ POST /v1/text-to-speech/{voice} → save to file
//!//!       ├──→ OpenAI TTS API (if OPENAI_API_KEY is set)
//!       │         └──→ POST /v1/audio/speech → save to file
//!//!       └──→ edge-tts (free, no key) — default fallback
//!                 └──→ subprocess: edge-tts --text "..." -o output.mp3
//! ```
//!
//! Provider can be forced via `tts.provider` in config.yaml or auto-detected.

use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;
use std::path::{Path, PathBuf};

use edgecrab_types::{ToolError, ToolSchema};

use crate::registry::{ToolContext, ToolHandler};

/// Default voice for edge-tts (Microsoft Edge neural voices).
const DEFAULT_EDGE_TTS_VOICE: &str = "en-US-AriaNeural";

/// Default voice for OpenAI TTS.
const DEFAULT_OPENAI_VOICE: &str = "alloy";

/// Default voice ID for ElevenLabs.
const DEFAULT_ELEVENLABS_VOICE_ID: &str = "21m00Tcm4TlvDq8ikWAM"; // Rachel

/// Check if the ElevenLabs API key is available for TTS.
fn elevenlabs_tts_available() -> bool {
    std::env::var("ELEVENLABS_API_KEY")
        .map(|k| !k.is_empty())
        .unwrap_or(false)
}

/// Check if the edge-tts Python package is available.
fn edge_tts_available() -> bool {
    std::process::Command::new("edge-tts")
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Check if the OpenAI API key is available for TTS.
fn openai_tts_available() -> bool {
    std::env::var("OPENAI_API_KEY")
        .map(|k| !k.is_empty())
        .unwrap_or(false)
}

/// Determine the TTS backend to use.
enum TtsBackend {
    ElevenLabs,
    OpenAi,
    EdgeTts,
    None,
}

fn detect_backend() -> TtsBackend {
    // Check if user has configured a preferred provider via env
    if let Ok(pref) = std::env::var("EDGECRAB_TTS_PROVIDER") {
        match pref.to_lowercase().as_str() {
            "elevenlabs" | "eleven" if elevenlabs_tts_available() => return TtsBackend::ElevenLabs,
            "openai" if openai_tts_available() => return TtsBackend::OpenAi,
            "edge-tts" | "edge" if edge_tts_available() => return TtsBackend::EdgeTts,
            _ => {} // fall through to auto-detect
        }
    }
    // Auto-detect: prefer edge-tts (free), then elevenlabs, then openai
    if edge_tts_available() {
        return TtsBackend::EdgeTts;
    }
    if elevenlabs_tts_available() {
        return TtsBackend::ElevenLabs;
    }
    if openai_tts_available() {
        return TtsBackend::OpenAi;
    }
    TtsBackend::None
}

/// Generate speech using edge-tts subprocess.
async fn tts_edge(text: &str, voice: &str, output_path: &Path) -> Result<String, ToolError> {
    let output = tokio::process::Command::new("edge-tts")
        .args([
            "--text",
            text,
            "--voice",
            voice,
            "--write-media",
            &output_path.to_string_lossy(),
        ])
        .output()
        .await
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "text_to_speech".into(),
            message: format!("Failed to run edge-tts: {e}"),
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(ToolError::ExecutionFailed {
            tool: "text_to_speech".into(),
            message: format!("edge-tts failed: {stderr}"),
        });
    }

    Ok(output_path.to_string_lossy().into_owned())
}

/// Generate speech using OpenAI TTS API.
async fn tts_openai(text: &str, voice: &str, output_path: &Path) -> Result<String, ToolError> {
    let api_key = std::env::var("OPENAI_API_KEY").map_err(|_| ToolError::Unavailable {
        tool: "text_to_speech".into(),
        reason: "OPENAI_API_KEY not set".into(),
    })?;

    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(30))
        .build()
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "text_to_speech".into(),
            message: format!("HTTP client error: {e}"),
        })?;

    let resp = client
        .post("https://api.openai.com/v1/audio/speech")
        .bearer_auth(&api_key)
        .json(&json!({
            "model": "tts-1",
            "input": text,
            "voice": voice,
            "response_format": "mp3"
        }))
        .send()
        .await
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "text_to_speech".into(),
            message: format!("OpenAI TTS API error: {e}"),
        })?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        return Err(ToolError::ExecutionFailed {
            tool: "text_to_speech".into(),
            message: format!("OpenAI TTS API returned {status}: {body}"),
        });
    }

    let bytes = resp.bytes().await.map_err(|e| ToolError::ExecutionFailed {
        tool: "text_to_speech".into(),
        message: format!("Failed to read audio response: {e}"),
    })?;

    tokio::fs::write(output_path, &bytes)
        .await
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "text_to_speech".into(),
            message: format!("Failed to write audio file: {e}"),
        })?;

    Ok(output_path.to_string_lossy().into_owned())
}

/// Generate speech using ElevenLabs TTS API.
async fn tts_elevenlabs(
    text: &str,
    voice_id: &str,
    output_path: &Path,
) -> Result<String, ToolError> {
    let api_key = std::env::var("ELEVENLABS_API_KEY").map_err(|_| ToolError::Unavailable {
        tool: "text_to_speech".into(),
        reason: "ELEVENLABS_API_KEY not set".into(),
    })?;

    let model_id =
        std::env::var("ELEVENLABS_MODEL_ID").unwrap_or_else(|_| "eleven_turbo_v2".to_string());

    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(60))
        .build()
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "text_to_speech".into(),
            message: format!("HTTP client error: {e}"),
        })?;

    let url = format!("https://api.elevenlabs.io/v1/text-to-speech/{voice_id}");

    let resp = client
        .post(&url)
        .header("xi-api-key", &api_key)
        .header("Content-Type", "application/json")
        .header("Accept", "audio/mpeg")
        .json(&json!({
            "text": text,
            "model_id": model_id,
            "voice_settings": {
                "stability": 0.5,
                "similarity_boost": 0.75
            }
        }))
        .send()
        .await
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "text_to_speech".into(),
            message: format!("ElevenLabs TTS API error: {e}"),
        })?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        return Err(ToolError::ExecutionFailed {
            tool: "text_to_speech".into(),
            message: format!("ElevenLabs TTS API returned {status}: {body}"),
        });
    }

    let bytes = resp.bytes().await.map_err(|e| ToolError::ExecutionFailed {
        tool: "text_to_speech".into(),
        message: format!("Failed to read audio response: {e}"),
    })?;

    tokio::fs::write(output_path, &bytes)
        .await
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "text_to_speech".into(),
            message: format!("Failed to write audio file: {e}"),
        })?;

    Ok(output_path.to_string_lossy().into_owned())
}

// ─── text_to_speech ────────────────────────────────────────────

pub struct TextToSpeechTool;

#[derive(Deserialize)]
struct TtsArgs {
    /// Text to convert to speech.
    text: String,
    /// Voice name (backend-dependent). Defaults to a sensible voice per backend.
    #[serde(default)]
    voice: Option<String>,
    /// Output file path. If omitted, saves to a temp file.
    #[serde(default)]
    output_path: Option<String>,
}

#[async_trait]
impl ToolHandler for TextToSpeechTool {
    fn name(&self) -> &'static str {
        "text_to_speech"
    }

    fn toolset(&self) -> &'static str {
        "media"
    }

    fn emoji(&self) -> &'static str {
        "🔊"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "text_to_speech".into(),
            description: "Convert text to speech audio. Uses edge-tts (free), OpenAI TTS API, \
                 or ElevenLabs API. Returns the path to the generated audio file."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "text": {
                        "type": "string",
                        "description": "Text to convert to speech"
                    },
                    "voice": {
                        "type": "string",
                        "description": "Voice name (e.g. 'en-US-AriaNeural' for edge-tts, 'alloy' for OpenAI)"
                    },
                    "output_path": {
                        "type": "string",
                        "description": "Output file path for the audio. Defaults to a temp file."
                    }
                },
                "required": ["text"]
            }),
            strict: None,
        }
    }

    fn is_available(&self) -> bool {
        edge_tts_available() || openai_tts_available() || elevenlabs_tts_available()
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        if ctx.cancel.is_cancelled() {
            return Err(ToolError::Other("Cancelled".into()));
        }

        let args: TtsArgs = serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
            tool: "text_to_speech".into(),
            message: e.to_string(),
        })?;

        if args.text.trim().is_empty() {
            return Err(ToolError::InvalidArgs {
                tool: "text_to_speech".into(),
                message: "Text cannot be empty".into(),
            });
        }

        // Determine output path
        let output_path = match args.output_path {
            Some(ref p) => PathBuf::from(p),
            None => {
                let tmp_dir = std::env::temp_dir().join("edgecrab_tts");
                tokio::fs::create_dir_all(&tmp_dir).await.map_err(|e| {
                    ToolError::ExecutionFailed {
                        tool: "text_to_speech".into(),
                        message: format!("Failed to create temp dir: {e}"),
                    }
                })?;
                let id = uuid::Uuid::new_v4();
                tmp_dir.join(format!("speech_{id}.mp3"))
            }
        };

        if ctx.cancel.is_cancelled() {
            return Err(ToolError::Other("Cancelled".into()));
        }

        let backend = detect_backend();
        let result = match backend {
            TtsBackend::EdgeTts => {
                let voice = args.voice.as_deref().unwrap_or(DEFAULT_EDGE_TTS_VOICE);
                tts_edge(&args.text, voice, &output_path).await?
            }
            TtsBackend::ElevenLabs => {
                let voice_id = args.voice.as_deref().unwrap_or(DEFAULT_ELEVENLABS_VOICE_ID);
                tts_elevenlabs(&args.text, voice_id, &output_path).await?
            }
            TtsBackend::OpenAi => {
                let voice = args.voice.as_deref().unwrap_or(DEFAULT_OPENAI_VOICE);
                tts_openai(&args.text, voice, &output_path).await?
            }
            TtsBackend::None => {
                return Err(ToolError::Unavailable {
                    tool: "text_to_speech".into(),
                    reason: "No TTS backend available. Install edge-tts (pip install edge-tts), \
                             set OPENAI_API_KEY, or set ELEVENLABS_API_KEY."
                        .into(),
                });
            }
        };

        Ok(format!("Audio saved to: {result}"))
    }
}

inventory::submit!(&TextToSpeechTool as &dyn ToolHandler);

// ─── Tests ────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tts_schema_valid() {
        let schema = TextToSpeechTool.schema();
        assert_eq!(schema.name, "text_to_speech");
        let required = schema.parameters["required"].as_array().expect("array");
        assert!(required.iter().any(|v| v == "text"));
    }

    #[test]
    fn tts_toolset() {
        assert_eq!(TextToSpeechTool.toolset(), "media");
    }

    #[test]
    fn tts_emoji() {
        assert_eq!(TextToSpeechTool.emoji(), "🔊");
    }

    #[test]
    fn detect_backend_returns_something() {
        // In CI neither may be available, but the function should not panic
        let _backend = detect_backend();
    }

    #[tokio::test]
    async fn tts_rejects_empty_text() {
        let ctx = ToolContext::test_context();
        let result = TextToSpeechTool.execute(json!({"text": "  "}), &ctx).await;
        assert!(result.is_err());
        let err = result.expect_err("empty text");
        assert!(err.to_string().contains("empty"));
    }

    #[tokio::test]
    async fn tts_rejects_missing_text() {
        let ctx = ToolContext::test_context();
        let result = TextToSpeechTool.execute(json!({}), &ctx).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn tts_cancelled() {
        let ctx = ToolContext::test_context();
        ctx.cancel.cancel();
        let result = TextToSpeechTool
            .execute(json!({"text": "hello"}), &ctx)
            .await;
        assert!(result.is_err());
        assert!(
            result
                .expect_err("cancelled")
                .to_string()
                .contains("Cancelled")
        );
    }

    #[test]
    fn default_voices_are_not_empty() {
        assert!(!DEFAULT_EDGE_TTS_VOICE.is_empty());
        assert!(!DEFAULT_OPENAI_VOICE.is_empty());
    }
}