use std::io::{IsTerminal, Write};
pub const AGENT_MARKERS: &[&str] = &["CLAUDECODE", "CLAUDE_CODE_CHILD_SESSION"];
pub const REFUSAL: &str = "the recovery code wasn't shown, because this doesn't look like a \
terminal a person is at. Run `mnemo recovery-code <file>` in a terminal of your own, not \
through an agent's shell or an editor terminal that one runs in (for example, Claude Code's `!`)";
pub fn refusal_reason() -> Option<String> {
if !std::io::stdout().is_terminal() {
return Some("stdout isn't a terminal".into());
}
if !std::io::stdin().is_terminal() {
return Some("stdin isn't a terminal".into());
}
marker_reason(|k| std::env::var_os(k))
.or_else(|| (!controlling_terminal_opens()).then(|| "no controlling terminal".into()))
}
pub fn marker_reason(get: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<String> {
AGENT_MARKERS
.iter()
.find(|m| get(m).is_some_and(|v| !v.is_empty()))
.map(|m| format!("{m} is set (an agent harness)"))
}
#[cfg(unix)]
fn controlling_terminal_opens() -> bool {
std::fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")
.is_ok()
}
#[cfg(windows)]
fn controlling_terminal_opens() -> bool {
std::fs::OpenOptions::new()
.read(true)
.write(true)
.open("CONOUT$")
.is_ok()
}
#[cfg(not(any(unix, windows)))]
fn controlling_terminal_opens() -> bool {
false
}
pub fn show(code: &str) -> std::io::Result<()> {
rpassword::prompt_password(
"Press Enter to show the recovery code. Make sure this is your own terminal. ",
)?;
let mut tty = open_tty()?;
#[cfg(unix)]
write!(tty, "\x1b[?1049h\x1b[H\x1b[2J")?;
write!(
tty,
"Your recovery code:\r\n\r\n {code}\r\n\r\n\
Write it down and keep it somewhere safe. It's the only way to open this brain \r\n\
on another machine, or here if the keychain entry is lost.\r\n\r\n"
)?;
#[cfg(not(unix))]
write!(
tty,
"Clear the screen (cls) once you've written it down.\r\n\r\n"
)?;
tty.flush()?;
drop(tty);
let r = rpassword::prompt_password("Press Enter when you've written it down. ");
let mut tty = open_tty()?;
#[cfg(unix)]
write!(tty, "\x1b[?1049l")?;
tty.flush()?;
r.map(|_| ())
}
pub fn ask_hidden(prompt: &str) -> std::io::Result<String> {
rpassword::prompt_password(prompt)
}
#[cfg(unix)]
fn open_tty() -> std::io::Result<std::fs::File> {
std::fs::OpenOptions::new().write(true).open("/dev/tty")
}
#[cfg(windows)]
fn open_tty() -> std::io::Result<std::fs::File> {
std::fs::OpenOptions::new().write(true).open("CONOUT$")
}
#[cfg(not(any(unix, windows)))]
fn open_tty() -> std::io::Result<std::fs::File> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"no controlling terminal",
))
}