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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Codex: how to recognize its process, which runs are interactive, where it
//! keeps its files, and how to resume a session. Its `SessionStart` hook
//! sends the same fields as Claude Code's, which `agents::HookInput` reads.
//!
//! Codex runs the sessions of its windows in one shared background server,
//! unless a window starts with `--no-daemon`. Then the server runs the hooks,
//! so the hook's process tree doesn't lead to the window's tab, and
//! [`window_of`] works out which window shows the session.

use std::path::{Path, PathBuf};

/// The subcommands of Codex (0.172) that don't open its interactive screen,
/// so that their runs are not tabs. `resume`, `fork` and `agents` open it,
/// and so does `codex` alone.
pub const ONE_OFF_COMMANDS: [&str; 33] = [
    "a",
    "app",
    "app-server",
    "apply",
    "archive",
    "cloud",
    "cloud-tasks",
    "completion",
    "debug",
    "delete",
    "doctor",
    "e",
    "exec",
    "exec-server",
    "execpolicy",
    "features",
    "git-credential",
    "help",
    "login",
    "logout",
    "mcp",
    "mcp-server",
    "migrate-nfs-db",
    "migrate-rollouts",
    "plugin",
    "queue",
    "remote-control",
    "responses-api-proxy",
    "review",
    "sandbox",
    "tcp-tunnel",
    "unarchive",
    "update",
];

/// How long after a Codex window starts it can create its first session.
/// Codex creates it right away, unless it first asks something, such as
/// whether to trust a new hook.
const FIRST_SESSION_MS: u64 = 10_000;

/// The originator that Codex writes into the files of sessions that one of
/// its windows created.
const WINDOW_ORIGINATOR: &str = "codex-tui";

/// Returns the command that brings a session back: `codex resume <id>`, or
/// plain `codex` when the conversation can't be resumed because it never got
/// a message or its file is gone.
pub fn resume_command(session_id: &str, conversation_exists: bool) -> Vec<String> {
    if conversation_exists && super::is_uuid(session_id) {
        vec!["codex".into(), "resume".into(), session_id.into()]
    } else {
        vec!["codex".into()]
    }
}

/// Returns whether a process is the Codex CLI: its native executable, named
/// `codex` or, as in its release downloads, `codex-<target>`, or Node running
/// the launcher of the npm package `@openai/codex`. On Windows the launcher
/// starts the native executable as a child, which is nearer to the hook.
pub fn is_codex_process(name: &str, command_line: &str) -> bool {
    let name = name.to_ascii_lowercase();
    let stem = name.strip_suffix(".exe").unwrap_or(&name);
    match stem {
        "codex" => true,
        "node" => command_line.contains("@openai/codex") || command_line.contains(r"@openai\codex"),
        _ => stem.starts_with("codex-"),
    }
}

/// Returns whether a process with this executable name may be the Codex CLI,
/// before its command line is read: Codex's own names, and Node.
pub fn may_be_codex(name: &str) -> bool {
    is_codex_process(name, "") || {
        let name = name.to_ascii_lowercase();
        name == "node" || name == "node.exe"
    }
}

/// Returns Codex's own arguments: those after its executable, or, for the npm
/// launcher, after its script.
fn codex_arguments(arguments: &[String]) -> &[String] {
    let start = arguments
        .iter()
        .position(|argument| argument.ends_with("codex.js"))
        .map_or(1, |script| script + 1);
    arguments.get(start..).unwrap_or_default()
}

/// Returns whether a Codex process's arguments open Codex's interactive
/// screen. One-off runs, such as `codex exec`, are not tabs, so kaeru ignores
/// them. Each argument is compared whole, so that a prompt such as
/// `codex "review my code"` isn't taken for the `review` subcommand.
pub fn is_interactive(arguments: &[String]) -> bool {
    !codex_arguments(arguments)
        .iter()
        .any(|argument| ONE_OFF_COMMANDS.contains(&argument.as_str()))
}

