rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! Running Claude Code or Codex without their own interface: how to start them, and what
//! the lines they print mean. Both report their progress as one JSON object per line.

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",
        }
    }

    /// The arguments for one turn. The message itself goes to standard input, so nothing in
    /// it has to be quoted or can be taken for an option.
    ///
    /// File edits in the folder are accepted without asking. Claude Code refuses anything
    /// else that would need approval, except what is in `allowed`; Codex runs commands in
    /// its sandbox, which only lets them write inside the folder.
    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 {
                    // `resume` has no --sandbox option.
                    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 {
    /// A file was written or changed.
    Edit,
    /// A shell command.
    Command,
    Other,
}

/// Something the agent was not allowed to do.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Denied {
    pub label: String,
    /// The permission that would allow exactly this, if it can be allowed from here.
    pub rule: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Event {
    /// The id to resume the conversation with.
    Session(String),
    /// The agent started doing something.
    Step {
        id: String,
        label: String,
        kind: StepKind,
    },
    StepDone {
        id: String,
        ok: bool,
    },
    /// Something the agent said, along the way or at the end.
    Text(String),
    Denied(Denied),
    /// Something worth showing that doesn't end the turn.
    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()
}

/// The first line of `text`, marked if there was more.
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 }
}

/// A path as shown: from the folder the agent works in, if it is inside.
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,
    }
}

/// A line describing a Claude Code tool call.
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),
    }
}

/// What was refused, and the permission that would allow just that.
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 {
        // The whole command, since this is what the person may be asked to allow.
        label = format!("$ {}", str_at(input, "command"));
    }
    let rule = match name {
        "Bash" | "PowerShell" => {
            let command = str_at(input, "command");
            // In a rule, `*` matches anything, so such a command can't be allowed exactly.
            (!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()),
        // Allowing a file tool would allow it on any file, so that isn't offered.
        _ => 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> {
    // What a subagent says and does stays its own business.
    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(),
    }
}

/// The command Codex ran, without the shell it wrapped it in.
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(),
    }
}

/// What one line of the agent's output means. `root` is the folder it works in.
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 -");
    }
}