use crate::skill::{
SkillAction, SkillError, SkillErrorKind, SkillLocation, SkillOptions, SkillReport, SkillScope,
SkillSpec, run_skill_admin,
};
use crate::{
ArgSpec, CliEmitter, CliStop, Combination, CommandSpec, OutputSpec, ResolvedInvocation,
cli_invocation_invalid_event, json_error, json_result,
};
pub const SKILL_CLI_ACTIONS: [&str; 3] = ["skill_status", "skill_install", "skill_uninstall"];
const SCOPES: [(&str, SkillScope); 2] = [
("personal", SkillScope::Personal),
("workspace", SkillScope::Workspace),
];
#[derive(Clone, Copy)]
struct Verb {
command: &'static str,
action: SkillAction,
takes_force: bool,
}
const VERBS: [Verb; 3] = [
Verb {
command: "status",
action: SkillAction::Status,
takes_force: false,
},
Verb {
command: "install",
action: SkillAction::Install,
takes_force: true,
},
Verb {
command: "uninstall",
action: SkillAction::Uninstall,
takes_force: true,
},
];
#[must_use]
pub fn skill_cli_commands(spec: &SkillSpec, output: &OutputSpec) -> Vec<CommandSpec> {
let mut commands = vec![CommandSpec::new(["skill"]).about(format!(
"Manage the {} skill. By default it uses the standard folders agents read skills from: the shared .agents/skills, .claude/skills, and, for personal scope, .gemini/config/skills. For an agent that reads only a folder of its own, pass that folder as --skills-dir",
spec.title
))];
commands.extend(VERBS.iter().map(|verb| verb_command(spec, *verb, output)));
commands
}
fn verb_command(spec: &SkillSpec, verb: Verb, output: &OutputSpec) -> CommandSpec {
let (about, shape_verb) = match verb.action {
SkillAction::Status => (
format!(
"Report whether the {} skill is installed, valid, and current",
spec.title
),
"Report on",
),
SkillAction::Install => (format!("Install the {} skill", spec.title), "Install into"),
SkillAction::Uninstall => (
format!(
"Remove the {} skill that {} installed",
spec.title, spec.marker_slug
),
"Remove from",
),
};
let action = action_id(verb.action);
let mut command = CommandSpec::new(["skill", verb.command])
.about(about)
.arg(
ArgSpec::option_enum("--scope", SCOPES.iter().map(|(name, _)| *name))
.value_name("SCOPE")
.default("personal")
.about("Standard folders under the home directory (personal) or the current directory (workspace)"),
)
.arg(
ArgSpec::option("--skills-dir", "PATH")
.about("One skills directory to use instead of the standard folders"),
);
let mut standard_optional = vec!["scope"];
let mut directory_optional = Vec::new();
if verb.takes_force {
command = command.arg(ArgSpec::flag("--force").about(format!(
"Overwrite or remove a skill at the target path that {} did not install",
spec.marker_slug
)));
standard_optional.push("force");
directory_optional.push("force");
}
command
.combination(
Combination::new(format!("skill-{}-standard", verb.command))
.action(action)
.about(format!("{shape_verb} the standard skill folders"))
.optional(standard_optional)
.output(output.clone()),
)
.combination(
Combination::new(format!("skill-{}-directory", verb.command))
.action(action)
.about(format!("{shape_verb} one skills directory"))
.required(["skills_dir"])
.optional(directory_optional)
.output(output.clone()),
)
}
fn action_id(action: SkillAction) -> &'static str {
match action {
SkillAction::Status => SKILL_CLI_ACTIONS[0],
SkillAction::Install => SKILL_CLI_ACTIONS[1],
SkillAction::Uninstall => SKILL_CLI_ACTIONS[2],
}
}
#[derive(Clone, Debug)]
pub struct SkillCliRequest {
action: SkillAction,
options: SkillOptions,
}
impl SkillCliRequest {
pub fn from_invocation(invocation: &ResolvedInvocation) -> Result<Self, CliStop> {
let action_id = invocation.action_id();
let verb = VERBS
.iter()
.find(|verb| self::action_id(verb.action) == action_id)
.ok_or_else(|| defect(&format!("action `{action_id}` is not a skill action")))?;
let action = verb.action;
let location = if invocation.declares("skills_dir") {
SkillLocation::Directory(invocation.text("skills_dir")?.to_string())
} else {
SkillLocation::Standard(
lookup(&SCOPES, invocation.text("scope")?, "--scope")
.map_err(|detail| defect(&detail))?,
)
};
let force = invocation.declares("force") && invocation.flag("force")?;
Ok(Self {
action,
options: SkillOptions { location, force },
})
}
#[must_use]
pub const fn action(&self) -> SkillAction {
self.action
}
#[must_use]
pub const fn options(&self) -> &SkillOptions {
&self.options
}
#[must_use]
pub fn execute(&self, spec: &SkillSpec) -> SkillCliOutcome {
SkillCliOutcome {
result: run_skill_admin(spec, self.action, &self.options),
}
}
pub fn run<W: std::io::Write>(&self, spec: &SkillSpec, emitter: &mut CliEmitter<W>) -> u8 {
self.execute(spec).emit(emitter)
}
}
#[derive(Debug)]
pub struct SkillCliOutcome {
result: Result<SkillReport, SkillError>,
}
impl SkillCliOutcome {
#[must_use]
pub fn report(&self) -> Option<&SkillReport> {
self.result.as_ref().ok()
}
#[must_use]
pub fn error(&self) -> Option<&SkillError> {
self.result.as_ref().err()
}
pub fn emit<W: std::io::Write>(self, emitter: &mut CliEmitter<W>) -> u8 {
match self.result {
Ok(report) => match serde_json::to_value(&report) {
Ok(value) => emitter.finish(json_result(value).build(), 0),
Err(error) => emitter.finish(
build_error(json_error(
"skill_report_serialization_failed",
&format!("failed to serialize the skill report: {error}"),
)),
1,
),
},
Err(error) => {
let status = match error.kind {
SkillErrorKind::Usage => 2,
_ => 1,
};
emitter.finish(skill_error_event(&error), status)
}
}
}
}
fn defect(detail: &str) -> CliStop {
CliStop::new(cli_invocation_invalid_event(detail), 1)
}
fn lookup<T: Copy>(table: &[(&str, T)], value: &str, flag: &str) -> Result<T, String> {
table
.iter()
.find(|(name, _)| *name == value)
.map(|(_, item)| *item)
.ok_or_else(|| format!("{flag} value `{value}` is not registered"))
}
fn skill_error_event(error: &SkillError) -> crate::Event {
let mut builder =
json_error(error.kind.code(), &error.message).hint_if_some(error.hint.as_deref());
if let Some(report) = error.partial_report.as_ref()
&& let Ok(value) = serde_json::to_value(report)
{
builder = builder.field("partial_report", value);
}
build_error(builder)
}
fn build_error(builder: crate::ErrorBuilder) -> crate::Event {
builder
.build()
.unwrap_or_else(|_| cli_invocation_invalid_event("could not construct the skill error"))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{CliOutcome, CliSpec, build_afdata_cli};
const SPEC: SkillSpec = SkillSpec {
name: "agent-first-widget",
source: "---\nname: agent-first-widget\ndescription: Widgets.\n---\n",
title: "Agent-First Widget",
marker_slug: "afwidget",
assets: &[],
};
fn cli() -> crate::BuiltCliSpec {
let output = OutputSpec::protocol_finite(["json"], ["split"], "json", "split");
let mut spec = CliSpec::new("afwidget", "1.0.0")
.lifecycle_output(output.clone())
.command(CommandSpec::root());
for command in skill_cli_commands(&SPEC, &output) {
spec = spec.command(command);
}
match build_afdata_cli(spec) {
Ok(cli) => cli,
Err(error) => panic!("skill commands must build: {error}"),
}
}
fn resolve(argv: &[&str]) -> Result<(SkillAction, SkillOptions), String> {
let mut full = vec!["afwidget"];
full.extend_from_slice(argv);
match cli().resolve_from(full) {
Ok(CliOutcome::Run(invocation)) => SkillCliRequest::from_invocation(&invocation)
.map(|request| (request.action, request.options))
.map_err(|stop| format!("{:?}", stop.event())),
Ok(_) => Err("not a run".to_string()),
Err(error) => Err(error.rule.code().to_string()),
}
}
#[test]
fn every_action_is_registered_once() {
let handlers = SKILL_CLI_ACTIONS.map(|action| {
(
action,
(|_: &ResolvedInvocation| Ok(())) as crate::CliHandler<()>,
)
});
assert!(cli().bind_actions(handlers).is_ok());
}
#[test]
fn defaults_reach_the_personal_standard_folders() {
match resolve(&["skill", "status"]) {
Ok((action, options)) => {
assert_eq!(action, SkillAction::Status);
assert_eq!(
options.location,
SkillLocation::Standard(SkillScope::Personal)
);
assert!(!options.force);
}
Err(error) => panic!("status must resolve: {error}"),
}
}
#[test]
fn every_registered_scope_translates() {
for (name, scope) in SCOPES {
match resolve(&["skill", "install", "--scope", name, "--force"]) {
Ok((action, options)) => {
assert_eq!(action, SkillAction::Install);
assert_eq!(options.location, SkillLocation::Standard(scope));
assert!(options.force);
}
Err(error) => panic!("--scope {name} must resolve: {error}"),
}
}
}
#[test]
fn serialized_names_are_the_cli_values() {
for (name, scope) in SCOPES {
let value = serde_json::to_value(scope).ok();
assert_eq!(value.as_ref().and_then(|value| value.as_str()), Some(name));
}
for verb in VERBS {
let value = serde_json::to_value(verb.action).ok();
assert_eq!(
value.as_ref().and_then(|value| value.as_str()),
Some(verb.command)
);
}
}
#[test]
fn skills_dir_is_its_own_shape_without_scope() {
for verb in VERBS {
let args = ["skill", verb.command, "--skills-dir", "/tmp/skills"];
let (action, options) = resolve(&args).expect("directory target resolves");
assert_eq!(action, verb.action);
assert_eq!(
options.location,
SkillLocation::Directory("/tmp/skills".to_string())
);
let mut with_scope = args.to_vec();
with_scope.extend(["--scope", "personal"]);
assert!(resolve(&with_scope).is_err());
}
assert!(resolve(&["skill", "install", "--agent", "codex"]).is_err());
}
fn request(argv: &[&str]) -> SkillCliRequest {
let mut full = vec!["afwidget"];
full.extend_from_slice(argv);
match cli().resolve_from(full) {
Ok(CliOutcome::Run(invocation)) => {
match SkillCliRequest::from_invocation(&invocation) {
Ok(request) => request,
Err(stop) => panic!("{argv:?} did not read: {:?}", stop.event()),
}
}
Ok(_) => panic!("{argv:?} is not a run"),
Err(error) => panic!("{argv:?} failed to resolve: {}", error.message),
}
}
#[test]
fn execute_reports_without_emitting() {
let dir = std::env::temp_dir().join(format!("afdata_skill_cli_{}", std::process::id()));
let dir_text = dir.to_string_lossy().to_string();
let install = request(&["skill", "install", "--skills-dir", &dir_text]);
assert_eq!(install.action(), SkillAction::Install);
assert_eq!(
install.options().location,
SkillLocation::Directory(dir_text.clone())
);
let installed = install.execute(&SPEC);
assert!(matches!(
installed.report(),
Some(SkillReport::Install { .. })
));
assert!(installed.error().is_none());
let unmanaged = dir.join("agent-first-widget").join("SKILL.md");
assert!(
std::fs::write(
&unmanaged,
"---\nname: agent-first-widget\ndescription: Mine.\n---\n"
)
.is_ok()
);
let refused = install.execute(&SPEC);
assert!(refused.report().is_none());
assert_eq!(
refused.error().map(|error| error.kind),
Some(SkillErrorKind::Refused)
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn status_rejects_force() {
assert!(resolve(&["skill", "status", "--force"]).is_err());
}
}