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();
if let Some(word) = args
.iter()
.rev()
.find(|a| SWITCH_WORDS.contains(&a.as_str()))
{
switch(word);
return;
}
let dry_run = args.iter().any(|a| a == "--dry-run");
if let Err(e) = run(dry_run) {
eprintln!("outloud: {e}");
}
}
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())
}
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(), };
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)?;
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)
}
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('*'));
}
}