cc-switch-tui 0.2.1

All-in-One Assistant for Claude Code, Codex, Gemini, OpenCode, OpenClaw & Hermes
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
use clap::Subcommand;
use std::future::Future;

use crate::app_config::AppType;
use crate::cli::ui::{create_table, highlight, info, success};
use crate::error::AppError;
use crate::services::skill::{SkillRepo, SyncMethod};
use crate::services::SkillService;

#[derive(Subcommand)]
pub enum SkillsCommand {
    /// List installed skills (from SSOT + database state)
    List,
    /// Discover available skills (from enabled repos)
    #[command(alias = "search")]
    Discover {
        /// Optional query filter (matches name/directory)
        query: Option<String>,
    },
    /// Install a skill (SSOT -> app skills dir)
    Install {
        /// Skill directory name or full key (owner/name:directory)
        spec: String,
    },
    /// Uninstall a skill (remove from SSOT and app dirs)
    Uninstall {
        /// Skill directory or id
        spec: String,
    },
    /// Enable a skill for the selected app
    Enable {
        /// Skill directory or id
        spec: String,
    },
    /// Disable a skill for the selected app
    Disable {
        /// Skill directory or id
        spec: String,
    },
    /// Sync enabled skills to app skills dirs
    Sync,
    /// Scan unmanaged skills in app skills dirs
    ScanUnmanaged,
    /// Import unmanaged skills from app skills dirs into SSOT
    ImportFromApps {
        /// One or more skill directories to import
        directories: Vec<String>,
    },
    /// Show skill information
    Info {
        /// Skill directory or id
        spec: String,
    },
    /// Get or set the skills sync method (auto|symlink|copy)
    SyncMethod {
        /// Optional method to set (omit to show current)
        #[arg(value_enum)]
        method: Option<SyncMethod>,
    },
    /// Manage skill repositories
    #[command(subcommand)]
    Repos(SkillReposCommand),
}

#[derive(Subcommand)]
pub enum SkillReposCommand {
    /// List all repositories
    List,
    /// Add a repository
    Add {
        /// Repository (GitHub URL or owner/name[@branch])
        url: String,
    },
    /// Remove a repository
    Remove {
        /// Repository (GitHub URL or owner/name)
        url: String,
    },
    /// Enable a repository without changing its branch
    Enable {
        /// Repository (GitHub URL or owner/name)
        url: String,
    },
    /// Disable a repository without changing its branch
    Disable {
        /// Repository (GitHub URL or owner/name)
        url: String,
    },
}

pub fn execute(cmd: SkillsCommand, app: Option<AppType>) -> Result<(), AppError> {
    let app_type = app.clone().unwrap_or(AppType::Claude);

    match cmd {
        SkillsCommand::List => list_installed(),
        SkillsCommand::Discover { query } => discover_skills(query.as_deref()),
        SkillsCommand::Install { spec } => install_skill(&app_type, &spec),
        SkillsCommand::Uninstall { spec } => uninstall_skill(&spec),
        SkillsCommand::Enable { spec } => toggle_skill(&app_type, &spec, true),
        SkillsCommand::Disable { spec } => toggle_skill(&app_type, &spec, false),
        SkillsCommand::Sync => sync_skills(app.as_ref()),
        SkillsCommand::ScanUnmanaged => scan_unmanaged(),
        SkillsCommand::ImportFromApps { directories } => import_from_apps(directories),
        SkillsCommand::Info { spec } => show_skill_info(&spec),
        SkillsCommand::SyncMethod { method } => sync_method(method),
        SkillsCommand::Repos(repos_cmd) => execute_repos(repos_cmd),
    }
}

fn run_async<T>(fut: impl Future<Output = Result<T, AppError>>) -> Result<T, AppError> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| AppError::Message(format!("Failed to create runtime: {e}")))?
        .block_on(fut)
}

fn list_installed() -> Result<(), AppError> {
    let skills = SkillService::list_installed()?;

    if skills.is_empty() {
        println!("{}", info("No installed skills found."));
        return Ok(());
    }

    let mut table = create_table();
    table.set_header(vec![
        "Directory",
        "Name",
        "Claude",
        "Codex",
        "Gemini",
        "OpenCode",
    ]);
    for skill in skills {
        table.add_row(vec![
            skill.directory,
            skill.name,
            if skill.apps.claude { "" } else { " " }.to_string(),
            if skill.apps.codex { "" } else { " " }.to_string(),
            if skill.apps.gemini { "" } else { " " }.to_string(),
            if skill.apps.opencode { "" } else { " " }.to_string(),
        ]);
    }

    println!("{}", table);
    Ok(())
}

