pub mod claude;
pub mod codex;
use std::io::{BufRead, BufReader, Read};
use std::path::PathBuf;
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use crate::engine::note::{AgentNote, Note, ShellNote};
use crate::engine::rules::{Liveness, SingleWindowClose};
use crate::os;
use crate::procs::system::SystemTable;
use crate::procs::{self, ProcInfo, ProcessTable};
use crate::shells::shell_name;
use crate::store::{self, Store};
use crate::terminals::{self, Env};
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum Agent {
Claude,
Codex,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct HookInput {
session_id: String,
cwd: String,
#[serde(default)]
transcript_path: Option<String>,
#[serde(default)]
source: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionStart {
pub session_id: String,
pub cwd: String,
pub transcript_path: Option<String>,
pub source: Option<String>,
}
impl Agent {
pub fn id(self) -> &'static str {
match self {
Agent::Claude => "claude",
Agent::Codex => "codex",
}
}
pub fn from_id(id: &str) -> Option<Agent> {
[Agent::Claude, Agent::Codex]
.into_iter()
.find(|agent| agent.id() == id)
}
pub fn name(self) -> &'static str {
match self {
Agent::Claude => "Claude Code",
Agent::Codex => "Codex",
}
}
pub fn conversation_file(self, note: &AgentNote) -> Option<PathBuf> {
let recorded = note
.transcript
.as_ref()
.map(PathBuf::from)
.filter(|path| path.is_file());
match self {
Agent::Claude => recorded
.or_else(|| claude::find_transcript(&claude::config_dir()?, ¬e.conversation)),
Agent::Codex => recorded,
}
}
pub fn resume_command(self, note: &AgentNote) -> Vec<String> {
let exists = self.conversation_file(note).is_some();
match self {
Agent::Claude => claude::resume_command(¬e.conversation, exists),
Agent::Codex => codex::resume_command(¬e.conversation, exists),
}
}
fn parse(self, input: &str) -> Result<SessionStart> {
let input: HookInput = serde_json::from_str(input.trim_start_matches('\u{feff}'))?;
if !is_uuid(&input.session_id) {
bail!("not a {} session id: {:?}", self.id(), input.session_id);
}
Ok(SessionStart {
session_id: input.session_id,
cwd: input.cwd,
transcript_path: input.transcript_path,
source: input.source,
})
}
fn is_process(self, process: &ProcInfo) -> bool {
let command_line = process.command_line.as_deref().unwrap_or_default();
match self {
Agent::Claude => claude::is_claude_process(&process.name, command_line),
Agent::Codex => codex::is_codex_process(&process.name, command_line),
}
}
fn is_interactive(self, process: &ProcInfo) -> bool {
match self {
Agent::Claude => {
claude::is_interactive(process.command_line.as_deref().unwrap_or_default())
}
Agent::Codex => codex::is_interactive(&process.arguments),
}
}
fn registered_pid(self, session_id: &str) -> Option<u32> {
match self {
Agent::Claude => claude::registered_pid(&claude::config_dir()?, session_id),
Agent::Codex => None,
}
}
}
pub fn is_uuid(text: &str) -> bool {
let groups: Vec<&str> = text.split('-').collect();
groups.len() == 5
&& groups.iter().zip([8, 4, 4, 4, 12]).all(|(group, length)| {
group.len() == length && group.chars().all(|c| c.is_ascii_hexdigit())
})
}
pub fn run_hook(agent: Agent) -> Result<()> {
let mut bytes = Vec::new();
if std::io::stdin().read_to_end(&mut bytes).is_err() {
return Ok(());
}
let input = String::from_utf8_lossy(&bytes);
if let Ok(store) = Store::open()
&& let Err(error) = record(&store, agent, &input)
{
store.log(&format!("hook {}: {error:#}", agent.id()));
}
Ok(())
}
fn record(store: &Store, agent: Agent, input: &str) -> Result<()> {
let start = agent.parse(input)?;
let mut table = SystemTable::snapshot();
let mut lineage = table.lineage(std::process::id());
let index = match lineage.iter().position(|process| agent.is_process(process)) {
Some(index) => index,
None => {
let pid = agent
.registered_pid(&start.session_id)
.context("the agent's process isn't above the hook")?;
lineage = table.lineage(pid);
if !lineage
.first()
.is_some_and(|process| agent.is_process(process))
{
bail!("process {pid} isn't the agent's");
}
0
}
};
let from_agent = &lineage[index..];
let session = os::session_id()?;
let new = if agent == Agent::Codex && codex::is_shared_server(&from_agent[0].arguments) {
server_session_note(store, start, &mut table, &session)
} else if agent.is_interactive(&from_agent[0]) {
let env: Env = std::env::vars().collect();
agent_note(agent, start, from_agent, &env, &session)?
} else {
None
};
let Some(new) = new else {
return Ok(());
};
let (path, new) = save_agent_note(store, new)?;
for stored in store.notes() {
if let Note::Agent(other) = &stored.note
&& other.agent == new.agent
&& other.conversation == new.conversation
&& stored.path != path
{
store.remove(&stored);
}
}
store::review(store, &table, &session, SingleWindowClose::default());
Ok(())
}
fn save_agent_note(store: &Store, mut note: AgentNote) -> Result<(PathBuf, AgentNote)> {
if let Ok(Note::Agent(earlier)) = store.read(&store.path_of(&Note::Agent(note.clone()))) {
note.cwd = earlier.cwd;
}
let path = store.save(&Note::Agent(note.clone()))?;
Ok((path, note))
}
fn agent_note(
agent: Agent,
start: SessionStart,
from_agent: &[ProcInfo],
env: &Env,
session: &str,
) -> Result<Option<AgentNote>> {
let process = from_agent
.first()
.context("there is no agent process")?
.to_ref()
.context("the agent's start time can't be read")?;
let Some((index, terminal)) = terminals::tab_of(&terminals::all(), env, from_agent) else {
return Ok(None);
};
let shell = from_agent.get(index).filter(|_| index > 0);
Ok(Some(AgentNote {
process,
agent: agent.id().into(),
conversation: start.session_id,
cwd: start.cwd,
shell: shell.and_then(ProcInfo::to_ref),
shell_name: shell.map(|shell| shell_name(&shell.name)),
terminal: Some(terminal),
transcript: start.transcript_path,
session: session.into(),
offered: false,
}))
}
fn server_session_note(
store: &Store,
start: SessionStart,
table: &mut SystemTable,
session: &str,
) -> Option<AgentNote> {
let found = table.find(codex::may_be_codex);
let windows = codex_windows(table, &found);
let from_window = start
.transcript_path
.as_deref()
.and_then(first_line)
.is_none_or(|line| codex::created_by_a_window(&line));
let server_session = codex::ServerSession {
id: &start.session_id,
cwd: &start.cwd,
source: start.source.as_deref(),
from_window,
};
let listed: Vec<codex::Window> = windows
.iter()
.map(|(window, _)| as_window(window))
.collect();
let (index, exact) = match codex::window_of(&server_session, &listed) {
codex::Shown::In { window, exact } => (window, exact),
codex::Shown::Unsure(reason) => {
if !is_placed(store, table, &start.session_id) {
store.log(&format!(
"hook codex: kaeru can't tell which tab shows session {}, because \
{reason}. Starting Codex with --no-daemon makes this exact.",
start.session_id
));
}
return None;
}
codex::Shown::Nowhere => return None,
};
if !exact && is_placed(store, table, &start.session_id) {
return None;
}
let (window, lineage) = &windows[index];
let shells: Vec<ShellNote> = store
.notes()
.into_iter()
.filter_map(|stored| match stored.note {
Note::Shell(shell) => Some(shell),
Note::Agent(_) => None,
})
.collect();
let shell = tab_shell(lineage, &shells)?;
Some(AgentNote {
process: window.to_ref()?,
agent: Agent::Codex.id().into(),
conversation: start.session_id,
cwd: start.cwd,
shell: Some(shell.process),
shell_name: Some(shell.shell.clone()),
terminal: shell.terminal.clone(),
transcript: start.transcript_path,
session: session.into(),
offered: false,
})
}
fn codex_windows(table: &dyn ProcessTable, found: &[ProcInfo]) -> Vec<(ProcInfo, Vec<ProcInfo>)> {
let windows: Vec<(ProcInfo, Vec<ProcInfo>)> = found
.iter()
.filter(|process| {
codex::is_codex_process(
&process.name,
process.command_line.as_deref().unwrap_or_default(),
) && codex::is_interactive(&process.arguments)
&& !codex::is_shared_server(&process.arguments)
})
.map(|process| (process.clone(), procs::lineage(table, process.pid)))
.collect();
windows
.iter()
.filter(|(window, _)| {
!windows.iter().any(|(other, lineage)| {
other.pid != window.pid && lineage.iter().any(|process| process.pid == window.pid)
})
})
.cloned()
.collect()
}
fn as_window(window: &ProcInfo) -> codex::Window {
codex::Window {
started_ms: window.started_ms.unwrap_or(0),
arguments: window.arguments.clone(),
folder: codex::window_folder(&window.arguments, window.cwd.as_deref())
.map(|folder| folder.display().to_string()),
}
}
fn tab_shell<'a>(lineage: &[ProcInfo], shells: &'a [ShellNote]) -> Option<&'a ShellNote> {
lineage
.iter()
.find_map(|process| shells.iter().find(|shell| process.is(&shell.process)))
}
fn is_placed(store: &Store, table: &dyn ProcessTable, conversation: &str) -> bool {
store.notes().iter().any(|stored| match &stored.note {
Note::Agent(note) => {
note.agent == Agent::Codex.id()
&& note.conversation == conversation
&& procs::liveness(table, ¬e.process) == Liveness::Running
}
Note::Shell(_) => false,
})
}
fn first_line(path: &str) -> Option<String> {
let file = std::fs::File::open(path).ok()?;
BufReader::new(file).lines().next()?.ok()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::procs::{fake::FakeTable, lineage};
const ID: &str = "00000000-0000-4000-8000-000000000001";
fn start() -> SessionStart {
SessionStart {
session_id: ID.into(),
cwd: r"C:\Users\demo\code\mobile-app".into(),
transcript_path: None,
source: Some("startup".into()),
}
}
fn codex_table() -> FakeTable {
FakeTable::new(&[
(10, None, "WindowsTerminal.exe", Some(1_000)),
(20, Some(10), "powershell.exe", Some(2_000)),
(30, Some(20), "node.exe", Some(3_000)),
(40, Some(30), "codex.exe", Some(3_000)),
(50, None, "codex.exe", Some(500)),
(60, Some(20), "codex.exe", Some(4_000)),
])
.with_command_line(30, r"node C:\npm\node_modules\@openai\codex\bin\codex.js")
.with_arguments(40, &["codex.exe"])
.with_arguments(
50,
&[
"codex.exe",
"app-server",
"--listen",
"unix://",
"--managed-daemon",
],
)
.with_arguments(60, &["codex.exe", "exec", "fix the tests"])
.with_cwd(40, r"C:\Users\demo\code\mobile-app")
}
#[test]
fn a_codex_window_is_found_once_and_the_server_is_not_one() {
let table = codex_table();
let windows = codex_windows(&table, &table.processes());
let pids: Vec<u32> = windows.iter().map(|(window, _)| window.pid).collect();
assert_eq!(pids, [40]);
let window = as_window(&windows[0].0);
assert_eq!(
window.folder.as_deref(),
Some(r"C:\Users\demo\code\mobile-app")
);
}
#[test]
fn a_window_is_in_the_tab_whose_shell_it_runs_under() {
let table = codex_table();
let windows = codex_windows(&table, &table.processes());
let shell = |pid, started_ms| ShellNote {
process: crate::engine::note::ProcessRef { pid, started_ms },
shell: "powershell".into(),
cwd: r"C:\Users\demo".into(),
terminal: None,
session: "win-1".into(),
offered: false,
};
let shells = [shell(70, 7_000), shell(20, 2_000)];
let found = tab_shell(&windows[0].1, &shells).unwrap();
assert_eq!(found.process.pid, 20);
assert!(tab_shell(&windows[0].1, &shells[..1]).is_none());
}
fn tab_env() -> Env {
Env::from([("WT_SESSION".to_string(), "x".to_string())])
}
#[test]
fn a_later_note_of_an_agent_keeps_the_folder_it_started_in() {
let dir = tempfile::tempdir().unwrap();
let store = Store::at(dir.path().to_path_buf()).unwrap();
let note = |pid, cwd: &str| AgentNote {
process: crate::engine::note::ProcessRef {
pid,
started_ms: 3_000,
},
agent: Agent::Claude.id().into(),
conversation: ID.into(),
cwd: cwd.into(),
shell: None,
shell_name: None,
terminal: None,
transcript: None,
session: "win-1".into(),
offered: false,
};
let started_in = r"C:\Users\demo\code";
save_agent_note(&store, note(30, started_in)).unwrap();
let (path, saved) =
save_agent_note(&store, note(30, r"C:\Users\demo\code\web-ui")).unwrap();
assert_eq!(saved.cwd, started_in);
let Ok(Note::Agent(on_disk)) = store.read(&path) else {
panic!("the agent's note is on disk");
};
assert_eq!(on_disk.cwd, started_in);
let elsewhere = r"C:\Users\demo\code\api-server";
let (_, resumed) = save_agent_note(&store, note(31, elsewhere)).unwrap();
assert_eq!(resumed.cwd, elsewhere);
}
#[test]
fn an_agent_in_a_tab_is_linked_to_its_shell() {
let table = FakeTable::new(&[
(50, Some(40), "kaeru.exe", Some(5_000)),
(40, Some(30), "bash.exe", Some(4_000)),
(30, Some(20), "claude.exe", Some(3_000)),
(20, Some(10), "powershell.exe", Some(2_000)),
(10, None, "WindowsTerminal.exe", Some(1_000)),
]);
let chain = lineage(&table, 50);
let index = chain
.iter()
.position(|p| Agent::Claude.is_process(p))
.unwrap();
let note = agent_note(Agent::Claude, start(), &chain[index..], &tab_env(), "win-1");
let note = note.unwrap().unwrap();
assert_eq!(note.process.pid, 30);
assert_eq!(note.shell.map(|shell| shell.pid), Some(20));
assert_eq!(note.shell_name.as_deref(), Some("powershell"));
assert_eq!(note.terminal.unwrap().process.pid, 10);
assert_eq!(note.conversation, ID);
}
#[test]
fn an_agent_that_the_terminal_started_has_no_shell() {
let table = FakeTable::new(&[
(30, Some(10), "claude.exe", Some(3_000)),
(10, None, "WindowsTerminal.exe", Some(1_000)),
]);
let note = agent_note(
Agent::Claude,
start(),
&lineage(&table, 30),
&tab_env(),
"win-1",
);
let note = note.unwrap().unwrap();
assert_eq!(note.shell, None);
assert!(note.terminal.is_some());
}
#[test]
fn an_agent_outside_known_terminals_gets_no_note() {
let table = FakeTable::new(&[
(30, Some(20), "claude.exe", Some(3_000)),
(20, None, "powershell.exe", Some(2_000)),
]);
let note = agent_note(
Agent::Claude,
start(),
&lineage(&table, 30),
&tab_env(),
"win-1",
);
assert!(note.unwrap().is_none());
}
#[test]
fn the_npm_build_of_claude_code_is_recognized() {
let table = FakeTable::new(&[(30, None, "node.exe", Some(3_000))]).with_command_line(
30,
r"node C:\npm\node_modules\@anthropic-ai\claude-code\cli.js",
);
assert!(Agent::Claude.is_process(&lineage(&table, 30)[0]));
}
#[test]
fn hook_input_may_start_with_a_byte_order_mark() {
let json = format!("\u{feff}{{\"session_id\":\"{ID}\",\"cwd\":\"C:\\\\demo\"}}");
assert_eq!(Agent::Claude.parse(&json).unwrap().session_id, ID);
}
#[test]
fn parses_session_start_input() {
let json = format!(
r#"{{"session_id":"{ID}","transcript_path":"/home/demo/.claude/projects/x/{ID}.jsonl",
"cwd":"/home/demo/code/mobile-app","hook_event_name":"SessionStart","source":"startup",
"model":"some-model","permission_mode":"default"}}"#
);
for agent in [Agent::Claude, Agent::Codex] {
let start = agent.parse(&json).unwrap();
assert_eq!(start.session_id, ID);
assert_eq!(start.cwd, "/home/demo/code/mobile-app");
assert_eq!(start.source.as_deref(), Some("startup"));
assert!(start.transcript_path.unwrap().ends_with(".jsonl"));
}
}
#[test]
fn rejects_bad_input() {
assert!(Agent::Claude.parse("not json").is_err());
assert!(
Agent::Codex
.parse(r#"{"session_id":"x; rm -rf /","cwd":"/"}"#)
.is_err()
);
}
#[test]
fn session_ids_are_uuids() {
assert!(is_uuid(ID));
assert!(!is_uuid("00000000-0000-4000-8000-00000000000"));
assert!(!is_uuid("0000000g-0000-4000-8000-000000000001"));
assert!(!is_uuid(""));
}
#[test]
fn codex_on_windows_is_found_below_its_launcher() {
let table = FakeTable::new(&[
(60, Some(50), "kaeru.exe", Some(6_000)),
(50, Some(40), "cmd.exe", Some(5_000)),
(40, Some(30), "codex.exe", Some(4_000)),
(30, Some(20), "node.exe", Some(3_000)),
(20, Some(10), "pwsh.exe", Some(2_000)),
(10, None, "WindowsTerminal.exe", Some(1_000)),
])
.with_command_line(30, r"node C:\npm\node_modules\@openai\codex\bin\codex.js");
let chain = lineage(&table, 60);
let index = chain
.iter()
.position(|p| Agent::Codex.is_process(p))
.unwrap();
let note = agent_note(Agent::Codex, start(), &chain[index..], &tab_env(), "win-1");
let note = note.unwrap().unwrap();
assert_eq!(note.agent, "codex");
assert_eq!(note.process.pid, 40);
assert_eq!(note.shell_name.as_deref(), Some("pwsh"));
}
}