outloud 0.1.0

Claude Code Stop hook that reads each reply out loud with your OS built-in voice
//! Claude Code `Stop` hook: reads Claude's last reply aloud using the
//! operating system's built-in voice (no cloud, no API keys).
//!
//! Claude Code runs this after every reply and sends a JSON object on stdin
//! that includes `transcript_path`, a JSONL file with one event per line.

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() {
    // A hook should never break Claude Code, so failures exit quietly.
    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)
}

/// Finds the most recent assistant event that contains text.
/// (Tool-call-only events are skipped.)
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; // ignore malformed lines
        };
        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)
}

/// Removes code blocks and markdown so the voice reads only prose.
fn clean(text: &str) -> String {
    let rules = [
        (r"(?s)```.*?```", " (code block) "), // fenced code
        (r"`([^`]*)`", "$1"),                 // inline code -> plain
        (r"\[([^\]]*)\]\([^)]*\)", "$1"),     // [label](url) -> label
        (r"[#*_>|]+", " "),                   // headings, bold, quotes, tables
    ];
    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()
}

/// Picks the built-in speech command for this OS. Each reads text from stdin.
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"]
    }
}

/// Starts the voice and returns right away, so Claude Code isn't blocked.
/// Text goes in over stdin (no shell), so nothing in a reply can run as a command.
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())?;
    // stdin is dropped here, closing the pipe so the voice knows the text ended.
    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('*'));
    }
}