use crate::skill::{
SkillAction, SkillAgentSelection, SkillError, SkillErrorKind, 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 EVERY_AGENT: &str = "all";
const AGENTS: [(&str, SkillAgentSelection); 4] = [
("codex", SkillAgentSelection::Codex),
("claude-code", SkillAgentSelection::ClaudeCode),
("opencode", SkillAgentSelection::Opencode),
("hermes", SkillAgentSelection::Hermes),
];
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 for Codex, Claude Code, opencode, and Hermes",
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(
"--agent",
std::iter::once(EVERY_AGENT).chain(AGENTS.iter().map(|(name, _)| *name)),
)
.value_name("AGENT")
.default(EVERY_AGENT)
.about("Target agent"),
)
.arg(
ArgSpec::option_enum("--scope", SCOPES.iter().map(|(name, _)| *name))
.value_name("SCOPE")
.default("personal")
.about("Skill scope"),
)
.arg(
ArgSpec::option("--skills-dir", "PATH")
.about("Explicit skills directory; only valid with one named agent"),
);
let mut every_optional = vec!["scope"];
let mut named_optional = vec!["scope", "skills_dir"];
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
)));
every_optional.push("force");
named_optional.push("force");
}
command
.combination(
Combination::new(format!("skill-{}-all", verb.command))
.action(action)
.about(format!("{shape_verb} every agent that supports the scope"))
.fixed("agent", EVERY_AGENT)
.optional(every_optional)
.output(output.clone()),
)
.combination(
Combination::new(format!("skill-{}-agent", verb.command))
.action(action)
.about(format!(
"{shape_verb} one named agent; only this shape accepts --skills-dir"
))
.fixed_one_of("agent", AGENTS.iter().map(|(name, _)| *name))
.optional(named_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 agent_name = invocation.text("agent")?;
let agent = if agent_name == EVERY_AGENT {
SkillAgentSelection::All
} else {
lookup(&AGENTS, agent_name, "--agent").map_err(|detail| defect(&detail))?
};
let scope = lookup(&SCOPES, invocation.text("scope")?, "--scope")
.map_err(|detail| defect(&detail))?;
let skills_dir = if invocation.declares("skills_dir") {
invocation.optional_text("skills_dir")?.map(str::to_string)
} else {
None
};
let force = invocation.declares("force") && invocation.flag("force")?;
Ok(Self {
action,
options: SkillOptions {
agent,
scope,
skills_dir,
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_every_personal_agent() {
match resolve(&["skill", "status"]) {
Ok((action, options)) => {
assert_eq!(action, SkillAction::Status);
assert_eq!(options.agent, SkillAgentSelection::All);
assert_eq!(options.scope, SkillScope::Personal);
assert_eq!(options.skills_dir, None);
assert!(!options.force);
}
Err(error) => panic!("status must resolve: {error}"),
}
}
#[test]
fn every_registered_agent_translates() {
for (name, selection) in AGENTS {
match resolve(&["skill", "install", "--agent", name, "--force"]) {
Ok((action, options)) => {
assert_eq!(action, SkillAction::Install);
assert_eq!(options.agent, selection);
assert!(options.force);
}
Err(error) => panic!("--agent {name} must resolve: {error}"),
}
}
}
#[test]
fn serialized_names_are_the_cli_values() {
let every = serde_json::to_value(SkillAgentSelection::All).ok();
assert_eq!(
every.as_ref().and_then(|value| value.as_str()),
Some(EVERY_AGENT)
);
for (name, selection) in AGENTS {
let value = serde_json::to_value(selection).ok();
assert_eq!(value.as_ref().and_then(|value| value.as_str()), Some(name));
}
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_needs_one_named_agent() {
assert!(resolve(&["skill", "install", "--skills-dir", "/tmp/skills"]).is_err());
match resolve(&[
"skill",
"uninstall",
"--agent",
"codex",
"--scope",
"workspace",
"--skills-dir",
"/tmp/skills",
]) {
Ok((action, options)) => {
assert_eq!(action, SkillAction::Uninstall);
assert_eq!(options.scope, SkillScope::Workspace);
assert_eq!(options.skills_dir.as_deref(), Some("/tmp/skills"));
}
Err(error) => panic!("one named agent accepts --skills-dir: {error}"),
}
}
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",
"--agent",
"codex",
"--skills-dir",
&dir_text,
]);
assert_eq!(install.action(), SkillAction::Install);
assert_eq!(
install.options().skills_dir.as_deref(),
Some(dir_text.as_str())
);
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());
}
}