scv-tools 0.1.34

Workspace-scoped filesystem, process, skill, and agent tools for SCV
Documentation
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
//! Short status lines from a delegated CLI's structured events.
//!
//! Each line names what the agent did (a command, a file it changed, a
//! search, a tool it called), never the output it got back. Commands, URLs,
//! and queries pass through [`redact`] first, so values that look like
//! credentials are replaced before a line leaves the process.

use serde_json::Value;

use crate::adapters::OutputFormat;

/// Longest command, path, query, or text excerpt in one line, in characters.
const DETAIL_CHARS: usize = 120;

/// The status lines one parsed event contributes, possibly none.
pub(crate) fn progress_lines(format: OutputFormat, kind: &str, event: &Value) -> Vec<String> {
    match format {
        OutputFormat::Text => Vec::new(),
        OutputFormat::ClaudeStreamJson => claude(kind, event),
        OutputFormat::CodexJsonl => codex(kind, event),
        OutputFormat::PiJson => pi(kind, event),
    }
}

fn claude(kind: &str, event: &Value) -> Vec<String> {
    if kind != "assistant" {
        return Vec::new();
    }
    let Some(parts) = event.pointer("/message/content").and_then(Value::as_array) else {
        return Vec::new();
    };
    parts
        .iter()
        .filter_map(|part| match part.get("type").and_then(Value::as_str) {
            Some("tool_use") => {
                let name = part.get("name").and_then(Value::as_str)?;
                Some(claude_tool(name, part.get("input").unwrap_or(&Value::Null)))
            }
            Some("text") => {
                let text = part.get("text").and_then(Value::as_str)?;
                let first = text.lines().find(|line| !line.trim().is_empty())?;
                Some(detail(first))
            }
            _ => None,
        })
        .filter(|line| !line.is_empty())
        .collect()
}

fn claude_tool(name: &str, input: &Value) -> String {
    let field = |key: &str| input.get(key).and_then(Value::as_str);
    match name {
        "Bash" => field("command").map_or_else(|| name.to_owned(), shell),
        "Read" | "Write" | "Edit" | "MultiEdit" => field("file_path").map_or_else(
            || name.to_owned(),
            |path| format!("{name} {}", short_path(path)),
        ),
        "NotebookEdit" => field("notebook_path").map_or_else(
            || name.to_owned(),
            |path| format!("{name} {}", short_path(path)),
        ),
        "Glob" | "Grep" => field("pattern").map_or_else(
            || name.to_owned(),
            |pattern| format!("{name} {}", detail(pattern)),
        ),
        "WebSearch" => field("query").map_or_else(
            || name.to_owned(),
            |query| format!("search: {}", detail(query)),
        ),
        "WebFetch" => field("url").map_or_else(
            || name.to_owned(),
            |url| format!("fetch {}", url_without_query(url)),
        ),
        "Task" | "Agent" => field("description").map_or_else(
            || name.to_owned(),
            |text| format!("{name}: {}", detail(text)),
        ),
        // Plan bookkeeping, not work.
        "TodoWrite" => String::new(),
        _ => name.to_owned(),
    }
}

fn codex(kind: &str, event: &Value) -> Vec<String> {
    let Some(item) = event.get("item") else {
        return Vec::new();
    };
    let field = |key: &str| item.get(key).and_then(Value::as_str);
    let line = match (kind, field("type").unwrap_or("")) {
        ("item.started", "command_execution") => field("command").map(shell),
        ("item.completed", "command_execution") => item
            .get("exit_code")
            .and_then(Value::as_i64)
            .filter(|code| *code != 0)
            .map(|code| match field("command") {
                Some(command) => format!("exit {code}: {}", strip_shell(command)),
                None => format!("exit {code}"),
            }),
        ("item.completed", "file_change") => {
            let changes = item.get("changes").and_then(Value::as_array);
            let lines: Vec<String> = changes
                .into_iter()
                .flatten()
                .filter_map(|change| {
                    let path = change.get("path").and_then(Value::as_str)?;
                    let action = change.get("kind").and_then(Value::as_str).unwrap_or("edit");
                    Some(format!("{action} {}", short_path(path)))
                })
                .collect();
            return lines;
        }
        ("item.completed", "web_search") => field("query")
            .filter(|query| !query.trim().is_empty())
            .map(|query| format!("search: {}", detail(query))),
        ("item.started", "mcp_tool_call") => match (field("server"), field("tool")) {
            (Some(server), Some(tool)) => Some(format!("{server}.{tool}")),
            (_, Some(tool)) => Some(tool.to_owned()),
            _ => None,
        },
        _ => None,
    };
    line.into_iter().collect()
}

