clash 0.6.1

Command Line Agent Safety Harness — permission policies for coding agents
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use anyhow::{Context, Result};
use serde_json::json;
use tracing::{Level, error, info, instrument, warn};

use crate::settings::ClashSettings;
use crate::style;
use crate::ui;

#[derive(Default)]
struct InitActions {
    policy_created: bool,
    plugin_installed: bool,
    statusline_installed: bool,
}

/// GitHub repository used to install the clash plugin marketplace.
const GITHUB_MARKETPLACE: &str = "empathic/clash";

/// Initialize clash at the chosen scope.
///
/// When `scope` is provided ("user" or "project"), initializes that scope
/// directly. When omitted, runs the interactive policy editor.
/// Only one scope is initialized per invocation.
#[instrument(level = Level::TRACE)]
pub fn run(scope: Option<String>, quick: bool, agent: crate::agents::AgentKind) -> Result<()> {
    if agent != crate::agents::AgentKind::Claude {
        return run_init_agent(agent, scope);
    }
    match scope.as_deref() {
        Some("project") => run_init_project(),
        _ if quick => run_init_quick(),
        _ => run_init_user(),
    }
}

/// Initialize or reconfigure the user-level policy via the interactive editor.
fn run_init_user() -> Result<()> {
    let mut actions = InitActions::default();

    let policy_path = write_starter_policy()?;
    crate::tui::run_with_options(&policy_path, false, true)?;
    actions.policy_created = true;

    // Always ensure settings.json records clash as an enabled plugin.
    let claude = claude_settings::ClaudeSettings::new();
    if let Err(e) = claude.set_plugin_enabled(claude_settings::SettingsLevel::User, "clash", true) {
        warn!(error = %e, "Could not set enabledPlugins in Claude Code settings");
    }

    // Install the Claude Code plugin from GitHub.
    match install_plugin() {
        Ok(()) => {
            actions.plugin_installed = true;
        }
        Err(e) => {
            error!(error = %e, "Could not install clash plugin");
            ui::warn(&format!(
                "Could not install the clash plugin: {e}\n  \
                 You can install it manually later:\n    \
                 claude plugin marketplace add {GITHUB_MARKETPLACE}\n    \
                 claude plugin install clash"
            ));
        }
    };

    // Install the status line so the user gets ambient policy visibility.
    if let Err(e) = super::statusline::install() {
        warn!(error = %e, "Could not install status line");
    } else {
        actions.statusline_installed = true;
    }

    print_user_summary(&actions);

    Ok(())
}

/// Quick-init: skip the interactive editor and write a sensible default policy directly.
fn run_init_quick() -> Result<()> {
    let settings_dir =
        ClashSettings::settings_dir().context("could not determine clash settings directory")?;

    std::fs::create_dir_all(&settings_dir)
        .with_context(|| format!("failed to create {}", settings_dir.display()))?;

    let policy_path = settings_dir.join("policy.star");

    let quick_policy = {
        use clash_starlark::codegen::ast::Stmt;
        use clash_starlark::codegen::builder::*;

        clash_starlark::codegen::serialize(&[
            load_std(&["match", "tool", "policy", "allow", "ask"]),
            Stmt::Blank,
            Stmt::def(
                "main",
                vec![Stmt::Return(policy(
                    ask(),
                    vec![
                        clash_starlark::match_tree! {
                            "Bash" => {
                                ("git", "cargo", "npm", "npx", "node", "bun", "python", "pip", "uv") => allow(),
                            },
                        },
                        tool(&["Read"]).allow(),
                        tool(&["Write"]).allow(),
                        tool(&["Edit"]).allow(),
                        tool(&["Glob"]).allow(),
                        tool(&["Grep"]).allow(),
                    ],
                    None,
                ))],
            ),
        ])
    };

    std::fs::write(&policy_path, quick_policy)
        .with_context(|| format!("failed to write {}", policy_path.display()))?;

    ui::success(&format!(
        "Quick setup: policy created at {}",
        policy_path.display()
    ));

    // Ensure settings.json records clash as an enabled plugin.
    let claude = claude_settings::ClaudeSettings::new();
    if let Err(e) = claude.set_plugin_enabled(claude_settings::SettingsLevel::User, "clash", true) {
        warn!(error = %e, "Could not set enabledPlugins in Claude Code settings");
    }

    // Install the Claude Code plugin from GitHub.
    if let Err(e) = install_plugin() {
        error!(error = %e, "Could not install clash plugin");
        ui::warn(&format!(
            "Could not install the clash plugin: {e}\n  \
             You can install it manually later:\n    \
             claude plugin marketplace add {GITHUB_MARKETPLACE}\n    \
             claude plugin install clash"
        ));
    }

    // Install the status line so the user gets ambient policy visibility.
    if let Err(e) = super::statusline::install() {
        warn!(error = %e, "Could not install status line");
    }

    Ok(())
}