/// Returns whether a Codex process is Codex's shared background server,
/// `codex app-server ... --managed-daemon`, which runs the sessions of the
/// windows that don't start with `--no-daemon`, and their hooks.
pub fn is_shared_server(arguments: &[String]) -> bool {
    let own = codex_arguments(arguments);
    own.iter().any(|argument| argument == "app-server")
        && own.iter().any(|argument| argument == "--managed-daemon")
}

/// Returns the folder that a Codex window works in: the one that its `--cd`
/// (`-C`) option names, or else the folder that its process works in.
pub fn window_folder(arguments: &[String], cwd: Option<&Path>) -> Option<PathBuf> {
    let own = codex_arguments(arguments);
    let named = own.iter().enumerate().find_map(|(index, argument)| {
        if argument == "-C" || argument == "--cd" {
            own.get(index + 1).cloned()
        } else {
            argument.strip_prefix("--cd=").map(String::from)
        }
    });
    match named.map(PathBuf::from) {
        Some(folder) if folder.is_absolute() => Some(folder),
        Some(folder) => cwd.map(|cwd| cwd.join(folder)),
        None => cwd.map(Path::to_path_buf),
    }
}

/// Returns when Codex created a session, in milliseconds since the Unix
/// epoch, from its id: Codex's session ids are version 7 UUIDs, whose first
/// 48 bits are that time.
pub fn created_ms(session_id: &str) -> Option<u64> {
    let digits: String = session_id.chars().filter(|&c| c != '-').collect();
    if digits.len() != 32 || digits.as_bytes()[12] != b'7' {
        return None;
    }
    u64::from_str_radix(&digits[..12], 16).ok()
}

/// Returns whether a Codex window created a session, from the first line of
/// the session's file. It is `false` only when that line names another
/// program, such as Codex's remote control, so that a file that can't be read
/// doesn't stop kaeru.
pub fn created_by_a_window(first_line: &str) -> bool {
    let Ok(record) = serde_json::from_str::<serde_json::Value>(first_line) else {
        return true;
    };
    record
        .pointer("/payload/originator")
        .and_then(serde_json::Value::as_str)
        .is_none_or(|originator| originator == WINDOW_ORIGINATOR)
}

/// A Codex window: a Codex process that shows sessions, which may run in
/// Codex's shared server rather than in it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Window {
    /// When the window started, in milliseconds since the Unix epoch, or 0
    /// when that can't be read.
    pub started_ms: u64,
    /// The arguments it started with, its executable first.
    pub arguments: Vec<String>,
    /// The folder it works in, if that can be read.
    pub folder: Option<String>,
}

/// A session that Codex's shared server runs, as its hook tells it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServerSession<'a> {
    /// The session's id.
    pub id: &'a str,
    /// The folder the session runs in.
    pub cwd: &'a str,
    /// Why the hook runs: `startup`, `resume`, `clear`, `compact` or
    /// `fork`.
    pub source: Option<&'a str>,
    /// Whether a Codex window created the session, as
    /// [`created_by_a_window`] tells.
    pub from_window: bool,
}

/// Which window shows a session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Shown {
    /// The window at this place in the list shows it. `exact` is `true` when
    /// the window was started with the session's id.
    In { window: usize, exact: bool },
    /// More than one window could show it, so kaeru doesn't guess. The text
    /// says why.
    Unsure(&'static str),
    /// No window shows it, because another program started it, or its
    /// window is gone.
    Nowhere,
}

