use std::env::current_dir;
use clap::{Args, Parser, Subcommand};
#[derive(Debug, Parser)]
#[command(
name = "ask",
version,
about = "Agent Skills Kit - Download version-specific library docs for AI coding agents",
propagate_version = true
)]
pub struct Cli {
#[command(subcommand)]
pub command: Command,
}
#[derive(Debug, Subcommand)]
pub enum Command {
Install,
Add(AddArgs),
Remove(RemoveArgs),
List(ListArgs),
Src(SrcArgs),
Docs(DocsArgs),
Fetch(FetchArgs),
Search(SearchArgs),
Skills(SkillsArgs),
Cache(CacheArgs),
}
#[derive(Debug, Args)]
pub struct AddArgs {
pub spec: Option<String>,
#[arg(long = "docs-paths")]
pub docs_paths: Option<String>,
#[arg(long = "clear-docs-paths")]
pub clear_docs_paths: bool,
}
#[derive(Debug, Args)]
pub struct RemoveArgs {
pub name: String,
}
#[derive(Debug, Args)]
pub struct ListArgs {
#[arg(long)]
pub json: bool,
}
#[derive(Debug, Args)]
pub struct SrcArgs {
pub spec: String,
#[arg(long = "no-fetch")]
pub no_fetch: bool,
#[arg(long)]
pub json: bool,
}
#[derive(Debug, Args)]
pub struct DocsArgs {
pub spec: String,
#[arg(long = "no-fetch")]
pub no_fetch: bool,
#[arg(long)]
pub json: bool,
}
#[derive(Debug, Args)]
pub struct FetchArgs {
#[arg(required = true)]
pub specs: Vec<String>,
#[arg(short = 'q', long)]
pub quiet: bool,
}
#[derive(Debug, Args)]
pub struct SearchArgs {
pub spec: String,
pub query: String,
#[arg(long)]
pub content: Option<String>,
#[arg(long = "top-k")]
pub top_k: Option<String>,
#[arg(long = "no-fetch")]
pub no_fetch: bool,
}
#[derive(Debug, Args)]
pub struct SkillsArgs {
#[command(subcommand)]
pub command: Option<SkillsCommand>,
#[arg(value_name = "SPEC")]
pub spec: Option<String>,
#[arg(long = "no-fetch")]
pub no_fetch: bool,
}
#[derive(Debug, Subcommand)]
pub enum SkillsCommand {
List(SkillsListArgs),
Install(SkillsInstallArgs),
Remove(SkillsRemoveArgs),
}
#[derive(Debug, Args)]
pub struct SkillsListArgs {
pub spec: String,
#[arg(long = "no-fetch")]
pub no_fetch: bool,
}
#[derive(Debug, Args)]
pub struct SkillsInstallArgs {
pub spec: String,
#[arg(long = "no-fetch")]
pub no_fetch: bool,
#[arg(long)]
pub force: bool,
#[arg(long)]
pub agent: Option<String>,
}
#[derive(Debug, Args)]
pub struct SkillsRemoveArgs {
pub spec: String,
#[arg(long = "ignore-missing")]
pub ignore_missing: bool,
}
#[derive(Debug, Args)]
pub struct CacheArgs {
#[command(subcommand)]
pub command: CacheCommand,
}
#[derive(Debug, Subcommand)]
pub enum CacheCommand {
Ls(CacheLsArgs),
Gc(CacheGcArgs),
Clean(CacheCleanArgs),
}
#[derive(Debug, Args)]
pub struct CacheLsArgs {
#[arg(long)]
pub kind: Option<String>,
#[arg(long)]
pub json: bool,
}
#[derive(Debug, Args)]
pub struct CacheGcArgs {
#[arg(long = "dry-run")]
pub dry_run: bool,
#[arg(long = "older-than")]
pub older_than: Option<String>,
#[arg(long)]
pub json: bool,
}
#[derive(Debug, Args)]
pub struct CacheCleanArgs {
#[arg(long)]
pub legacy: bool,
}
pub fn run(cli: Cli) -> anyhow::Result<()> {
match cli.command {
Command::Install => {
crate::install::run_install(¤t_dir()?, &Default::default())?;
Ok(())
}
Command::List(args) => run_list(args),
Command::Add(args) => run_add_cmd(args),
Command::Remove(args) => run_remove_cmd(args),
Command::Src(args) => run_src_cmd(args),
Command::Docs(args) => run_docs_cmd(args),
Command::Fetch(args) => run_fetch_cmd(args),
Command::Search(args) => run_search_cmd(args),
Command::Skills(args) => run_skills_cmd(args),
Command::Cache(args) => run_cache_cmd(args),
}
}
fn run_add_cmd(args: AddArgs) -> anyhow::Result<()> {
let client = crate::http::UreqClient::new();
let project_dir = current_dir()?;
let Some(spec) = args.spec else {
use crate::commands::add::{run_interactive_add, RunInteractiveDeps};
let report = run_interactive_add(&client, &project_dir, &RunInteractiveDeps::default())?;
for line in &report.stdout {
println!("{line}");
}
for line in &report.stderr {
eprintln!("{line}");
}
if report.exit_code != 0 {
std::process::exit(report.exit_code);
}
return Ok(());
};
use crate::commands::add::{run_add, RunAddDeps, RunAddOptions};
let options = RunAddOptions {
project_dir,
spec,
docs_paths_arg: args.docs_paths,
clear_docs_paths: args.clear_docs_paths,
};
match run_add(&client, &options, &RunAddDeps::default()) {
Ok(report) => {
for line in &report.stdout {
println!("{line}");
}
for line in &report.stderr {
eprintln!("{line}");
}
Ok(())
}
Err(err) => {
eprintln!("{err}");
std::process::exit(1);
}
}
}
fn run_skills_cmd(args: SkillsArgs) -> anyhow::Result<()> {
use crate::commands::skills::{
run_skills_install, run_skills_list, run_skills_remove, RunSkillsInstallOptions,
RunSkillsListOptions, RunSkillsRemoveOptions, SkillsReport,
};
let client = crate::http::UreqClient::new();
let project_dir = current_dir()?;
let report: SkillsReport = match args.command {
None => {
let Some(spec) = args.spec else {
return Ok(());
};
run_skills_list(
&client,
&RunSkillsListOptions {
spec,
project_dir,
no_fetch: args.no_fetch,
},
&Default::default(),
)
}
Some(SkillsCommand::List(a)) => run_skills_list(
&client,
&RunSkillsListOptions {
spec: a.spec,
project_dir,
no_fetch: a.no_fetch,
},
&Default::default(),
),
Some(SkillsCommand::Install(a)) => {
let agents = a.agent.as_deref().and_then(|s| {
let v: Vec<String> = s
.split(',')
.map(|x| x.trim().to_string())
.filter(|x| !x.is_empty())
.collect();
(!v.is_empty()).then_some(v)
});
run_skills_install(
&client,
&RunSkillsInstallOptions {
spec: a.spec,
project_dir,
no_fetch: a.no_fetch,
force: a.force,
agents,
},
&Default::default(),
)?
}
Some(SkillsCommand::Remove(a)) => run_skills_remove(&RunSkillsRemoveOptions {
spec: a.spec,
project_dir,
ignore_missing: a.ignore_missing,
})?,
};
for line in &report.stdout {
println!("{line}");
}
for line in &report.stderr {
eprintln!("{line}");
}
if report.exit_code != 0 {
std::process::exit(report.exit_code);
}
Ok(())
}
fn run_src_cmd(args: SrcArgs) -> anyhow::Result<()> {
use crate::commands::src::{run_src, RunSrcOptions};
let client = crate::http::UreqClient::new();
let options = RunSrcOptions {
spec: args.spec,
project_dir: current_dir()?,
no_fetch: args.no_fetch,
json: args.json,
};
match run_src(&client, &options) {
Ok(out) => {
println!("{out}");
Ok(())
}
Err(err) => {
eprintln!("{err}");
std::process::exit(1);
}
}
}
fn run_fetch_cmd(args: FetchArgs) -> anyhow::Result<()> {
use crate::commands::fetch::{run_fetch, RunFetchOptions};
let client = crate::http::UreqClient::new();
let options = RunFetchOptions {
specs: args.specs,
project_dir: current_dir()?,
quiet: args.quiet,
};
let report = run_fetch(&client, &options);
for line in &report.stdout {
println!("{line}");
}
for line in &report.stderr {
eprintln!("{line}");
}
if report.had_errors {
std::process::exit(1);
}
Ok(())
}
fn run_cache_cmd(args: CacheArgs) -> anyhow::Result<()> {
use crate::store::cache::{
build_cache_gc_model, build_cache_ls_model, cache_clean_legacy, cache_gc, cache_ls,
detect_legacy_layout, format_bytes, parse_duration, CacheGcOptions, CacheKind,
};
use crate::store::resolve_ask_home;
let ask_home = resolve_ask_home();
match args.command {
CacheCommand::Ls(a) => {
let filter = match a.kind.as_deref() {
Some(k) => match CacheKind::parse(k) {
Some(kind) => Some(kind),
None => {
eprintln!(
"Invalid --kind '{k}'. Must be one of: npm, github, web, llms-txt"
);
std::process::exit(1);
}
},
None => None,
};
if a.json {
let model = build_cache_ls_model(&ask_home, filter);
println!("{}", serde_json::to_string_pretty(&model)?);
return Ok(());
}
let entries = cache_ls(&ask_home, filter);
if entries.is_empty() {
eprintln!("No entries in store at {}", ask_home.display());
return Ok(());
}
eprintln!("Store: {}", ask_home.display());
eprintln!(
"{} entr{}:\n",
entries.len(),
if entries.len() == 1 { "y" } else { "ies" }
);
for e in &entries {
println!(
" {}/{} {}",
e.kind.as_str(),
e.key,
format_bytes(e.size_bytes)
);
}
let total: u64 = entries.iter().map(|e| e.size_bytes).sum();
eprintln!("\nTotal: {}", format_bytes(total));
}
CacheCommand::Gc(a) => {
let scan_roots =
std::env::var_os("ASK_GC_SCAN_ROOTS").map(|v| std::env::split_paths(&v).collect());
let older_than = match a.older_than.as_deref() {
Some(raw) => match parse_duration(raw) {
Some(ms) => Some(ms),
None => {
eprintln!(
"Invalid --older-than value '{raw}'. Use format like 30d, 12h, 90m, 60s."
);
std::process::exit(1);
}
},
None => None,
};
let opts = CacheGcOptions {
dry_run: a.dry_run,
scan_roots,
older_than,
silent: a.json,
};
if a.json {
let model = build_cache_gc_model(&ask_home, &opts);
println!("{}", serde_json::to_string_pretty(&model)?);
return Ok(());
}
let result = cache_gc(&ask_home, &opts);
if result.removed.is_empty() {
eprintln!("Store is clean — no unreferenced entries.");
return Ok(());
}
let n = result.removed.len();
let plural = if n == 1 { "y" } else { "ies" };
if a.dry_run {
eprintln!(
"Would remove {n} entr{plural} ({}):",
format_bytes(result.freed_bytes)
);
for e in &result.removed {
println!(
" {}/{} {}",
e.kind.as_str(),
e.key,
format_bytes(e.size_bytes)
);
}
} else {
eprintln!(
"Removed {n} entr{plural}, freed {}.",
format_bytes(result.freed_bytes)
);
}
}
CacheCommand::Clean(a) => {
if !a.legacy {
eprintln!(
"ask cache clean requires a mode. Pass --legacy to remove pre-v2 github store dirs."
);
std::process::exit(1);
}
if !detect_legacy_layout(&ask_home) {
eprintln!(
"No legacy github store detected at {}. Nothing to clean.",
ask_home.display()
);
return Ok(());
}
let removed = cache_clean_legacy(&ask_home);
if removed.is_empty() {
eprintln!("No legacy paths removed.");
return Ok(());
}
eprintln!(
"Removed {} legacy path{}:",
removed.len(),
if removed.len() == 1 { "" } else { "s" }
);
for p in &removed {
println!(" {}", p.display());
}
}
}
Ok(())
}
fn run_search_cmd(args: SearchArgs) -> anyhow::Result<()> {
use crate::commands::resolve_csp::resolve_csp_default;
use crate::commands::search::{run_search, spawn_csp, RunSearchOptions, SearchDeps};
let content: Vec<String> = args
.content
.as_deref()
.filter(|s| !s.is_empty())
.map(|s| {
s.split(',')
.map(|p| p.trim().to_string())
.filter(|p| !p.is_empty())
.collect()
})
.unwrap_or_default();
let top_k = match args.top_k.as_deref().filter(|s| !s.is_empty()) {
Some(raw) => match raw.parse::<u64>() {
Ok(n) => Some(n),
Err(_) => {
eprintln!("ask: ignoring invalid --top-k '{raw}' (not a number)");
None
}
},
None => None,
};
let client = crate::http::UreqClient::new();
let deps = SearchDeps {
checkout: Default::default(),
resolve_csp: &resolve_csp_default,
run_csp: &spawn_csp,
};
let options = RunSearchOptions {
spec: args.spec,
query: args.query,
project_dir: current_dir()?,
no_fetch: args.no_fetch,
content,
top_k,
};
let report = run_search(&client, &options, &deps);
for line in &report.stdout {
println!("{line}");
}
for line in &report.stderr {
eprintln!("{line}");
}
std::process::exit(report.exit_code);
}
fn run_remove_cmd(args: RemoveArgs) -> anyhow::Result<()> {
use crate::commands::remove::{run_remove, RemoveOutcome};
match run_remove(¤t_dir()?, &args.name)? {
RemoveOutcome::NoAskJson => {
eprintln!("No ask.json found — nothing to remove");
}
RemoveOutcome::NoMatch(target) => {
eprintln!("No ask.json entry matches '{target}'");
}
RemoveOutcome::Removed(spec) => {
eprintln!("Removed {spec}");
}
}
Ok(())
}
fn run_docs_cmd(args: DocsArgs) -> anyhow::Result<()> {
use crate::commands::docs::{run_docs, RunDocsOptions};
let client = crate::http::UreqClient::new();
let options = RunDocsOptions {
spec: args.spec,
project_dir: current_dir()?,
no_fetch: args.no_fetch,
json: args.json,
};
match run_docs(&client, &options) {
Ok(run) => {
for w in &run.warnings {
eprintln!("{w}");
}
println!("{}", run.stdout);
Ok(())
}
Err(err) => {
eprintln!("{err}");
std::process::exit(1);
}
}
}
fn run_list(args: ListArgs) -> anyhow::Result<()> {
let model = crate::list::build_list_model(¤t_dir()?);
if args.json {
println!("{}", serde_json::to_string_pretty(&model)?);
} else {
println!("{}", crate::list::format_list(&model));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use clap::CommandFactory;
#[test]
fn cli_definition_is_valid() {
Cli::command().debug_assert();
}
#[test]
fn version_is_the_crate_version() {
assert_eq!(
Cli::command().get_version(),
Some(env!("CARGO_PKG_VERSION"))
);
}
#[test]
fn all_top_level_subcommands_are_present() {
let cmd = Cli::command();
let names: Vec<_> = cmd.get_subcommands().map(|c| c.get_name()).collect();
for expected in [
"install", "add", "remove", "list", "src", "docs", "fetch", "search", "skills", "cache",
] {
assert!(names.contains(&expected), "missing subcommand: {expected}");
}
}
#[test]
fn parses_representative_invocations() {
Cli::try_parse_from(["ask", "install"]).unwrap();
Cli::try_parse_from(["ask", "add", "next", "--docs-paths", "docs,readme"]).unwrap();
Cli::try_parse_from(["ask", "list", "--json"]).unwrap();
Cli::try_parse_from(["ask", "fetch", "npm:next", "github:a/b", "-q"]).unwrap();
Cli::try_parse_from(["ask", "cache", "gc", "--dry-run", "--older-than", "30d"]).unwrap();
Cli::try_parse_from(["ask", "skills", "list", "react"]).unwrap();
Cli::try_parse_from(["ask", "skills", "install", "react", "--agent", "claude"]).unwrap();
Cli::try_parse_from(["ask", "skills", "remove", "react", "--ignore-missing"]).unwrap();
Cli::try_parse_from(["ask", "skills", "react"]).unwrap();
Cli::try_parse_from(["ask", "skills"]).unwrap();
}
}