mod doctor;
mod hooks;
mod profile;
pub use doctor::doctor;
use std::ffi::OsString;
use std::fs;
use std::io::{self, BufRead, IsTerminal, Write};
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
use crate::agents::{claude, codex};
use crate::store::Store;
use profile::Profile;
const CLAUDE_HOOK: &str = "kaeru hook claude";
const CODEX_HOOK: &str = "kaeru hook codex";
const CODEX_HOOK_NAME: &str = "kaeru: remember this session's tab";
struct HookFile {
agent: &'static str,
path: PathBuf,
command: &'static str,
name: Option<&'static str>,
}
impl HookFile {
fn agent_is_set_up(&self) -> bool {
self.path.parent().is_some_and(Path::is_dir)
}
}
fn hook_files() -> Vec<HookFile> {
let mut files = Vec::new();
if let Some(dir) = claude::config_dir() {
files.push(HookFile {
agent: "Claude Code",
path: dir.join("settings.json"),
command: CLAUDE_HOOK,
name: None,
});
}
if let Some(home) = codex::home_dir() {
files.push(HookFile {
agent: "Codex",
path: home.join("hooks.json"),
command: CODEX_HOOK,
name: Some(CODEX_HOOK_NAME),
});
}
files
}
pub fn install() -> Result<()> {
require_terminal("kaeru install")?;
crate::tui::greet()?;
let profiles = profile::profiles();
if profiles.is_empty() {
println!(
"kaeru install sets up PowerShell on Windows so far. See the roadmap in README.md."
);
}
for profile in &profiles {
install_profile(profile)?;
}
for file in hook_files() {
if !file.agent_is_set_up() {
println!(
"{} isn't set up on this computer, so it gets no hook.",
file.agent
);
continue;
}
if file.command == CODEX_HOOK
&& let Some(config) = codex_config_with_hooks()
{
explain_codex_config(&config);
continue;
}
if install_hook(&file)? && file.command == CODEX_HOOK {
println!(
"Codex runs a new hook only after you trust it. The next time you start Codex, \
it asks about this one, {CODEX_HOOK_NAME:?}: trust it."
);
}
}
if hook_files()
.iter()
.any(|file| file.command == CODEX_HOOK && file.agent_is_set_up())
{
install_codex_no_daemon()?;
}
println!("\nOpen a new tab and run kaeru doctor to check the setup.");
Ok(())
}
fn install_codex_no_daemon() -> Result<()> {
let store = Store::open()?;
let mut config = store.config();
if config.codex_no_daemon {
println!("Tabs that kaeru tracks start Codex with --no-daemon already.");
return Ok(());
}
println!(
"\nCodex runs its sessions in a shared background server, so its hooks can't tell which \
tab a session runs in, and kaeru works it out from when and where the session started. \
Started with --no-daemon, a session runs in its tab, and kaeru knows exactly where it \
is. Codex's remote control needs the background server, so those sessions can't use it."
);
if ask("Start Codex with --no-daemon in the tabs that kaeru tracks?")? {
config.codex_no_daemon = true;
store.save_config(&config)?;
println!("Done. The tabs that you open from now on start Codex this way.");
}
Ok(())
}
pub fn uninstall() -> Result<()> {
require_terminal("kaeru uninstall")?;
for profile in profile::profiles() {
let bytes = read_or_empty(&profile.path)?;
if profile::has_line(&bytes, profile.kind)?
&& ask(&format!(
"Remove kaeru's lines from the {} profile, {}?",
profile.shell,
profile.path.display()
))?
{
write_file(&profile.path, &profile::remove_line(&bytes, profile.kind)?)?;
println!("Removed.");
}
}
for file in hook_files() {
let mut root = read_json(&file.path)?;
if hooks::has_hook(&root, file.command)
&& ask(&format!(
"Remove kaeru's hook from {}'s {}?",
file.agent,
file.path.display()
))?
{
hooks::remove_hook(&mut root, file.command);
write_json(&file.path, &root)?;
let _ = fs::remove_file(backup_of(&file.path));
println!("Removed.");
}
}
if let Some(config) = codex_config_with_hooks()
&& fs::read_to_string(&config).is_ok_and(|text| text.contains(CODEX_HOOK))
{
println!(
"{} runs kaeru's hook. Take out its [[hooks.SessionStart]] entry with {CODEX_HOOK:?} \
yourself.",
config.display()
);
}
let store = Store::open()?;
if ask_default_no(&format!(
"Also delete kaeru's notes, log and options, in {}?",
store.dir().display()
))? {
store.delete_all()?;
println!("Deleted.");
}
Ok(())
}
fn install_profile(profile: &Profile) -> Result<()> {
let bytes = read_or_empty(&profile.path)?;
if profile::has_line(&bytes, profile.kind)? {
println!("The {} profile loads kaeru already.", profile.shell);
} else {
println!(
"\nkaeru adds these lines to the end of the {} profile, {}:\n {}\n {}",
profile.shell,
profile.path.display(),
profile::COMMENT,
profile.kind.line()
);
if ask("Add them?")? {
write_file(&profile.path, &profile::add_line(&bytes, profile.kind)?)?;
println!("Added.");
}
}
if let Some(problem) = bash_profile_problem(profile) {
println!("{problem}");
}
Ok(())
}
fn bash_profile_problem(profile: &Profile) -> Option<String> {
if profile.kind != profile::Kind::Bash {
return None;
}
let bash_profile = profile.path.parent()?.join(".bash_profile");
let text = fs::read_to_string(&bash_profile).ok()?;
(!profile::reads_bashrc(&text)).then(|| {
format!(
"{} doesn't read ~/.bashrc, and Git Bash reads only that file, so add this line to \
it:\n test -f ~/.bashrc && . ~/.bashrc",
bash_profile.display()
)
})
}
fn install_hook(file: &HookFile) -> Result<bool> {
let mut root = read_json(&file.path)?;
if hooks::has_hook(&root, file.command) {
println!("{} runs kaeru's hook already.", file.agent);
return Ok(false);
}
println!(
"\nkaeru adds a SessionStart hook that runs {:?} to {}'s {}.",
file.command,
file.agent,
file.path.display()
);
if !ask("Add it?")? {
return Ok(false);
}
hooks::add_hook(&mut root, file.command, file.name)
.with_context(|| format!("can't add the hook to {}", file.path.display()))?;
if file.path.exists() {
fs::copy(&file.path, backup_of(&file.path))?;
println!(
"The file as it was is kept as {}.",
backup_of(&file.path).display()
);
}
write_json(&file.path, &root)?;
println!("Added.");
Ok(true)
}
fn codex_config_with_hooks() -> Option<PathBuf> {
let config = codex::home_dir()?.join("config.toml");
let text = fs::read_to_string(&config).ok()?;
declares_hooks(&text).then_some(config)
}
fn declares_hooks(config: &str) -> bool {
let Ok(config) = config.parse::<toml::Table>() else {
return false;
};
config
.get("hooks")
.and_then(toml::Value::as_table)
.is_some_and(|hooks| {
hooks.iter().any(|(key, value)| {
key != "state" && value.as_array().is_some_and(|groups| !groups.is_empty())
})
})
}
fn explain_codex_config(config: &Path) {
if fs::read_to_string(config).is_ok_and(|text| text.contains(CODEX_HOOK)) {
println!(
"Codex runs kaeru's hook already, from {}.",
config.display()
);
return;
}
println!(
"\nCodex declares hooks in {} already, and it warns when hooks.json has hooks too. \
Add this to it yourself, and trust the hook when Codex asks about it:\n\n\
[[hooks.SessionStart]]\n\n[[hooks.SessionStart.hooks]]\ntype = \"command\"\n\
command = {CODEX_HOOK:?}\nstatusMessage = {CODEX_HOOK_NAME:?}\n",
config.display()
);
}
fn require_terminal(command: &str) -> Result<()> {
if !io::stdin().is_terminal() {
bail!("{command} asks before each change, so run it in a terminal.");
}
Ok(())
}
fn ask(question: &str) -> Result<bool> {
Ok(answer(question, "[Y/n]")?.is_none_or(|yes| yes))
}
fn ask_default_no(question: &str) -> Result<bool> {
Ok(answer(question, "[y/N]")?.is_some_and(|yes| yes))
}
fn answer(question: &str, choices: &str) -> Result<Option<bool>> {
loop {
print!("{question} {choices} ");
io::stdout().flush()?;
let mut line = String::new();
if io::stdin().lock().read_line(&mut line)? == 0 {
return Ok(Some(false));
}
match line.trim().to_ascii_lowercase().as_str() {
"" => return Ok(None),
"y" | "yes" => return Ok(Some(true)),
"n" | "no" => return Ok(Some(false)),
_ => {}
}
}
}
fn read_or_empty(path: &Path) -> Result<Vec<u8>> {
match fs::read(path) {
Ok(bytes) => Ok(bytes),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Vec::new()),
Err(error) => Err(error).with_context(|| format!("can't read {}", path.display())),
}
}
fn read_json(path: &Path) -> Result<Value> {
let bytes = read_or_empty(path)?;
if bytes.iter().all(u8::is_ascii_whitespace) {
return Ok(json!({}));
}
serde_json::from_slice(&bytes).with_context(|| {
format!(
"can't read {} as JSON, so kaeru leaves it alone",
path.display()
)
})
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
let mut text = serde_json::to_string_pretty(value)?;
text.push('\n');
write_file(path, text.as_bytes())
}
fn write_file(path: &Path, bytes: &[u8]) -> Result<()> {
let linked;
let path = if fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink())
{
linked = fs::canonicalize(path)
.with_context(|| format!("can't follow the link {}", path.display()))?;
linked.as_path()
} else {
path
};
if let Some(folder) = path.parent() {
fs::create_dir_all(folder).with_context(|| format!("can't create {}", folder.display()))?;
}
let mut temp = path.as_os_str().to_owned();
temp.push(".kaeru-tmp");
let temp = PathBuf::from(temp);
fs::write(&temp, bytes).with_context(|| format!("can't write {}", temp.display()))?;
fs::rename(&temp, path).with_context(|| format!("can't write {}", path.display()))
}
fn backup_of(path: &Path) -> PathBuf {
let mut name: OsString = path.as_os_str().to_owned();
name.push(".kaeru-backup");
PathBuf::from(name)
}
fn on_path(program: &str) -> Option<PathBuf> {
std::env::split_paths(&std::env::var_os("PATH")?)
.map(|folder| folder.join(program))
.find(|candidate| candidate.is_file())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codex_s_trust_records_declare_no_hooks() {
let trust = r#"
[hooks.state]
[hooks.state.'C:\Users\demo\.codex\hooks.json:session_start:0:0']
trusted_hash = "sha256:0000"
enabled = true
"#;
let inline = r#"
[[hooks.SessionStart]]
[[hooks.SessionStart.hooks]]
type = "command"
command = "kaeru hook codex"
"#;
assert!(!declares_hooks(trust));
assert!(declares_hooks(inline));
assert!(declares_hooks(&format!("{trust}{inline}")));
assert!(!declares_hooks("model = \"some-model\"\n"));
assert!(!declares_hooks("[hooks\n"));
}
#[test]
fn a_file_that_doesn_t_exist_reads_as_empty() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("missing.json");
assert!(read_or_empty(&missing).unwrap().is_empty());
assert_eq!(read_json(&missing).unwrap(), json!({}));
}
#[test]
fn json_is_written_and_read_back() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("new folder").join("settings.json");
write_json(&path, &json!({ "a": 1 })).unwrap();
assert_eq!(read_json(&path).unwrap(), json!({ "a": 1 }));
assert!(fs::read_to_string(&path).unwrap().ends_with("}\n"));
}
#[test]
fn broken_json_is_left_alone() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
fs::write(&path, "{ not json").unwrap();
assert!(read_json(&path).is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), "{ not json");
}
#[test]
fn writing_through_a_link_keeps_the_link() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("dotfiles-profile.ps1");
let link = dir.path().join("profile.ps1");
fs::write(&target, "old").unwrap();
#[cfg(unix)]
let made = std::os::unix::fs::symlink(&target, &link);
#[cfg(windows)]
let made = std::os::windows::fs::symlink_file(&target, &link);
if made.is_err() {
return;
}
write_file(&link, b"new").unwrap();
assert!(
fs::symlink_metadata(&link)
.unwrap()
.file_type()
.is_symlink()
);
assert_eq!(fs::read_to_string(&target).unwrap(), "new");
}
#[test]
fn the_backup_sits_next_to_the_file() {
assert_eq!(
backup_of(Path::new("settings.json")),
Path::new("settings.json.kaeru-backup")
);
}
}