/// Returns which of the Codex windows shows a session that Codex's shared
/// server runs. Each rule is tried in turn, and a rule that fits more than one
/// window gives [`Shown::Unsure`] instead of a guess:
///
/// 1. A window started with the session's id, as `codex resume <id>` is.
/// 2. For a new session, the window in the session's folder that started
///    shortly before Codex created the session, which its id tells.
/// 3. Otherwise, such as after `/new` in a window, the only window in the
///    session's folder. A new session can't be shown by a window that
///    started after it.
///
/// Rules 2 and 3 only apply to sessions that a window created.
pub fn window_of(session: &ServerSession, windows: &[Window]) -> Shown {
    let matching = |fits: &dyn Fn(&Window) -> bool| -> Vec<usize> {
        (0..windows.len())
            .filter(|&index| fits(&windows[index]))
            .collect()
    };
    let by_id = matching(&|window| {
        codex_arguments(&window.arguments)
            .iter()
            .any(|a| a == session.id)
    });
    match by_id.as_slice() {
        [] => {}
        [window] => {
            return Shown::In {
                window: *window,
                exact: true,
            };
        }
        _ => return Shown::Unsure("more than one Codex window was started with its id"),
    }
    if !session.from_window {
        return Shown::Nowhere;
    }
    let is_new = matches!(session.source, Some("startup" | "clear" | "fork"));
    let created = created_ms(session.id).filter(|_| is_new);
    // A window whose folder can't be read could be in any folder.
    let here = |window: &Window| {
        window
            .folder
            .as_deref()
            .is_none_or(|folder| same_folder(folder, session.cwd))
    };
    if let Some(created) = created {
        let first = matching(&|window| {
            here(window)
                && window.started_ms <= created
                && created <= window.started_ms + FIRST_SESSION_MS
        });
        match first.as_slice() {
            [] => {}
            [window] => {
                return Shown::In {
                    window: *window,
                    exact: false,
                };
            }
            _ => {
                return Shown::Unsure(
                    "two Codex windows in its folder started at about the same time",
                );
            }
        }
    }
    let alone = matching(&|window| {
        here(window) && created.is_none_or(|created| window.started_ms <= created)
    });
    match alone.as_slice() {
        [] => Shown::Nowhere,
        [window] => Shown::In {
            window: *window,
            exact: false,
        },
        _ => Shown::Unsure("more than one Codex window runs in its folder"),
    }
}

/// Returns whether two paths name the same folder, ignoring a separator at
/// the end and, on Windows, the case of letters.
fn same_folder(a: &str, b: &str) -> bool {
    let a = a.trim_end_matches(['\\', '/']);
    let b = b.trim_end_matches(['\\', '/']);
    if cfg!(windows) {
        a.eq_ignore_ascii_case(b)
    } else {
        a == b
    }
}

/// Returns Codex's home folder: `CODEX_HOME` when that is set, or else
/// `~/.codex`.
pub fn home_dir() -> Option<PathBuf> {
    std::env::var_os("CODEX_HOME")
        .map(PathBuf::from)
        .or_else(|| dirs::home_dir().map(|home| home.join(".codex")))
}

#[cfg(test)]
mod tests {
    use super::*;

    const ID: &str = "00000000-0000-4000-8000-000000000001";

    /// When Codex created the new session in these tests.
    const CREATED: u64 = 100_000;

    /// Returns a made-up version 7 session id that Codex created at
    /// `created_ms`.
    fn new_id(created_ms: u64) -> String {
        format!(
            "{:08x}-{:04x}-7000-8000-000000000001",
            created_ms >> 16,
            created_ms & 0xffff
        )
    }

    fn args(words: &[&str]) -> Vec<String> {
        words.iter().map(|&word| word.into()).collect()
    }

    fn window(started_ms: u64, words: &[&str], folder: &str) -> Window {
        Window {
            started_ms,
            arguments: args(words),
            folder: Some(folder.into()),
        }
    }

    fn session<'a>(id: &'a str, source: &'a str) -> ServerSession<'a> {
        ServerSession {
            id,
            cwd: "/home/demo/code/api-server",
            source: Some(source),
            from_window: true,
        }
    }

    const HERE: &str = "/home/demo/code/api-server";
    const THERE: &str = "/home/demo/code/web-ui";

