use serde_json::Value;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Agent {
Claude,
Codex,
}
impl Agent {
pub fn parse(name: &str) -> Option<Agent> {
match name.trim().to_ascii_lowercase().as_str() {
"" | "claude" => Some(Agent::Claude),
"codex" => Some(Agent::Codex),
_ => None,
}
}
pub fn name(self) -> &'static str {
match self {
Agent::Claude => "Claude",
Agent::Codex => "Codex",
}
}
pub fn program(self) -> &'static str {
match self {
Agent::Claude => "claude",
Agent::Codex => "codex",
}
}
pub fn args(self, session: Option<&str>, allowed: &[String]) -> Vec<String> {
let mut args: Vec<&str> = Vec::new();
match self {
Agent::Claude => {
args.extend(["-p", "--output-format", "stream-json", "--verbose", "--permission-mode", "acceptEdits"]);
if let Some(id) = session {
args.extend(["--resume", id]);
}
if !allowed.is_empty() {
args.push("--allowedTools");
args.extend(allowed.iter().map(String::as_str));
}
}
Agent::Codex => {
args.push("exec");
match session {
Some(_) => args.extend(["resume", "-c", "sandbox_mode=\"workspace-write\""]),
None => args.extend(["--sandbox", "workspace-write"]),
}
args.extend(["--json", "--skip-git-repo-check"]);
args.extend(session);
args.push("-");
}
}
args.into_iter().map(str::to_string).collect()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StepKind {
Edit,
Command,
Other,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Denied {
pub label: String,
pub rule: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Event {
Session(String),
Step {
id: String,
label: String,
kind: StepKind,
},
StepDone {
id: String,
ok: bool,
},
Text(String),
Denied(Denied),
Note(String),
Finished {
error: Option<String>,
},
}
fn str_at<'a>(v: &'a Value, key: &str) -> &'a str {
v.get(key).and_then(Value::as_str).unwrap_or_default()
}
fn first_line(text: &str) -> String {
let mut lines = text.trim().lines();
let first = lines.next().unwrap_or_default().to_string();
if lines.next().is_some() { first + " \u{2026}" } else { first }
}
fn short_path(path: &str, root: &str) -> String {
let norm = |s: &str| s.replace('\\', "/");
let (path, root) = (norm(path), norm(root));
let root = root.trim_end_matches('/');
match path.get(..root.len()) {
Some(head) if !root.is_empty() && head.eq_ignore_ascii_case(root) && path[root.len()..].starts_with('/') => {
path[root.len() + 1..].to_string()
}
_ => path,
}
}
fn claude_step(name: &str, input: &Value, root: &str) -> (String, StepKind) {
let path = |key: &str| short_path(str_at(input, key), root);
match name {
"Read" => (format!("Read {}", path("file_path")), StepKind::Other),
"Edit" | "MultiEdit" => (format!("Edited {}", path("file_path")), StepKind::Edit),
"Write" => (format!("Wrote {}", path("file_path")), StepKind::Edit),
"NotebookEdit" => (format!("Edited {}", path("notebook_path")), StepKind::Edit),
"Bash" | "PowerShell" => (format!("$ {}", first_line(str_at(input, "command"))), StepKind::Command),
"Grep" | "Glob" => (format!("Searched for {}", first_line(str_at(input, "pattern"))), StepKind::Other),
"WebFetch" => (format!("Fetched {}", str_at(input, "url")), StepKind::Other),
"WebSearch" => (format!("Searched the web: {}", str_at(input, "query")), StepKind::Other),
"Task" | "Agent" => (format!("Delegated: {}", str_at(input, "description")), StepKind::Other),
other => (other.to_string(), StepKind::Other),
}
}
fn claude_denial(denial: &Value, root: &str) -> Denied {
let name = str_at(denial, "tool_name");
let input = denial.get("tool_input").unwrap_or(&Value::Null);
let (mut label, kind) = claude_step(name, input, root);
if kind == StepKind::Command {
label = format!("$ {}", str_at(input, "command"));
}
let rule = match name {
"Bash" | "PowerShell" => {
let command = str_at(input, "command");
(!command.is_empty() && !command.contains(['*', '\n', '\r'])).then(|| format!("{name}({command})"))
}
"WebFetch" | "WebSearch" => Some(name.to_string()),
n if n.starts_with("mcp__") => Some(n.to_string()),
_ => None,
};
let label = if name.starts_with("mcp__") { name.to_string() } else { label };
Denied { label, rule }
}
fn claude_events(v: &Value, root: &str) -> Vec<Event> {
let from_subagent = v.get("parent_tool_use_id").is_some_and(|p| !p.is_null());
let blocks = || v.pointer("/message/content").and_then(Value::as_array).into_iter().flatten();
match str_at(v, "type") {
"system" if str_at(v, "subtype") == "init" => vec![Event::Session(str_at(v, "session_id").to_string())],
"assistant" if !from_subagent => blocks()
.filter_map(|b| match str_at(b, "type") {
"text" => {
let said = str_at(b, "text").trim();
(!said.is_empty()).then(|| Event::Text(said.to_string()))
}
"tool_use" => {
let (label, kind) = claude_step(str_at(b, "name"), b.get("input").unwrap_or(&Value::Null), root);
Some(Event::Step { id: str_at(b, "id").to_string(), label, kind })
}
_ => None,
})
.collect(),
"user" if !from_subagent => blocks()
.filter(|b| str_at(b, "type") == "tool_result")
.map(|b| Event::StepDone {
id: str_at(b, "tool_use_id").to_string(),
ok: b.get("is_error").and_then(Value::as_bool) != Some(true),
})
.collect(),
"result" => {
let mut events: Vec<Event> = v
.get("permission_denials")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|d| Event::Denied(claude_denial(d, root)))
.collect();
if let Some(id) = v.get("session_id").and_then(Value::as_str) {
events.insert(0, Event::Session(id.to_string()));
}
let failed = v.get("is_error").and_then(Value::as_bool) == Some(true);
let error = failed.then(|| {
let said = str_at(v, "result");
if said.is_empty() { str_at(v, "subtype").replace('_', " ") } else { said.to_string() }
});
events.push(Event::Finished { error });
events
}
_ => Vec::new(),
}
}
fn codex_command(command: &str) -> String {
let inner = [" -Command ", " -lc ", " /c "].iter().find_map(|flag| command.split_once(flag).map(|(_, c)| c));
first_line(inner.unwrap_or(command).trim().trim_matches(['"', '\'']))
}
fn codex_events(v: &Value, root: &str) -> Vec<Event> {
let item = v.get("item").unwrap_or(&Value::Null);
let id = str_at(item, "id").to_string();
let done = str_at(v, "type") == "item.completed";
match str_at(v, "type") {
"thread.started" => vec![Event::Session(str_at(v, "thread_id").to_string())],
"turn.completed" => vec![Event::Finished { error: None }],
"turn.failed" => {
let message = v.pointer("/error/message").and_then(Value::as_str).unwrap_or("the turn failed");
vec![Event::Finished { error: Some(message.to_string()) }]
}
"error" => vec![Event::Note(str_at(v, "message").to_string())],
"item.started" | "item.completed" => match str_at(item, "type") {
"agent_message" if done => vec![Event::Text(str_at(item, "text").trim().to_string())],
"command_execution" => {
let label = format!("$ {}", codex_command(str_at(item, "command")));
let mut events = vec![Event::Step { id: id.clone(), label, kind: StepKind::Command }];
if done {
let ok = item.get("exit_code").and_then(Value::as_i64) == Some(0);
events.push(Event::StepDone { id, ok });
}
events
}
"file_change" if done => {
let ok = str_at(item, "status") != "failed";
item.get("changes")
.and_then(Value::as_array)
.into_iter()
.flatten()
.enumerate()
.flat_map(|(i, change)| {
let verb = match str_at(change, "kind") {
"add" => "Wrote",
"delete" => "Deleted",
_ => "Edited",
};
let label = format!("{verb} {}", short_path(str_at(change, "path"), root));
let id = format!("{id}-{i}");
[Event::Step { id: id.clone(), label, kind: StepKind::Edit }, Event::StepDone { id, ok }]
})
.collect()
}
"web_search" if done => {
let label = format!("Searched the web: {}", str_at(item, "query"));
vec![Event::Step { id: id.clone(), label, kind: StepKind::Other }, Event::StepDone { id, ok: true }]
}
"mcp_tool_call" if done => {
let label = format!("{}.{}", str_at(item, "server"), str_at(item, "tool"));
let ok = str_at(item, "status") != "failed";
vec![Event::Step { id: id.clone(), label, kind: StepKind::Other }, Event::StepDone { id, ok }]
}
"error" if done => vec![Event::Note(str_at(item, "message").to_string())],
_ => Vec::new(),
},
_ => Vec::new(),
}
}
pub fn parse_line(agent: Agent, line: &str, root: &str) -> Vec<Event> {
let Ok(v) = serde_json::from_str::<Value>(line.trim()) else { return Vec::new() };
match agent {
Agent::Claude => claude_events(&v, root),
Agent::Codex => codex_events(&v, root),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn claude(line: &str) -> Vec<Event> {
parse_line(Agent::Claude, line, r"C:\proj")
}
fn codex(line: &str) -> Vec<Event> {
parse_line(Agent::Codex, line, r"C:\proj")
}
#[test]
fn claude_lines_become_steps_and_text() {
assert_eq!(claude(r#"{"type":"system","subtype":"init","session_id":"s1"}"#), [Event::Session("s1".into())]);
let line = r#"{"type":"assistant","parent_tool_use_id":null,"message":{"content":[
{"type":"thinking","thinking":"..."},
{"type":"tool_use","id":"t1","name":"Write","input":{"file_path":"C:\\proj\\src\\a.txt"}},
{"type":"text","text":" Done. "}]}}"#;
assert_eq!(
claude(&line.replace('\n', " ")),
[
Event::Step { id: "t1".into(), label: "Wrote src/a.txt".into(), kind: StepKind::Edit },
Event::Text("Done.".into())
]
);
assert_eq!(
claude(
r#"{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"t1","is_error":true}]}}"#
),
[Event::StepDone { id: "t1".into(), ok: false }]
);
let sub =
r#"{"type":"assistant","parent_tool_use_id":"x","message":{"content":[{"type":"text","text":"sub"}]}}"#;
assert_eq!(claude(sub), []);
assert_eq!(claude("not json"), []);
}
#[test]
fn a_refused_command_can_be_allowed_exactly() {
let line = r#"{"type":"result","is_error":false,"result":"ok","session_id":"s1","permission_denials":[
{"tool_name":"PowerShell","tool_input":{"command":"node --version"}},
{"tool_name":"Bash","tool_input":{"command":"rm *.log"}},
{"tool_name":"Write","tool_input":{"file_path":"C:\\other\\x"}}]}"#;
let events = claude(&line.replace('\n', " "));
let rules: Vec<_> = events
.iter()
.filter_map(|e| match e {
Event::Denied(d) => Some((d.label.as_str(), d.rule.as_deref())),
_ => None,
})
.collect();
assert_eq!(
rules,
[
("$ node --version", Some("PowerShell(node --version)")),
("$ rm *.log", None),
("Wrote C:/other/x", None)
]
);
assert_eq!(events.last(), Some(&Event::Finished { error: None }));
assert_eq!(
claude(r#"{"type":"result","subtype":"error_max_turns","is_error":true}"#),
[Event::Finished { error: Some("error max turns".into()) }]
);
}
#[test]
fn codex_lines_become_steps_and_text() {
assert_eq!(codex(r#"{"type":"thread.started","thread_id":"t9"}"#), [Event::Session("t9".into())]);
let started = r#"{"type":"item.started","item":{"id":"i1","type":"command_execution","command":"\"C:\\Windows\\powershell.exe\" -Command \"node --version\"","exit_code":null}}"#;
assert_eq!(
codex(started),
[Event::Step { id: "i1".into(), label: "$ node --version".into(), kind: StepKind::Command }]
);
let change = r#"{"type":"item.completed","item":{"id":"i2","type":"file_change","status":"completed","changes":[{"path":"C:\\proj\\b.txt","kind":"add"}]}}"#;
assert_eq!(
codex(change)[0],
Event::Step { id: "i2-0".into(), label: "Wrote b.txt".into(), kind: StepKind::Edit }
);
assert_eq!(
codex(r#"{"type":"item.completed","item":{"id":"i3","type":"agent_message","text":"hi"}}"#),
[Event::Text("hi".into())]
);
assert_eq!(codex(r#"{"type":"turn.completed"}"#), [Event::Finished { error: None }]);
assert_eq!(
codex(r#"{"type":"turn.failed","error":{"message":"no quota"}}"#),
[Event::Finished { error: Some("no quota".into()) }]
);
}
#[test]
fn edits_are_accepted_and_nothing_else_is_opened_up() {
let first = Agent::Claude.args(None, &[]).join(" ");
assert!(first.contains("--permission-mode acceptEdits"));
assert!(!first.contains("bypass") && !first.contains("dangerously"));
let again = Agent::Claude.args(Some("s1"), &["Bash(ls)".into()]).join(" ");
assert!(again.ends_with("--resume s1 --allowedTools Bash(ls)"));
assert_eq!(
Agent::Codex.args(None, &[]).join(" "),
"exec --sandbox workspace-write --json --skip-git-repo-check -"
);
let resume = Agent::Codex.args(Some("t9"), &[]).join(" ");
assert_eq!(resume, "exec resume -c sandbox_mode=\"workspace-write\" --json --skip-git-repo-check t9 -");
}
}