outloud 0.1.1

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.
//! Newer versions include the reply itself as `last_assistant_message`;
//! older ones only give `transcript_path`, a JSONL file with one event per line.
//!
//! `outloud on|off|toggle|status` switches the voice without touching settings.

use regex::Regex;
use serde_json::Value;
use std::fs::{self, File};
use std::io::{self, BufRead, BufReader, Read, Write};
use std::path::PathBuf;
use std::process::{Command, Stdio};

const MAX_CHARS: usize = 4000;
const SWITCH_WORDS: [&str; 4] = ["on", "off", "toggle", "status"];

fn main() {
    let args: Vec<String> = std::env::args().skip(1).collect();

    // `outloud off`, `outloud toggle` etc. flip the switch and exit.
    // The last matching word wins, so `outloud toggle off` means "off".
    if let Some(word) = args
        .iter()
        .rev()
        .find(|a| SWITCH_WORDS.contains(&a.as_str()))
    {
        switch(word);
        return;
    }

    // A hook should never break Claude Code, so failures exit quietly.
    let dry_run = args.iter().any(|a| a == "--dry-run");
    if let Err(e) = run(dry_run) {
        eprintln!("outloud: {e}");
    }
}

/// The voice is off while this file exists: `~/.outloud-off`.
fn off_flag() -> Option<PathBuf> {
    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
    Some(PathBuf::from(home).join(".outloud-off"))
}

fn is_off() -> bool {
    off_flag().is_some_and(|flag| flag.exists())
}

/// Turns the voice on or off by removing or creating the flag file.
fn switch(word: &str) {
    let Some(flag) = off_flag() else {
        println!("outloud: could not find your home folder");
        return;
    };
    let turn_off = match word {
        "off" => true,
        "on" => false,
        "toggle" => !flag.exists(),
        _ => flag.exists(), // "status": leave it as it is
    };
    // Errors are ignored on purpose: the line below reports what is true now.
    if turn_off {
        let _ = File::create(&flag);
    } else {
        let _ = fs::remove_file(&flag);
    }
    println!("outloud is {}", if flag.exists() { "off" } else { "on" });
}

fn run(dry_run: bool) -> Result<(), Box<dyn std::error::Error>> {
    if is_off() && !dry_run {
        return Ok(());
    }

    let mut input = String::new();
    io::stdin().read_to_string(&mut input)?;
    let hook: Value = serde_json::from_str(&input)?;

    // Prefer the reply Claude Code hands us. The transcript file can lag
    // behind: when this hook runs, the newest reply may not be written yet.
    let reply = match hook["last_assistant_message"].as_str() {
        Some(message) if !message.trim().is_empty() => message.to_string(),
        _ => {
            let path = hook["transcript_path"]
                .as_str()
                .ok_or("no last_assistant_message or transcript_path in hook input")?;
            last_reply(path)?
        }
    };

    let text = clean(&reply);
    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('*'));
    }
}