fn pi(kind: &str, event: &Value) -> Vec<String> {
    let name = event
        .get("toolName")
        .and_then(Value::as_str)
        .unwrap_or("tool");
    match kind {
        "tool_execution_start" => {
            let args = event.get("args").unwrap_or(&Value::Null);
            let field = |key: &str| args.get(key).and_then(Value::as_str);
            let line = match name {
                "bash" => field("command").map(shell),
                "read" | "write" | "edit" => field("path")
                    .or_else(|| field("file_path"))
                    .map(|path| format!("{name} {}", short_path(path))),
                "grep" | "find" => {
                    field("pattern").map(|pattern| format!("{name} {}", detail(pattern)))
                }
                _ => None,
            };
            vec![line.unwrap_or_else(|| name.to_owned())]
        }
        "tool_execution_end" if event.get("isError").and_then(Value::as_bool) == Some(true) => {
            vec![format!("{name} failed")]
        }
        _ => Vec::new(),
    }
}

/// `$ <command>` without the login-shell wrapper the CLI adds.
fn shell(command: &str) -> String {
    format!("$ {}", strip_shell(command))
}

/// The inner command of `<shell> -lc '<command>'`, redacted and bounded.
fn strip_shell(command: &str) -> String {
    let trimmed = command.trim();
    let inner = trimmed
        .split_once(' ')
        .filter(|(program, _)| {
            let base = program.rsplit('/').next().unwrap_or(program);
            matches!(base, "bash" | "zsh" | "sh" | "dash")
        })
        .and_then(|(_, rest)| {
            let rest = rest.trim_start();
            rest.strip_prefix("-lc ")
                .or_else(|| rest.strip_prefix("-c "))
                .map(str::trim)
        })
        .map(|rest| {
            for quote in ['\'', '"'] {
                if let Some(unquoted) = rest
                    .strip_prefix(quote)
                    .and_then(|value| value.strip_suffix(quote))
                {
                    return unquoted;
                }
            }
            rest
        })
        .unwrap_or(trimmed);
    detail(inner)
}

/// The last two components of a path, enough to recognise the file.
fn short_path(path: &str) -> String {
    let parts: Vec<&str> = path.split('/').filter(|part| !part.is_empty()).collect();
    let tail = if parts.len() > 2 {
        format!("…/{}", parts[parts.len() - 2..].join("/"))
    } else {
        path.to_owned()
    };
    detail(&tail)
}

/// A URL's scheme, host, and path; the query and fragment can carry tokens.
fn url_without_query(url: &str) -> String {
    let end = url.find(['?', '#']).unwrap_or(url.len());
    detail(&url[..end])
}

/// Redacted, single-line, and at most `DETAIL_CHARS` characters.
fn detail(text: &str) -> String {
    let line = redact(&text.split_whitespace().collect::<Vec<_>>().join(" "));
    if line.chars().count() <= DETAIL_CHARS {
        return line;
    }
    let mut cut: String = line.chars().take(DETAIL_CHARS - 1).collect();
    cut.push('…');
    cut
}

/// Words that name a credential in `name=value` or `name: value` form.
const SECRET_NAMES: [&str; 8] = [
    "key",
    "token",
    "secret",
    "password",
    "passwd",
    "authorization",
    "credential",
    "cookie",
];

