codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
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
415
416
417
418
419
420
421
422
//! Approval risk and stakes policy.
//!
//! This module is intentionally UI-free: it classifies tool calls so the
//! approval and elevation views can render the decision without owning the
//! policy itself.

use crate::command_safety::is_parallel_readonly_command;
use crate::tools::canonical_action::canonical_action_alias;
use serde_json::Value;

/// Categorizes tools by cost/risk level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolCategory {
    /// Free, read-only operations (`list_dir`, `read_file`, todo_*)
    Safe,
    /// File modifications (`write_file`, `edit_file`)
    FileWrite,
    /// Shell execution (`exec_shell`)
    Shell,
    /// Network-oriented built-in tools
    Network,
    /// Read-only MCP discovery and resource access
    McpRead,
    /// MCP actions that may change remote state
    McpAction,
    /// Sub-agent lifecycle (`agent` start/status/peek/cancel); the child's
    /// own tool gates govern what it may actually do.
    Agent,
    /// Unknown or unclassified tool surface
    Unknown,
}

/// Stakes-based variant for the takeover modal.
///
/// `RiskLevel::Benign` lets a single keystroke commit the approval.
/// `RiskLevel::Destructive` keeps stronger warning copy and styling
/// around approvals that can touch files, shell, or remote state.
///
/// Routing rules live in [`classify_risk`] - when in doubt, route to
/// `Destructive`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RiskLevel {
    Benign,
    Destructive,
}

/// Presentation-level stakes for the approval prompt (#3883 follow-up).
///
/// `RiskLevel` drives keymaps and stays conservative ("not provably
/// read-only" is `Destructive`), but rendering everything in that bucket
/// as a red DESTRUCTIVE takeover made routine file edits and build
/// commands read like emergencies. Stakes split presentation three ways:
///
/// - `Routine` - provably read-only; minimal chrome.
/// - `Elevated` - ordinary state-touching work (edits, builds, MCP
///   actions); a calm approval, not a warning.
/// - `Critical` - genuinely destructive, publish-like, or
///   secret-touching per `ToolActionKind`; keeps the strong styling and
///   the policy semantics lines.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalStakes {
    Routine,
    Elevated,
    Critical,
}

/// Get the category for a tool by name.
pub fn get_tool_category(name: &str) -> ToolCategory {
    if name == "agent" || name == "workflow" {
        // Workflow is multi-agent orchestration; reuse Agent stakes/routing
        // and specialize the impact card via build_impact_summary (#4126).
        ToolCategory::Agent
    } else if matches!(
        name,
        "write" | "edit" | "write_file" | "edit_file" | "apply_patch"
    ) {
        ToolCategory::FileWrite
    } else if matches!(
        name,
        "web_run" | "web_search" | "fetch_url" | "wait_for_dev_server" | "registry_sync"
    ) {
        ToolCategory::Network
    } else if matches!(
        name,
        "bash"
            | "Bash"
            | "exec_shell"
            | "task_shell_start"
            | "task_shell_wait"
            | "exec_shell_wait"
            | "exec_shell_interact"
            | "exec_shell_cancel"
            | "exec_wait"
            | "exec_interact"
    ) {
        ToolCategory::Shell
    } else if name.starts_with("list_mcp_")
        || name.starts_with("read_mcp_")
        || name.starts_with("get_mcp_")
    {
        ToolCategory::McpRead
    } else if name.starts_with("mcp_") {
        ToolCategory::McpAction
    } else if matches!(
        name,
        "read"
            | "read_file"
            | "list_dir"
            | "work_update"
            | "todo_write"
            | "todo_read"
            | "checklist_write"
            | "note"
            | "update_plan"
            | "search"
            | "file_search"
            | "grep_files"
            | "git_status"
            | "git_diff"
            | "git_log"
            | "git_show"
            | "git_blame"
            | "project"
            | "diagnostics"
    ) || name.starts_with("read_")
        || name.starts_with("list_")
        || name.starts_with("get_")
    {
        ToolCategory::Safe
    } else if matches!(name, "start_mcp_server" | "start_registry_mcp_server") {
        // Starting an MCP server spawns child processes or opens network
        // connections — classify as McpAction to trigger appropriate
        // approval prompts.
        ToolCategory::McpAction
    } else {
        ToolCategory::Unknown
    }
}