fn discover_skills(query: Option<&str>) -> Result<(), AppError> {
    let service = SkillService::new()?;
    let mut skills = run_async(service.list_skills())?;

    if let Some(query) = query.map(str::trim).filter(|q| !q.is_empty()) {
        let q = query.to_lowercase();
        skills.retain(|s| {
            s.name.to_lowercase().contains(&q) || s.directory.to_lowercase().contains(&q)
        });
    }

    if skills.is_empty() {
        println!("{}", info("No skills found."));
        return Ok(());
    }

    let mut table = create_table();
    table.set_header(vec!["", "Directory", "Name"]);
    for skill in skills {
        table.add_row(vec![
            if skill.installed { "" } else { " " }.to_string(),
            skill.directory,
            skill.name,
        ]);
    }
    println!("{}", table);
    Ok(())
}

fn install_skill(app_type: &AppType, spec: &str) -> Result<(), AppError> {
    let service = SkillService::new()?;
    let installed = run_async(service.install(spec, app_type))?;
    println!(
        "{}",
        success(&format!(
            "✓ Installed skill '{}' (enabled for {})",
            installed.directory,
            app_type.as_str()
        ))
    );
    Ok(())
}

fn uninstall_skill(spec: &str) -> Result<(), AppError> {
    SkillService::uninstall(spec)?;
    println!("{}", success(&format!("✓ Uninstalled skill '{spec}'")));
    Ok(())
}

fn toggle_skill(app_type: &AppType, spec: &str, enabled: bool) -> Result<(), AppError> {
    SkillService::toggle_app(spec, app_type, enabled)?;
    println!(
        "{}",
        success(&format!(
            "{} '{}' for {}",
            if enabled { "Enabled" } else { "Disabled" },
            spec,
            app_type.as_str()
        ))
    );
    Ok(())
}

fn sync_skills(app: Option<&AppType>) -> Result<(), AppError> {
    SkillService::sync_all_enabled(app)?;
    println!("{}", success("✓ Skills synced successfully"));
    Ok(())
}

fn scan_unmanaged() -> Result<(), AppError> {
    let skills = SkillService::scan_unmanaged()?;
    if skills.is_empty() {
        println!("{}", info("No unmanaged skills found."));
        return Ok(());
    }

    let mut table = create_table();
    table.set_header(vec!["Directory", "Found In", "Name"]);
    for s in skills {
        table.add_row(vec![s.directory, s.found_in.join(", "), s.name]);
    }
    println!("{}", table);
    Ok(())
}

fn import_from_apps(directories: Vec<String>) -> Result<(), AppError> {
    if directories.is_empty() {
        return Err(AppError::InvalidInput(
            "Please provide at least one directory".to_string(),
        ));
    }

    let imported = SkillService::import_from_apps(directories)?;
    println!(
        "{}",
        success(&format!("✓ Imported {} skill(s) into SSOT", imported.len()))
    );
    Ok(())
}

fn show_skill_info(spec: &str) -> Result<(), AppError> {
    let index = SkillService::load_index()?;

    let record = index
        .skills
        .values()
        .find(|s| s.directory.eq_ignore_ascii_case(spec) || s.id.eq_ignore_ascii_case(spec))
        .ok_or_else(|| AppError::Message(format!("Skill not found: {spec}")))?;

    println!("{}", highlight("Skill"));
    println!("Directory: {}", record.directory);
    println!("Name:      {}", record.name);
    if let Some(desc) = record
        .description
        .as_deref()
        .filter(|s| !s.trim().is_empty())
    {
        println!("Desc:      {}", desc);
    }
    println!(
        "Enabled:   claude={} codex={} gemini={} opencode={}",
        record.apps.claude, record.apps.codex, record.apps.gemini, record.apps.opencode
    );

    Ok(())
}

fn execute_repos(cmd: SkillReposCommand) -> Result<(), AppError> {
    match cmd {
        SkillReposCommand::List => list_repos(),
        SkillReposCommand::Add { url } => add_repo(&url),
        SkillReposCommand::Remove { url } => remove_repo(&url),
        SkillReposCommand::Enable { url } => set_repo_enabled(&url, true),
        SkillReposCommand::Disable { url } => set_repo_enabled(&url, false),
    }
}

