use std::collections::BTreeSet;
use std::io::IsTerminal;
use std::process::Command;
use anyhow::{bail, Context, Result};
use inquire::Select;
use serde::Deserialize;
pub const SKILLS_SOURCE: &str = "coralogix/cx-cli/skills";
const INSTALLED_SOURCE: &str = "coralogix/cx-cli";
const MANUAL_INSTALL_CMD: &str = "npx skills add coralogix/cx-cli/skills";
const SKILLS_REVIEW_URL: &str = "https://skills.sh/coralogix/cx-cli";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkillsScope {
Global,
Local,
}
pub struct InstallOptions {
pub scope: Option<SkillsScope>,
pub agents: Vec<String>,
pub skip_if_installed: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstallOutcome {
Installed,
AlreadyInstalled,
}
#[derive(Debug, PartialEq, Eq)]
enum Preflight {
Fail(String),
Proceed {
scope: Option<SkillsScope>,
},
}
fn preflight(
npx_available: bool,
scope: Option<SkillsScope>,
stdin_is_terminal: bool,
) -> Preflight {
if !npx_available {
return Preflight::Fail(
"Node.js/npx is required to install the cx agent skills.\n\
Install Node.js (https://nodejs.org) and rerun, or skip the skills install."
.to_string(),
);
}
if scope.is_none() && !stdin_is_terminal {
return Preflight::Fail(
"no skills install scope - pass --global or --local \
(--global-skills/--local-skills on `cx init`)"
.into(),
);
}
Preflight::Proceed { scope }
}
pub fn run_install(opts: InstallOptions) -> Result<InstallOutcome> {
let scope = match preflight(npx_available(), opts.scope, std::io::stdin().is_terminal()) {
Preflight::Fail(message) => bail!(message),
Preflight::Proceed { scope } => match scope {
Some(scope) => scope,
None => ask_scope()?,
},
};
let installed = installed_cx_skills(scope);
if !installed.is_empty() {
if opts.skip_if_installed {
return Ok(InstallOutcome::AlreadyInstalled);
}
println!(
"cx agent skills already installed ({}) - reinstalling to update.",
installed_summary(&installed)
);
}
let args = build_install_args(scope, &opts.agents);
println!("Installing cx agent skills…");
let output = Command::new(npx_program())
.args(&args)
.output()
.context("failed to run npx")?;
if !output.status.success() {
for captured in [&output.stdout, &output.stderr] {
let text = String::from_utf8_lossy(captured);
let trimmed = text.trim();
if !trimmed.is_empty() {
eprintln!("{trimmed}");
}
}
bail!(
"skills installer exited with {}.\n\
You can retry manually with: {MANUAL_INSTALL_CMD}",
output.status
);
}
print_install_summary(scope);
Ok(InstallOutcome::Installed)
}
fn print_install_summary(scope: SkillsScope) {
let scope_label = match scope {
SkillsScope::Global => "global",
SkillsScope::Local => "local",
};
let count = installed_cx_skills(scope).len();
if count > 0 {
println!(
"✓ Installed {count} cx agent skills ({scope_label}). \
Browse them at: {SKILLS_REVIEW_URL}"
);
} else {
println!(
"✓ cx agent skills installed ({scope_label}). \
Browse them at: {SKILLS_REVIEW_URL}"
);
}
}
pub fn run_advanced_install() -> Result<()> {
println!("Running the skills installer interactively: {MANUAL_INSTALL_CMD}");
let status = Command::new(npx_program())
.args(["skills", "add", SKILLS_SOURCE])
.status()
.context(
"failed to run npx - Node.js is required for the skills install \
(https://nodejs.org)",
)?;
if !status.success() {
bail!("skills installer exited with {status}");
}
Ok(())
}
fn npx_program() -> &'static str {
if cfg!(windows) {
"npx.cmd"
} else {
"npx"
}
}
fn npx_available() -> bool {
Command::new(npx_program())
.arg("--version")
.output()
.map(|out| out.status.success())
.unwrap_or(false)
}
#[derive(Deserialize)]
struct LsSkill {
name: String,
#[serde(default)]
source: Option<String>,
}
fn installed_cx_skills(scope: SkillsScope) -> Vec<String> {
let mut cmd = Command::new(npx_program());
cmd.args(["-y", "skills", "ls"]);
if scope == SkillsScope::Global {
cmd.arg("-g");
}
cmd.arg("--json");
let Ok(output) = cmd.output() else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
let Ok(skills) = serde_json::from_slice::<Vec<LsSkill>>(&output.stdout) else {
return Vec::new();
};
skills
.into_iter()
.filter(|skill| skill.source.as_deref() == Some(INSTALLED_SOURCE))
.map(|skill| skill.name)
.collect::<BTreeSet<_>>()
.into_iter()
.collect()
}
fn build_install_args(scope: SkillsScope, agents: &[String]) -> Vec<String> {
let mut args: Vec<String> = vec![
"-y".into(),
"skills".into(),
"add".into(),
SKILLS_SOURCE.into(),
"--skill".into(),
"*".into(),
"-y".into(),
];
if scope == SkillsScope::Global {
args.push("-g".into());
}
if !agents.is_empty() {
args.push("-a".into());
args.extend(agents.iter().cloned());
}
args
}
fn installed_summary(installed: &[String]) -> String {
const SHOWN: usize = 3;
let names = installed
.iter()
.take(SHOWN)
.map(String::as_str)
.collect::<Vec<_>>()
.join(", ");
let suffix = if installed.len() > SHOWN { ", ..." } else { "" };
format!("{} skills: {names}{suffix}", installed.len())
}
fn ask_scope() -> Result<SkillsScope> {
const GLOBAL: &str = "Global (~/) - available in every project";
const LOCAL: &str = "Local (./) - this project only";
let chosen = Select::new(
"Where should the agent skills be installed?",
vec![GLOBAL, LOCAL],
)
.with_help_message(
"Skills teach coding agents (Claude Code, Cursor, Codex, ...) how to use cx.",
)
.prompt()?;
Ok(if chosen == GLOBAL {
SkillsScope::Global
} else {
SkillsScope::Local
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn install_args_local_scope() {
let args = build_install_args(SkillsScope::Local, &[]);
assert_eq!(
args,
["-y", "skills", "add", SKILLS_SOURCE, "--skill", "*", "-y"]
);
}
#[test]
fn install_args_global_scope() {
let args = build_install_args(SkillsScope::Global, &[]);
assert_eq!(
args,
[
"-y",
"skills",
"add",
SKILLS_SOURCE,
"--skill",
"*",
"-y",
"-g"
]
);
}
#[test]
fn install_args_pass_agents_through() {
let args = build_install_args(
SkillsScope::Global,
&["claude-code".to_string(), "cursor".to_string()],
);
assert_eq!(
args,
[
"-y",
"skills",
"add",
SKILLS_SOURCE,
"--skill",
"*",
"-y",
"-g",
"-a",
"claude-code",
"cursor"
]
);
}
#[test]
fn summary_truncates_long_skill_lists() {
let skills: Vec<String> = ["cx-a", "cx-b", "cx-c", "cx-d"]
.iter()
.map(|s| s.to_string())
.collect();
assert_eq!(
installed_summary(&skills),
"4 skills: cx-a, cx-b, cx-c, ..."
);
assert_eq!(installed_summary(&skills[..2]), "2 skills: cx-a, cx-b");
}
#[test]
fn ls_json_matches_only_our_source_ignoring_extra_fields() {
let json = r#"[
{"name": "cx-alerts", "path": "/p", "scope": "global",
"agents": ["Claude Code"], "source": "coralogix/cx-cli",
"sourceUrl": null, "sourceType": "github"},
{"name": "cx-other", "source": "someone/else"},
{"name": "cx-copied", "source": null}
]"#;
let skills: Vec<LsSkill> = serde_json::from_str(json).unwrap();
let ours: Vec<&str> = skills
.iter()
.filter(|s| s.source.as_deref() == Some(INSTALLED_SOURCE))
.map(|s| s.name.as_str())
.collect();
assert_eq!(ours, ["cx-alerts"]);
}
#[test]
fn preflight_no_npx_fails_actionably() {
let Preflight::Fail(message) = preflight(false, None, true) else {
panic!("expected Fail");
};
assert!(message.contains("Node.js"));
}
#[test]
fn preflight_no_scope_no_tty_fails_naming_the_flags() {
let Preflight::Fail(message) = preflight(true, None, false) else {
panic!("expected Fail");
};
assert!(message.contains("--global") && message.contains("--local"));
}
#[test]
fn preflight_no_scope_with_tty_asks() {
assert_eq!(
preflight(true, None, true),
Preflight::Proceed { scope: None }
);
}
#[test]
fn preflight_scope_flag_proceeds_without_asking() {
assert_eq!(
preflight(true, Some(SkillsScope::Local), false),
Preflight::Proceed {
scope: Some(SkillsScope::Local)
}
);
}
}