/// Categorize a concrete call after resolving an action-based canonical tool.
#[must_use]
pub fn get_tool_category_for_call(name: &str, params: &Value) -> ToolCategory {
    get_tool_category(canonical_action_alias(name, params))
}

#[must_use]
pub fn classify_stakes(
    tool_name: &str,
    category: ToolCategory,
    risk: RiskLevel,
    params: &Value,
) -> ApprovalStakes {
    if matches!(risk, RiskLevel::Benign) {
        return ApprovalStakes::Routine;
    }
    let semantic_name = canonical_action_alias(tool_name, params);
    match crate::tui::auto_review::ToolActionKind::from_tool_call(semantic_name, params, category) {
        crate::tui::auto_review::ToolActionKind::Publish
        | crate::tui::auto_review::ToolActionKind::Destructive => ApprovalStakes::Critical,
        _ => ApprovalStakes::Elevated,
    }
}

/// Decide the stakes variant for an approval request.
///
/// The bias is conservative: a category we don't recognise routes to
/// `Destructive`, and any shell command that `command_safety` flags as
/// `Dangerous` is forced to `Destructive` even when the rest of the
/// request looks calm. The split lets the modal render stronger warning
/// copy on anything that can touch state outside this turn.
#[must_use]
pub fn classify_risk(tool_name: &str, category: ToolCategory, params: &Value) -> RiskLevel {
    let tool_name = canonical_action_alias(tool_name, params);
    match category {
        // Read paths and discovery.
        ToolCategory::Safe | ToolCategory::McpRead => RiskLevel::Benign,
        // Query-only network is benign; opening a URL pulls arbitrary
        // remote content, so it stays destructive.
        ToolCategory::Network => match tool_name {
            "web_search" | "wait_for_dev_server" | "registry_sync" => RiskLevel::Benign,
            // web_run is benign for search/query, but its `open`/`click`
            // actions fetch model-supplied URLs (arbitrary remote content) -
            // destructive, consistent with fetch_url.
            "web_run" => {
                let fetches_url = params
                    .get("open")
                    .and_then(Value::as_array)
                    .is_some_and(|a| !a.is_empty())
                    || params
                        .get("click")
                        .and_then(Value::as_array)
                        .is_some_and(|a| !a.is_empty());
                if fetches_url {
                    RiskLevel::Destructive
                } else {
                    RiskLevel::Benign
                }
            }
            _ => RiskLevel::Destructive,
        },
        // Shell stays destructive unless the existing command-safety analyzer
        // can prove the concrete command is read-only.
        ToolCategory::Shell => {
            if let Some(cmd) = params.get("command").and_then(Value::as_str)
                && is_parallel_readonly_command(cmd)
            {
                return RiskLevel::Benign;
            }
            RiskLevel::Destructive
        }
        // Sub-agent lifecycle: status/peek are inspection-only. Starts and
        // other actions keep the explicit-options keymap (the child's own
        // gates govern what it may do once running).
        ToolCategory::Agent => match params.get("action").and_then(Value::as_str) {
            Some("status" | "peek" | "list") => RiskLevel::Benign,
            _ => RiskLevel::Destructive,
        },
        // File writes, MCP actions, unclassified surfaces - all require
        // explicit confirmation.
        ToolCategory::FileWrite | ToolCategory::McpAction | ToolCategory::Unknown => {
            RiskLevel::Destructive
        }
    }
}

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

    #[test]
    fn classifies_read_only_surfaces_as_benign() {
        for name in ["read_file", "list_dir", "list_mcp_tools", "web_search"] {
            let category = get_tool_category(name);
            assert_eq!(
                classify_risk(name, category, &json!({})),
                RiskLevel::Benign,
                "{name}"
            );
        }
    }

    #[test]
    fn classifies_stateful_or_unknown_surfaces_as_destructive() {
        for name in [
            "write_file",
            "edit_file",
            "apply_patch",
            "mcp_linear_save_issue",
            "fetch_url",
            "unknown_tool",
        ] {
            let category = get_tool_category(name);
            assert_eq!(
                classify_risk(name, category, &json!({})),
                RiskLevel::Destructive,
                "{name}"
            );
        }
    }

    #[test]
    fn shell_risk_uses_command_safety_analysis() {
        let category = get_tool_category("exec_shell");
        assert_eq!(
            classify_risk(
                "exec_shell",
                category,
                &json!({"command": "git status --short"})
            ),
            RiskLevel::Benign
        );
        assert_eq!(
            classify_risk(
                "exec_shell",
                category,
                &json!({"command": "rm -rf /tmp/example"})
            ),
            RiskLevel::Destructive
        );
    }

    #[test]
    fn shell_exec_flags_are_not_benign() {
        let category = get_tool_category("exec_shell");
        for command in [
            "fd -x ./pwn.sh",
            "fd -uHtx ./pwn.sh",
            "rg --pre /tmp/evil.sh needle .",
            "git grep -O needle",
            "git grep -nO needle",
        ] {
            assert_eq!(
                classify_risk("exec_shell", category, &json!({"command": command})),
                RiskLevel::Destructive,
                "{command} should not be classified as benign"
            );
        }

        for command in [
            "fd -e rs .",
            "fd -H --type f src",
            "rg needle crates/",
            "git grep needle crates/",
            "git grep -n needle crates/",
        ] {
            assert_eq!(
                classify_risk("exec_shell", category, &json!({"command": command})),
                RiskLevel::Benign,
                "{command} should remain benign"
            );
        }
    }

    #[test]
    fn web_run_open_and_click_fetch_remote_content() {
        let category = get_tool_category("web_run");
        assert_eq!(
            classify_risk(
                "web_run",
                category,
                &json!({"search_query": [{"q": "rust"}]})
            ),
            RiskLevel::Benign
        );
        assert_eq!(
            classify_risk("web_run", category, &json!({"open": [{"ref_id": "x"}]})),
            RiskLevel::Destructive
        );
        assert_eq!(
            classify_risk(
                "web_run",
                category,
                &json!({"click": [{"ref_id": "x", "id": 1}]})
            ),
            RiskLevel::Destructive
        );
    }

    #[test]
    fn canonical_actions_keep_legacy_approval_categories_and_risk() {
        let cases = [
            ("Bash", "run", ToolCategory::Shell, RiskLevel::Destructive),
            ("Bash", "wait", ToolCategory::Shell, RiskLevel::Destructive),
            (
                "Bash",
                "interact",
                ToolCategory::Shell,
                RiskLevel::Destructive,
            ),
            (
                "Bash",
                "cancel",
                ToolCategory::Shell,
                RiskLevel::Destructive,
            ),
            ("File", "read", ToolCategory::Safe, RiskLevel::Benign),
            ("File", "list", ToolCategory::Safe, RiskLevel::Benign),
            ("File", "search_name", ToolCategory::Safe, RiskLevel::Benign),
            (
                "File",
                "search_content",
                ToolCategory::Safe,
                RiskLevel::Benign,
            ),
            (
                "File",
                "write",
                ToolCategory::FileWrite,
                RiskLevel::Destructive,
            ),
            (
                "File",
                "edit",
                ToolCategory::FileWrite,
                RiskLevel::Destructive,
            ),
            (
                "File",
                "patch",
                ToolCategory::FileWrite,
                RiskLevel::Destructive,
            ),
            ("Git", "status", ToolCategory::Safe, RiskLevel::Benign),
            ("Git", "diff", ToolCategory::Safe, RiskLevel::Benign),
            ("Git", "log", ToolCategory::Safe, RiskLevel::Benign),
            ("Git", "show", ToolCategory::Safe, RiskLevel::Benign),
            ("Git", "blame", ToolCategory::Safe, RiskLevel::Benign),
            (
                "Run",
                "tests",
                ToolCategory::Unknown,
                RiskLevel::Destructive,
            ),
            (
                "Run",
                "verifiers",
                ToolCategory::Unknown,
                RiskLevel::Destructive,
            ),
            ("Web", "search", ToolCategory::Network, RiskLevel::Benign),
            (
                "Web",
                "fetch",
                ToolCategory::Network,
                RiskLevel::Destructive,
            ),
            ("Web", "wait", ToolCategory::Network, RiskLevel::Benign),
        ];

        for (family, action, expected_category, expected_risk) in cases {
            let params = json!({"action": action});
            let category = get_tool_category_for_call(family, &params);
            assert_eq!(category, expected_category, "{family}.{action}");
            assert_eq!(
                classify_risk(family, category, &params),
                expected_risk,
                "{family}.{action}"
            );
        }
    }
}