kaeru 0.1.2

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! `kaeru install`, `kaeru uninstall` and `kaeru doctor`: the line in the
//! shell profiles and the agents' hooks. These files aren't kaeru's, so
//! kaeru asks before it changes each one, and `kaeru uninstall` takes out
//! exactly what `kaeru install` put in.

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;

/// The command that Claude Code's hook runs.
const CLAUDE_HOOK: &str = "kaeru hook claude";

/// The command that Codex's hook runs.
const CODEX_HOOK: &str = "kaeru hook codex";

/// The name of Codex's hook, which Codex shows when it asks you to trust the
/// hook.
const CODEX_HOOK_NAME: &str = "kaeru: remember this session's tab";

/// An agent's hook file.
struct HookFile {
    /// The agent, as kaeru names it to you.
    agent: &'static str,
    /// The file.
    path: PathBuf,
    /// The command that kaeru's hook runs.
    command: &'static str,
    /// The name of kaeru's hook, for an agent that shows hooks by name.
    name: Option<&'static str>,
}

impl HookFile {
    /// Returns whether the agent is set up on this computer: its folder
    /// exists. An agent that never ran here has nothing to hook into.
    fn agent_is_set_up(&self) -> bool {
        self.path.parent().is_some_and(Path::is_dir)
    }
}

/// Returns the agents' hook files: Claude Code's `settings.json`, and Codex's
/// `hooks.json`.
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
}

/// Sets kaeru up, for `kaeru install`: the line in each PowerShell profile
/// and in Git Bash's `~/.bashrc`, and a hook for each agent. It starts with
/// kaeru's frog, and asks before each change.
///
/// # Errors
///
/// Fails when it doesn't run in a terminal, so that it can't ask, or when a
/// file can't be read or written.
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(())
}

/// Asks whether the tabs that kaeru tracks should start Codex with
/// `--no-daemon`, and keeps the answer in kaeru's options.
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(())
}

/// Removes what `kaeru install` added, for `kaeru uninstall`. It asks before
/// each change, and also offers to delete kaeru's notes and options.
///
/// # Errors
///
/// Fails when it doesn't run in a terminal, so that it can't ask, or when a
/// file can't be read or written.
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(())
}

/// Adds kaeru's lines to a shell profile, after asking.
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(())
}

/// Returns what is wrong when Git Bash wouldn't run kaeru's line in
/// `~/.bashrc`: its `~/.bash_profile`, which login shells read instead,
/// doesn't read `~/.bashrc`. When there is no `~/.bash_profile`, Git Bash
/// writes one that does.
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()
        )
    })
}

/// Adds kaeru's hook to an agent's hook file, after asking, and returns
/// whether it did. It keeps a copy of the file as it was, next to it.
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)
}

/// Returns Codex's `config.toml` when it declares hooks itself. Codex warns
/// when one folder has hooks in both `config.toml` and `hooks.json`, so then
/// kaeru leaves the hook for you to add there.
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)
}

/// Returns whether the text of a Codex `config.toml` declares hooks: whether
/// its `hooks` table lists hooks for an event, as `[[hooks.SessionStart]]`
/// does. Codex also keeps which hooks you trust in that table, under
/// `[hooks.state]`, which declares none. A file that isn't valid TOML declares
/// none either, since Codex can't read it.
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())
            })
        })
}

/// Tells you how to add kaeru's hook to a Codex `config.toml` that declares
/// hooks itself.
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()
    );
}

/// Fails unless standard input is a terminal, since `command` asks questions.
fn require_terminal(command: &str) -> Result<()> {
    if !io::stdin().is_terminal() {
        bail!("{command} asks before each change, so run it in a terminal.");
    }
    Ok(())
}

/// Asks a yes or no question, where yes is the default.
fn ask(question: &str) -> Result<bool> {
    Ok(answer(question, "[Y/n]")?.is_none_or(|yes| yes))
}

/// Asks a yes or no question, where no is the default.
fn ask_default_no(question: &str) -> Result<bool> {
    Ok(answer(question, "[y/N]")?.is_some_and(|yes| yes))
}

/// Asks a question until the answer is yes, no or empty, and returns it:
/// `None` for an empty answer, which means the default.
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)),
            _ => {}
        }
    }
}

/// Returns a file's bytes, or nothing when the file doesn't exist yet.
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())),
    }
}

/// Returns a JSON file's contents, or an empty object when the file doesn't
/// exist yet.
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()
        )
    })
}

/// Writes a JSON file, indented as these files usually are.
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())
}

/// Writes a file, creating its folder when needed. The bytes go to a
/// temporary file that is then renamed, to avoid a half-written file. When
/// the path is a symbolic link, as in many dotfiles setups, the file it
/// points to is written, so that the link stays a link.
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()))
}

/// Returns the path of the copy that `kaeru install` keeps of a file it
/// changes.
fn backup_of(path: &Path) -> PathBuf {
    let mut name: OsString = path.as_os_str().to_owned();
    name.push(".kaeru-backup");
    PathBuf::from(name)
}

/// Returns where a program is on the PATH, if it is.
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() {
            // Windows lets only some users make links, such as in developer
            // mode, so the check can't run everywhere.
            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")
        );
    }
}