use anyhow::Result;
use async_trait::async_trait;
use serde_json::json;
use crate::Workspace;
use crate::speech::synth::{self, NotReady, SayOutcome};
use crate::tools::Tool;
const MAX_PHRASE_CHARS: usize = 100;
pub(crate) struct SayTool;
#[async_trait]
impl Tool for SayTool {
fn name(&self) -> &'static str {
"say"
}
fn parameters_schema(&self) -> serde_json::Value {
super::tool_params_schema(
&json!({
"text": {
"type": "string",
"description": format!(
"The phrase to speak, in the language the user speaks — at most \
{MAX_PHRASE_CHARS} characters."
),
}
}),
&["text"],
)
}
async fn execute(&self, _ws: &Workspace, args: serde_json::Value) -> Result<String> {
let Some(text) = args.get("text").and_then(|text| text.as_str()) else {
return Ok(
"Nothing was spoken: `text` is required and names the phrase to say.".into(),
);
};
let text = text.trim();
if text.is_empty() {
return Ok("Nothing was spoken: the phrase is empty.".into());
}
let chars = text.chars().count();
if chars > MAX_PHRASE_CHARS {
return Ok(format!(
"Nothing was spoken: the phrase is {chars} characters long. Say it in one short \
phrase of at most {MAX_PHRASE_CHARS} characters — long text is not read aloud."
));
}
Ok(match synth::say_phrase(text).await {
SayOutcome::Speaking => "Spoken: the phrase plays now.".into(),
SayOutcome::SpeechOff => {
"Nothing was spoken: the user has speech output turned off right now.".into()
}
SayOutcome::Absent => {
"Nothing was spoken: the user is not at the computer right now.".into()
}
SayOutcome::NotReady(reason) => {
format!("Nothing was spoken: {}.", not_ready_reason(&reason))
}
SayOutcome::Failed(reason) => format!("Nothing was spoken: {reason}"),
})
}
}
fn not_ready_reason(reason: &NotReady) -> &'static str {
match reason {
NotReady::ModelsMissing => {
"the speech models are not on this machine yet, and they are being fetched in the \
background"
}
NotReady::LoadFailed => {
"the speech models could not be loaded; the next attempt loads them again"
}
NotReady::NoAudioDevice => "this machine has no audio output device",
NotReady::NoAudioLibrary => crate::audio::LIBRARY_UNAVAILABLE,
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn say(args: serde_json::Value) -> String {
let snapshot = crate::config::CONFIG.snapshot();
assert!(
crate::config::CONFIG.set_string_field("tts_enabled", ""),
"tts_enabled is a known config key"
);
let answer = SayTool
.execute(&crate::workspace::test_ws("test"), args)
.await
.unwrap();
crate::config::CONFIG.swap(snapshot);
answer
}
#[tokio::test]
#[serial_test::serial(speech)]
async fn a_phrase_over_the_limit_is_refused_by_visible_characters() {
let too_long = say(json!({ "text": "a".repeat(101) })).await;
assert!(
too_long.contains("101") && too_long.contains("100"),
"the refusal must name the limit and the length, got: {too_long}"
);
for text in ["é".repeat(100), format!(" {} ", "é".repeat(100))] {
let answer = say(json!({ "text": text })).await;
assert!(
answer.contains("speech output turned off"),
"a phrase within the limit reaches the engine, which refuses it while speech is \
off — got: {answer}"
);
}
}
#[tokio::test]
#[serial_test::serial(speech)]
async fn a_call_without_text_says_so() {
assert!(
say(json!({})).await.contains("`text` is required"),
"a missing phrase must be answered plainly"
);
}
}