use regex::Regex;
use serde_json::Value;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read, Write};
use std::process::{Command, Stdio};
const MAX_CHARS: usize = 4000;
fn main() {
if let Err(e) = run() {
eprintln!("outloud: {e}");
}
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
let dry_run = std::env::args().any(|a| a == "--dry-run");
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let hook: Value = serde_json::from_str(&input)?;
let path = hook["transcript_path"]
.as_str()
.ok_or("no transcript_path in hook input")?;
let text = clean(&last_reply(path)?);
if text.is_empty() {
return Ok(());
}
if dry_run {
println!("{:?}\n---\n{text}", speech_command());
return Ok(());
}
speak(&text)
}
fn last_reply(path: &str) -> io::Result<String> {
let mut last = String::new();
for line in BufReader::new(File::open(path)?).lines() {
let Ok(event) = serde_json::from_str::<Value>(&line?) else {
continue; };
if event["type"] != "assistant" {
continue;
}
let Some(blocks) = event["message"]["content"].as_array() else {
continue;
};
let parts: Vec<&str> = blocks
.iter()
.filter(|b| b["type"] == "text")
.filter_map(|b| b["text"].as_str())
.collect();
if !parts.is_empty() {
last = parts.join("\n");
}
}
Ok(last)
}
fn clean(text: &str) -> String {
let rules = [
(r"(?s)```.*?```", " (code block) "), (r"`([^`]*)`", "$1"), (r"\[([^\]]*)\]\([^)]*\)", "$1"), (r"[#*_>|]+", " "), ];
let mut out = text.to_string();
for (pattern, replacement) in rules {
out = Regex::new(pattern)
.unwrap()
.replace_all(&out, replacement)
.into_owned();
}
out.trim().chars().take(MAX_CHARS).collect()
}
fn speech_command() -> Vec<&'static str> {
if cfg!(target_os = "macos") {
vec!["say"]
} else if cfg!(windows) {
vec![
"powershell",
"-NoProfile",
"-Command",
"Add-Type -AssemblyName System.Speech; \
(New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak([Console]::In.ReadToEnd())",
]
} else if Command::new("espeak-ng").arg("--version").output().is_ok() {
vec!["espeak-ng"]
} else {
vec!["spd-say", "-e"]
}
}
fn speak(text: &str) -> Result<(), Box<dyn std::error::Error>> {
let cmd = speech_command();
let mut child = Command::new(cmd[0])
.args(&cmd[1..])
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?;
child.stdin.take().ok_or("no stdin")?.write_all(text.as_bytes())?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_markdown_and_code() {
let s = clean("## Done\nFixed **the bug** in `main.rs`. See [docs](http://x).\n```rust\nfn main(){}\n```\nTests pass.");
assert!(s.contains("Fixed the bug in main.rs. See docs."));
assert!(s.contains("(code block)"));
assert!(!s.contains("fn main"));
assert!(!s.contains('#') && !s.contains('*'));
}
}