/// Prefixes of well-known credential formats.
const SECRET_PREFIXES: [&str; 9] = [
    "sk-",
    "sk_",
    "ghp_",
    "gho_",
    "ghs_",
    "github_pat_",
    "xoxb-",
    "xoxp-",
    "AKIA",
];

/// Replace values that look like credentials with `…`. A heuristic for
/// display lines, not a guarantee: it covers `Bearer <token>`,
/// `NAME=value` and `--name value` where the name mentions a key, token,
/// secret, or password, and well-known token prefixes.
pub(crate) fn redact(text: &str) -> String {
    let words: Vec<&str> = text.split(' ').collect();
    let mut output = Vec::with_capacity(words.len());
    let mut hide_next = false;
    for word in words {
        let lower = word.to_ascii_lowercase();
        let bare = lower.trim_matches(|character: char| {
            matches!(character, '"' | '\'' | '-' | ':' | '(' | ')' | ',')
        });
        // An auth scheme is shown; the credential after it is not.
        if bare == "bearer" || bare == "basic" {
            output.push(word.to_owned());
            hide_next = true;
            continue;
        }
        if std::mem::take(&mut hide_next) && !word.is_empty() {
            output.push("…".to_owned());
            continue;
        }
        if let Some((name, value)) = word.split_once(['=', ':'])
            && !value.starts_with("//")
            && SECRET_NAMES
                .iter()
                .any(|secret| name.to_ascii_lowercase().contains(secret))
        {
            if value.trim_matches(['"', '\'']).is_empty() {
                // `Authorization: <value>`: the value is the next word.
                output.push(word.to_owned());
                hide_next = true;
            } else {
                let separator = &word[name.len()..=name.len()];
                output.push(format!("{name}{separator}…"));
            }
            continue;
        }
        if word.starts_with("--") && SECRET_NAMES.iter().any(|secret| bare.contains(secret)) {
            output.push(word.to_owned());
            hide_next = true;
            continue;
        }
        let token = word.trim_matches(|character: char| matches!(character, '"' | '\''));
        if SECRET_PREFIXES
            .iter()
            .any(|prefix| token.starts_with(prefix) && token.len() >= prefix.len() + 8)
        {
            output.push("…".to_owned());
            continue;
        }
        output.push(word.to_owned());
    }
    output.join(" ")
}

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

    #[test]
    fn codex_reports_commands_files_and_searches() {
        let started = json!({"type":"item.started","item":{"type":"command_execution","command":"/usr/bin/zsh -lc 'cargo test -p scv-tools'","aggregated_output":"secret output","exit_code":null}});
        assert_eq!(
            progress_lines(OutputFormat::CodexJsonl, "item.started", &started),
            ["$ cargo test -p scv-tools"]
        );
        let failed = json!({"type":"item.completed","item":{"type":"command_execution","command":"bash -lc \"false\"","aggregated_output":"boom","exit_code":1}});
        assert_eq!(
            progress_lines(OutputFormat::CodexJsonl, "item.completed", &failed),
            ["exit 1: false"]
        );
        let succeeded = json!({"type":"item.completed","item":{"type":"command_execution","command":"ls","exit_code":0}});
        assert!(progress_lines(OutputFormat::CodexJsonl, "item.completed", &succeeded).is_empty());
        let files = json!({"type":"item.completed","item":{"type":"file_change","changes":[{"path":"/home/u/projects/scv/src/main.rs","kind":"update"},{"path":"note.txt","kind":"add"}]}});
        assert_eq!(
            progress_lines(OutputFormat::CodexJsonl, "item.completed", &files),
            ["update …/src/main.rs", "add note.txt"]
        );
        let search = json!({"type":"item.completed","item":{"type":"web_search","query":"latest serde version"}});
        assert_eq!(
            progress_lines(OutputFormat::CodexJsonl, "item.completed", &search),
            ["search: latest serde version"]
        );
        let message =
            json!({"type":"item.completed","item":{"type":"agent_message","text":"final answer"}});
        assert!(progress_lines(OutputFormat::CodexJsonl, "item.completed", &message).is_empty());
    }

    #[test]
    fn claude_reports_tool_use_and_brief_text_but_not_results() {
        let assistant = json!({"type":"assistant","message":{"content":[
            {"type":"text","text":"I'll list the files.\nThen more detail."},
            {"type":"tool_use","name":"Bash","input":{"command":"ls -la","description":"List"}},
            {"type":"tool_use","name":"Edit","input":{"file_path":"/w/crates/core/src/lib.rs","old_string":"a","new_string":"b"}},
            {"type":"tool_use","name":"WebFetch","input":{"url":"https://docs.rs/serde?token=abc","prompt":"x"}},
            {"type":"tool_use","name":"TodoWrite","input":{"todos":[]}},
            {"type":"tool_use","name":"mcp__github__search","input":{}}
        ]}});
        assert_eq!(
            progress_lines(OutputFormat::ClaudeStreamJson, "assistant", &assistant),
            [
                "I'll list the files.",
                "$ ls -la",
                "Edit …/src/lib.rs",
                "fetch https://docs.rs/serde",
                "mcp__github__search",
            ]
        );
        let result = json!({"type":"user","message":{"content":[{"type":"tool_result","content":"private output"}]}});
        assert!(progress_lines(OutputFormat::ClaudeStreamJson, "user", &result).is_empty());
    }

    #[test]
    fn pi_reports_tool_starts_and_failures() {
        let bash = json!({"type":"tool_execution_start","toolName":"bash","args":{"command":"ls","timeout":10}});
        assert_eq!(
            progress_lines(OutputFormat::PiJson, "tool_execution_start", &bash),
            ["$ ls"]
        );
        let write = json!({"type":"tool_execution_start","toolName":"write","args":{"path":"pi.txt","content":"hi"}});
        assert_eq!(
            progress_lines(OutputFormat::PiJson, "tool_execution_start", &write),
            ["write pi.txt"]
        );
        let failed = json!({"type":"tool_execution_end","toolName":"bash","result":{"content":[{"type":"text","text":"out"}]},"isError":true});
        assert_eq!(
            progress_lines(OutputFormat::PiJson, "tool_execution_end", &failed),
            ["bash failed"]
        );
        let update = json!({"type":"tool_execution_update","toolName":"bash","partialResult":{"content":[{"type":"text","text":"out"}]}});
        assert!(progress_lines(OutputFormat::PiJson, "tool_execution_update", &update).is_empty());
    }

    #[test]
    fn credentials_are_redacted() {
        assert_eq!(
            redact("curl -H Authorization: Bearer abc.def https://x"),
            "curl -H Authorization: Bearer … https://x"
        );
        assert_eq!(
            redact("OPENAI_API_KEY=sk-live-123 run"),
            "OPENAI_API_KEY=… run"
        );
        assert_eq!(
            redact("tool --api-key s3cret --verbose"),
            "tool --api-key … --verbose"
        );
        assert_eq!(
            redact("echo sk-abcdefghijklmnop ghp_0123456789abcdef"),
            "echo … …"
        );
        assert_eq!(redact("cargo test -p scv-tools"), "cargo test -p scv-tools");
        assert_eq!(redact("git log --oneline -3"), "git log --oneline -3");
        assert_eq!(
            codex(
                "item.started",
                &json!({"item":{"type":"command_execution","command":"bash -lc 'curl -H \"Authorization: Bearer tok123\" https://api'"}})
            ),
            ["$ curl -H \"Authorization: Bearer … https://api"]
        );
    }

    #[test]
    fn details_are_one_bounded_line() {
        let long = format!("echo {}", "x".repeat(400));
        let line = shell(&long);
        assert!(line.chars().count() <= DETAIL_CHARS + 2);
        assert!(line.ends_with('…'));
        assert_eq!(detail("a\n  b\tc"), "a b c");
    }
}