/// Initialize a project-level policy in the project root's `.clash/` directory.
fn run_init_project() -> Result<()> {
    let project_root = ClashSettings::project_root()
        .context("could not find project root — are you inside a git repository?")?;

    let clash_dir = project_root.join(".clash");
    let policy_path = clash_dir.join("policy.star");

    if policy_path.exists() {
        ui::skip(&format!(
            "Project policy already exists at {}",
            policy_path.display()
        ));
        return Ok(());
    }

    std::fs::create_dir_all(&clash_dir)
        .with_context(|| format!("failed to create {}", clash_dir.display()))?;

    let project_policy = "load(\"@clash//std.star\", \"policy\", \"deny\")\ndef main():\n    return policy(default = deny(), rules = [])\n";
    std::fs::write(&policy_path, project_policy)
        .with_context(|| format!("failed to write {}", policy_path.display()))?;

    ui::success(&format!(
        "Project policy initialized at {}",
        policy_path.display()
    ));

    println!();
    println!("{}", style::bold("Setup complete!"));
    println!();
    ui::success(&format!(
        "Project policy created at {}",
        policy_path.display()
    ));
    println!();
    println!("{}:", style::bold("Next steps"));
    println!(
        "  {}  {}",
        style::dim("clash policy show"),
        style::dim("# view the compiled policy")
    );
    println!(
        "  {}  {}",
        style::dim("clash policy validate"),
        style::dim("# check for errors")
    );

    Ok(())
}

/// Build the starter policy JSON value for onboarding.
///
/// Includes pre-configured rules for base Claude tools (Read, Write, Edit,
/// Glob, Grep) so new users start with a working set of file-operation
/// permissions out of the box.
fn starter_policy_json() -> serde_json::Value {
    json!({
        "schema_version": 5,
        "default_effect": "ask",
        "default_sandbox": "default",
        "includes": [{"path": "@clash//builtin.star"}],
        "sandboxes": {
            "default": {
                "default": ["read", "execute"],
                "rules": [
                    {
                        "effect": "allow",
                        "caps": ["read", "write", "create"],
                        "path": "$PWD",
                        "path_match": "subpath"
                    },
                    {
                        "effect": "allow",
                        "caps": ["read", "write", "create"],
                        "path": "$TMPDIR",
                        "path_match": "subpath"
                    },
                    {
                        "effect": "allow",
                        "caps": ["read"],
                        "path": "$HOME",
                        "path_match": "subpath"
                    }
                ],
                "network": "deny"
            }
        },
        "tree": [
            {
                "condition": {
                    "observe": "tool_name",
                    "pattern": { "any_of": [
                        { "literal": { "literal": "Read" } },
                        { "literal": { "literal": "Glob" } },
                        { "literal": { "literal": "Grep" } }
                    ]},
                    "children": [{ "decision": { "allow": "default" } }]
                }
            },
            {
                "condition": {
                    "observe": "tool_name",
                    "pattern": { "any_of": [
                        { "literal": { "literal": "Write" } },
                        { "literal": { "literal": "Edit" } }
                    ]},
                    "children": [{ "decision": { "allow": "default" } }]
                }
            }
        ]
    })
}

/// Write a starter policy.json for onboarding.
///
/// Creates a minimal policy with `default_effect: "ask"`, the builtin include,
/// a sensible dev sandbox, and an empty rule tree. Returns the path to the file.
pub fn write_starter_policy() -> Result<std::path::PathBuf> {
    let policy_path = ClashSettings::policy_file()?;
    let policy_path = policy_path.with_extension("json");
    let dir = policy_path
        .parent()
        .context("policy file path has no parent directory")?;
    std::fs::create_dir_all(dir).with_context(|| format!("failed to create {}", dir.display()))?;

    let policy = starter_policy_json();

    std::fs::write(&policy_path, serde_json::to_string_pretty(&policy)?)
        .with_context(|| format!("failed to write {}", policy_path.display()))?;

    Ok(policy_path)
}

fn print_user_summary(actions: &InitActions) {
    let any_action =
        actions.policy_created || actions.plugin_installed || actions.statusline_installed;
    if !any_action {
        return;
    }

    println!();
    println!(
        "{}",
        style::bold("Setup complete! Here's what was configured:")
    );
    println!();

    if actions.policy_created {
        ui::success("Policy created");
    }
    if actions.plugin_installed {
        ui::success("Clash plugin installed in Claude Code");
    }
    if actions.statusline_installed {
        ui::success("Status line installed");
    }

    println!();
    println!("{}:", style::bold("To undo"));
    println!(
        "  {}  {}",
        style::dim("clash uninstall"),
        style::dim("# remove everything")
    );
    if actions.policy_created {
        println!(
            "  {}  {}",
            style::dim("clash policy edit"),
            style::dim("# modify your policy")
        );
    }

    println!();
    println!("{}:", style::bold("Next steps"));
    println!(
        "  {}  {}",
        style::dim("claude"),
        style::dim("# start a session with clash active")
    );
    println!(
        "  {}  {}",
        style::dim("/clash:status"),
        style::dim("# check policy status inside a session")
    );
    println!(
        "  {}  {}",
        style::dim("/clash:edit"),
        style::dim("# interactively edit your policy")
    );
}