fn list_repos() -> Result<(), AppError> {
    let repos = SkillService::list_repos()?;

    if repos.is_empty() {
        println!("{}", info("No skill repos configured."));
        return Ok(());
    }

    let mut table = create_table();
    table.set_header(vec!["Enabled", "Repo", "Branch"]);
    for repo in repos {
        table.add_row(vec![
            if repo.enabled { "" } else { " " }.to_string(),
            format!("{}/{}", repo.owner, repo.name),
            repo.branch,
        ]);
    }
    println!("{}", table);
    Ok(())
}

fn add_repo(_url: &str) -> Result<(), AppError> {
    let repo = parse_repo_spec(_url)?;
    SkillService::upsert_repo(repo)?;
    println!("{}", success("✓ Repository added."));
    Ok(())
}

fn remove_repo(_url: &str) -> Result<(), AppError> {
    let repo = parse_repo_spec(_url)?;
    SkillService::remove_repo(&repo.owner, &repo.name)?;
    println!("{}", success("✓ Repository removed."));
    Ok(())
}

fn set_repo_enabled(url: &str, enabled: bool) -> Result<(), AppError> {
    let repo = parse_repo_spec(url)?;
    let existing = SkillService::list_repos()?
        .into_iter()
        .find(|candidate| candidate.owner == repo.owner && candidate.name == repo.name)
        .ok_or_else(|| {
            AppError::Message(format!(
                "Repository not found: {}/{}",
                repo.owner, repo.name
            ))
        })?;

    SkillService::upsert_repo(repo_with_enabled(existing, enabled))?;
    println!(
        "{}",
        success(&format!(
            "✓ Repository {}.",
            if enabled { "enabled" } else { "disabled" }
        ))
    );
    Ok(())
}

fn repo_with_enabled(mut repo: SkillRepo, enabled: bool) -> SkillRepo {
    repo.enabled = enabled;
    repo
}

fn sync_method(method: Option<SyncMethod>) -> Result<(), AppError> {
    match method {
        Some(method) => {
            SkillService::set_sync_method(method)?;
            println!(
                "{}",
                success(&format!("✓ Skill sync method set to {method:?}"))
            );
        }
        None => {
            let method = SkillService::get_sync_method()?;
            println!("{}", highlight("Skill Sync Method"));
            println!("{method:?}");
        }
    }
    Ok(())
}

fn parse_repo_spec(raw: &str) -> Result<SkillRepo, AppError> {
    let raw = raw.trim().trim_end_matches('/');
    if raw.is_empty() {
        return Err(AppError::InvalidInput(
            "Repository cannot be empty".to_string(),
        ));
    }

    // Allow: https://github.com/owner/name or owner/name[@branch]
    let without_prefix = raw
        .strip_prefix("https://github.com/")
        .or_else(|| raw.strip_prefix("http://github.com/"))
        .unwrap_or(raw);

    let without_git = without_prefix.trim_end_matches(".git");

    let (path, branch) = if let Some((left, right)) = without_git.rsplit_once('@') {
        (left, Some(right))
    } else {
        (without_git, None)
    };

    let Some((owner, name)) = path.split_once('/') else {
        return Err(AppError::InvalidInput(
            "Invalid repo format. Use owner/name or https://github.com/owner/name".to_string(),
        ));
    };

    Ok(SkillRepo {
        owner: owner.to_string(),
        name: name.to_string(),
        branch: branch.unwrap_or("main").to_string(),
        enabled: true,
    })
}

#[cfg(test)]
mod tests {
    use super::{parse_repo_spec, repo_with_enabled};
    use crate::services::skill::SkillRepo;

    #[test]
    fn parse_repo_spec_supports_plain_owner_repo() {
        let repo = parse_repo_spec("foo/bar").expect("plain owner/repo should parse");

        assert_eq!(repo.owner, "foo");
        assert_eq!(repo.name, "bar");
        assert_eq!(repo.branch, "main");
        assert!(repo.enabled);
    }

    #[test]
    fn parse_repo_spec_supports_branch_suffix() {
        let repo = parse_repo_spec("foo/bar@dev").expect("branch suffix should parse");

        assert_eq!(repo.owner, "foo");
        assert_eq!(repo.name, "bar");
        assert_eq!(repo.branch, "dev");
        assert!(repo.enabled);
    }

    #[test]
    fn repo_with_enabled_preserves_branch_and_identity() {
        let repo = SkillRepo {
            owner: "foo".to_string(),
            name: "bar".to_string(),
            branch: "release".to_string(),
            enabled: true,
        };

        let updated = repo_with_enabled(repo, false);

        assert_eq!(updated.owner, "foo");
        assert_eq!(updated.name, "bar");
        assert_eq!(updated.branch, "release");
        assert!(!updated.enabled);
    }
}