    #[test]
    fn resumes_only_conversations_that_exist() {
        assert_eq!(resume_command(ID, true), ["codex", "resume", ID]);
        assert_eq!(resume_command(ID, false), ["codex"]);
        assert_eq!(resume_command("bad", true), ["codex"]);
    }

    #[test]
    fn recognizes_the_codex_process() {
        assert!(is_codex_process("codex.exe", ""));
        assert!(is_codex_process("codex", ""));
        assert!(is_codex_process("codex-x86_64-pc-windows-msvc.exe", ""));
        assert!(is_codex_process(
            "node.exe",
            r"node C:\npm\node_modules\@openai\codex\bin\codex.js"
        ));
        assert!(!is_codex_process("node.exe", "node server.js"));
        assert!(!is_codex_process("codexx.exe", ""));
        assert!(may_be_codex("node.exe"));
        assert!(may_be_codex("codex"));
        assert!(!may_be_codex("bash"));
    }

    #[test]
    fn one_off_runs_are_not_interactive() {
        assert!(is_interactive(&args(&["codex"])));
        assert!(is_interactive(&args(&["codex", "resume", ID])));
        assert!(is_interactive(&args(&[
            r"C:\tools\codex.exe",
            "--model",
            "x"
        ])));
        assert!(is_interactive(&args(&["codex", "--no-daemon", "agents"])));
        assert!(!is_interactive(&args(&["codex", "exec", "fix the tests"])));
        assert!(!is_interactive(&args(&["codex", "app-server"])));
    }

    #[test]
    fn a_prompt_is_not_taken_for_a_subcommand() {
        assert!(is_interactive(&args(&["codex", "review my code"])));
        assert!(!is_interactive(&args(&["codex", "review"])));
    }

    #[test]
    fn the_npm_launcher_s_script_is_skipped() {
        let launcher = args(&[
            "node",
            "/usr/lib/node_modules/@openai/codex/bin/codex.js",
            "exec",
        ]);
        assert!(!is_interactive(&launcher));
        assert!(is_interactive(&args(&[
            "node",
            "/usr/lib/node_modules/@openai/codex/bin/codex.js"
        ])));
    }

    #[test]
    fn the_shared_server_is_recognized() {
        assert!(is_shared_server(&args(&[
            "codex",
            "app-server",
            "--listen",
            "unix://",
            "--managed-daemon"
        ])));
        // An editor's own app-server isn't the shared server.
        assert!(!is_shared_server(&args(&["codex", "app-server"])));
        assert!(!is_shared_server(&args(&["codex", "--no-daemon"])));
    }

    #[test]
    fn a_window_works_in_the_folder_it_names() {
        let cwd = Path::new("/home/demo");
        assert_eq!(
            window_folder(&args(&["codex"]), Some(cwd)),
            Some(PathBuf::from("/home/demo"))
        );
        assert_eq!(
            window_folder(&args(&["codex", "-C", "code"]), Some(cwd)),
            Some(PathBuf::from("/home/demo/code"))
        );
        assert_eq!(
            window_folder(&args(&["codex", "--cd=/srv/app"]), Some(cwd)),
            Some(PathBuf::from("/srv/app"))
        );
        assert_eq!(window_folder(&args(&["codex"]), None), None);
    }

    #[test]
    fn a_session_id_tells_when_it_was_created() {
        assert_eq!(created_ms(&new_id(CREATED)), Some(CREATED));
        assert_eq!(created_ms(ID), None, "not a version 7 UUID");
        assert_eq!(created_ms("bad"), None);
    }