/// Initialize clash for a non-Claude agent.
///
/// Creates the policy (same policy file — portable across agents) and prints
/// agent-specific setup instructions.
fn run_init_agent(agent: crate::agents::AgentKind, scope: Option<String>) -> Result<()> {
    use crate::agents::AgentKind;

    // Write the policy (same as Claude — policies are agent-agnostic).
    let settings_dir = if scope.as_deref() == Some("project") {
        let root = ClashSettings::project_root()
            .context("could not find project root — are you inside a git repository?")?;
        let dir = root.join(".clash");
        std::fs::create_dir_all(&dir)?;
        dir
    } else {
        let dir = ClashSettings::settings_dir()
            .context("could not determine clash settings directory")?;
        std::fs::create_dir_all(&dir)?;
        dir
    };

    let policy_path = settings_dir.join("policy.star");
    if !policy_path.exists() {
        write_starter_policy()?;
        ui::success(&format!("Policy created at {}", policy_path.display()));
    } else {
        ui::info(&format!(
            "Policy already exists at {}",
            policy_path.display()
        ));
    }

    // Print agent-specific setup instructions.
    println!();
    style::header(&format!("Setup instructions for {agent}"));
    println!();

    match agent {
        AgentKind::Gemini => {
            println!("  Install the Clash extension for Gemini CLI:");
            println!(
                "    {}",
                style::bold("gemini extensions install <path-to-clash-gemini-ext>")
            );
            println!();
            println!("  Or copy hooks manually to ~/.gemini/settings.json.");
        }
        AgentKind::Codex => {
            println!("  Add the following to your ~/.codex/config.toml:");
            println!();
            println!("    {}", style::dim("[hooks.pre_tool_use]"));
            println!(
                "    {}",
                style::dim("command = \"clash hook --agent codex pre-tool-use\"")
            );
            println!("    {}", style::dim("timeout_seconds = 10"));
            println!("    {}", style::dim("pattern = \"*\""));
            println!();
            println!("  See clash-codex/hooks.toml for the full configuration.");
        }
        AgentKind::AmazonQ => {
            println!("  Add Clash hooks to your Amazon Q agent configuration.");
            println!("  See clash-amazonq/agent.json for the hook definitions.");
        }
        AgentKind::OpenCode => {
            println!("  Copy the Clash plugin to your OpenCode plugins directory:");
            println!(
                "    {}",
                style::bold("cp clash-opencode/plugin.ts .opencode/plugins/clash.ts")
            );
        }
        AgentKind::Copilot => {
            println!("  Copy the hooks configuration to your repository:");
            println!(
                "    {}",
                style::bold("cp -r clash-copilot/.github/hooks .github/hooks")
            );
        }
        AgentKind::Claude => unreachable!(),
    }

    println!();
    println!(
        "  Then run: {}",
        style::bold(&format!("clash doctor --agent {agent}"))
    );
    println!("  to verify the setup is correct.");

    Ok(())
}

/// Install the clash plugin into Claude Code from the GitHub marketplace.
pub fn install_plugin() -> Result<()> {
    ui::progress(&format!(
        "Installing clash plugin from {}...",
        GITHUB_MARKETPLACE,
    ));

    // Register the marketplace.
    let add_output = std::process::Command::new("claude")
        .args(["plugin", "marketplace", "add", GITHUB_MARKETPLACE])
        .output()
        .context("failed to run `claude plugin marketplace add` — is claude on PATH?")?;

    if !add_output.status.success() {
        let stderr = String::from_utf8_lossy(&add_output.stderr);
        // "already exists" is fine — marketplace was previously registered.
        if !stderr.contains("already") {
            anyhow::bail!("claude plugin marketplace add failed: {stderr}");
        }
        info!("marketplace already registered, continuing");
    }

    // Install the plugin.
    let install_output = std::process::Command::new("claude")
        .args(["plugin", "install", "clash"])
        .output()
        .context("failed to run `claude plugin install`")?;

    if !install_output.status.success() {
        let stderr = String::from_utf8_lossy(&install_output.stderr);
        // "already installed" is fine.
        if !stderr.contains("already") {
            anyhow::bail!("claude plugin install failed: {stderr}");
        }
        info!("plugin already installed");
    }

    ui::success("Clash plugin installed in Claude Code.");
    Ok(())
}

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

    #[test]
    fn starter_policy_compiles() {
        let policy = starter_policy_json();
        let json_str = serde_json::to_string_pretty(&policy).expect("serialize starter policy");
        crate::policy::compile::compile_to_tree(&json_str)
            .expect("starter policy must compile without errors");
    }
}