    #[test]
    fn a_session_file_tells_which_program_created_it() {
        let made_by = |originator: &str| {
            format!(r#"{{"type":"session_meta","payload":{{"originator":"{originator}"}}}}"#)
        };
        assert!(created_by_a_window(&made_by("codex-tui")));
        assert!(!created_by_a_window(&made_by("some-other-client")));
        assert!(created_by_a_window(
            r#"{"type":"session_meta","payload":{}}"#
        ));
        assert!(created_by_a_window("not json"));
    }

    #[test]
    fn a_window_started_with_the_session_s_id_shows_it() {
        let windows = [
            window(0, &["codex"], HERE),
            window(0, &["codex", "resume", ID], THERE),
        ];
        assert_eq!(
            window_of(&session(ID, "resume"), &windows),
            Shown::In {
                window: 1,
                exact: true
            }
        );
    }

    #[test]
    fn a_new_session_belongs_to_the_window_that_just_started() {
        // Two windows in the folder: one from before, one that started 1
        // second before Codex created the session.
        let windows = [
            window(50_000, &["codex"], HERE),
            window(99_000, &["codex"], HERE),
            window(99_500, &["codex"], THERE),
        ];
        let id = new_id(CREATED);
        assert_eq!(
            window_of(&session(&id, "startup"), &windows),
            Shown::In {
                window: 1,
                exact: false
            }
        );
    }

    #[test]
    fn two_windows_started_together_are_not_guessed_between() {
        let windows = [
            window(98_000, &["codex"], HERE),
            window(99_000, &["codex"], HERE),
        ];
        let id = new_id(CREATED);
        assert!(matches!(
            window_of(&session(&id, "startup"), &windows),
            Shown::Unsure(_)
        ));
    }

    #[test]
    fn a_later_session_belongs_to_the_only_window_in_its_folder() {
        // After /new, the session is newer than every window.
        let windows = [
            window(10_000, &["codex"], HERE),
            window(20_000, &["codex"], THERE),
        ];
        let id = new_id(CREATED);
        assert_eq!(
            window_of(&session(&id, "startup"), &windows),
            Shown::In {
                window: 0,
                exact: false
            }
        );
        let crowded = [
            window(10_000, &["codex"], HERE),
            window(20_000, &["codex"], HERE),
        ];
        assert!(matches!(
            window_of(&session(&id, "clear"), &crowded),
            Shown::Unsure(_)
        ));
    }

    #[test]
    fn a_window_that_started_after_a_new_session_doesn_t_show_it() {
        let windows = [window(200_000, &["codex"], HERE)];
        let id = new_id(CREATED);
        assert_eq!(
            window_of(&session(&id, "startup"), &windows),
            Shown::Nowhere
        );
    }

    #[test]
    fn a_resumed_session_belongs_to_the_only_window_in_its_folder() {
        // `codex resume --last` doesn't name the session, and the session is
        // older than the window.
        let windows = [window(200_000, &["codex", "resume", "--last"], HERE)];
        let id = new_id(CREATED);
        assert_eq!(
            window_of(&session(&id, "resume"), &windows),
            Shown::In {
                window: 0,
                exact: false
            }
        );
    }

    #[test]
    fn a_window_whose_folder_is_unknown_could_be_anywhere() {
        let mut unknown = window(10_000, &["codex"], HERE);
        unknown.folder = None;
        let windows = [window(10_000, &["codex"], HERE), unknown];
        let id = new_id(CREATED);
        assert!(matches!(
            window_of(&session(&id, "startup"), &windows),
            Shown::Unsure(_)
        ));
    }

    #[test]
    fn a_session_that_another_program_started_has_no_window() {
        let windows = [window(99_000, &["codex"], HERE)];
        let id = new_id(CREATED);
        let remote = ServerSession {
            from_window: false,
            ..session(&id, "startup")
        };
        assert_eq!(window_of(&remote, &windows), Shown::Nowhere);
    }

    #[test]
    fn folders_are_compared_as_the_os_does() {
        assert!(same_folder(r"C:\Users\demo\code\", r"C:\Users\demo\code"));
        assert!(!same_folder("/home/demo/a", "/home/demo/b"));
        assert_eq!(
            same_folder(r"C:\Users\Demo", r"c:\users\demo"),
            cfg!(windows)
        );
    }
}